Symfony Manually Log User In

A page exists where a user entity is created (this is outside of the normal registration flow).

When the user is created they should be logged in, a guardHandler is used with an authenticator as shown below.

use AppSecurityFakeAuthenticator;
use SymfonyComponentSecurityGuardGuardAuthenticatorHandler;

        $response = $guardHandler->authenticateUserAndHandleSuccess(
                $user, // the User object you just created
                $request,
                $authenticator, // authenticator whose onAuthenticationSuccess you want to use
                'main'          // the name of your firewall in security.yaml
        );

However the authenticator is a mess, it has only been created for the one method onAuthenticationSuccess.

use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;

class FakeAuthenticator extends AbstractGuardAuthenticator
{
    public function supports(Request $request)
    {
    return false;
    }

    public function getCredentials(Request $request)
    {
    throw new RuntimeException('Unreachable code');
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
    throw new RuntimeException('Unreachable code');
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
    throw new RuntimeException('Unreachable code');
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {

    return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
    throw new RuntimeException('Unreachable code');
    }

    public function start(Request $request, AuthenticationException $authException = null)
    {
    throw new RuntimeException('Unreachable code');
    }

    public function supportsRememberMe()
    {
    return true;
    }
}

Lots of methods have to be implemented because the method handleAuthenticationSuccess expects a class which implements AuthenticatorInterface.

The code works and the user is logged in but it doesn’t feel like the cleanest solution, is there another way to log in a user?

FosUserBundle is being used in the project and the following does work, but I am unsure if calling methods on loginManager is supported, I can’t find anything in the documentation and I don’t want my code to be depend on a feature that could change.

FOSUserBundleSecurityLoginManagerInterface::logInUser('main', $user, $response);

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *