Disable Magento 2 Two Factor Authentication For Specific User

With the extensive custom database, you always have to go to extra mile to improve Magento admin security. Two-factor authentication is one of those tiny security steps you have to take to avoid any security loopholes and data leaks. 

Correspondingly it is an additional layer of security beyond credentials and reCAPTCHA every user attempting to log in goes through.

Though it is not recommended to disable 2FA in Magento, there are some exceptions. You can disable it if the store is in the development or testing stage. 

Still, you don't have to disable two-factor authentication completely, you can do this for a specific user. And we know how.

To disable Two-factor authentication in Magento for a specific user:

1. Create a etc/di.xml file in your custom module:

<?xml version="1.0" ?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\TwoFactorAuth\Model\TfaSession">
<plugin name="Magento_TwoFactorAuthCustom_Plugin_Magento_TwoFactorAuth_Model_TfaSession" type="Magento\TwoFactorAuthCustom\Plugin\Magento\TwoFactorAuth\Model\TfaSession" sortOrder="10" disabled="false"/>

2. Create a plugin file Plugin/Magento/TwoFactorAuth/Model/TfaSession.php:


namespace Magento\TwoFactorAuthCustom\Plugin\Magento\TwoFactorAuth\Model;
use Magento\Authorization\Model\UserContextInterface;
class TfaSession
   private $allowedUserIds = [
       30, //some admin user id
11 //some other admin user id
   public function __construct
       UserContextInterface $userContext
   ) {
       $this->userContext = $userContext;
   }     public function afterIsGranted(\Magento\TwoFactorAuth\Model\TfaSession $subject, $result)
      return (in_array($this->userContext->getUserId(), $this->allowedUserIds)) ? true : $result;

In this example, we have disabled a 2F authentication for users with IDs 30 and 11. So all that you need to do is add your user IDs in the array $allowedUserIds;.

And this is what the extension structure should look like:

Disable 2F Authentication in Magento 2

Disabling Magento 2F Authentication for the specific user comes in handy. But isn't an ultimate practice for a secure Magento environment. So once testing is done it's better to enable it back. 

You can download Magento_TwoFactorAuthCustom module here.