How to hook into user authentication? I have a 2FA option that users can enable. I am currently writing API layer where I want to preserve this functionality but so far I haven't been able to find a point where I can hook into authentication. The \Drupal\user\UserAuth does not invoke any hooks or events so I am wondering if the only solution is to completely swap the user.auth service for a custom implementation?

PS: my thinking is that if the 2FA is enabled, I would be checking a custom header.
I'm assuming this is Drupal 8 so my answer is for Drupal 8.

You need to do two things:


Create a service provider in your custom module that extends ServiceProviderBase.  The name of this class must be your module name, in camel case, plus "ServiceProvider", i.e. MyUserAuthenticationModuleServiceProvider.  Then, implement the alter function which sets the class for the user.auth service, like this:



    public function alter(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('user.auth');
        $definition- >setClass('Drupal\my_module\AuthenticationClass');
    }



The class you specify in the call to setClass above has to extend \Drupal\user\UserAuth and implement the following function, which returns true/false based on successful authentication


public function authenticate($username, $password)