Skip to content

Login a user in a programatic way is no longer possible using Guard and anonymous: lazy #36208

@tristanbes

Description

@tristanbes

Hello :)

Symfony version(s) affected: v4.4.5

Description
Login in programatic way a user with anonymous: lazy breaks the behaviour; The user is logged, but the next request, when he's redirected to the homepage, he's not (back to anon.);

How to reproduce

public function programaticLogIn(Request $request) 
{
    $user = ....;
    $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
    $response = RedirectResponse($this->generateUrl('home'));

    // `@security.authentication.rememberme.services.simplehash.main`
    $rememberMeService->loginSuccess($request, $response, $token);

    $this->guardAuthenticatorHandler->authenticateWithToken($token, $request, 'main');

    return $response;
}

public function homeAction()
{
    dump($this->getUser())
    // outputs null when using `anonymous: lazy`
    // outputs the right user when using ``anonymous: true`
}

Possible Solution
Only changing anonymous: lazy to anonymous: true fixes the behaviour and the user is correctly logged in when he's redirected to the homepage.

Additional context
My wild guess is related to this bug: #34614
And this PR had me on a lead: #34627

Nicolas fixed it but it seems that the scenario where user are logged in a programatic way is not concerned by this fixed as guard supports methods does not match anything since it's a programmatic login.

For reference:

// security.yml
firewalls:
        main:
            pattern: ^/
            anonymous: lazy
            stateless: false
            user_checker: App\Security\UserChecker

            remember_me:
                secret: '%env(APP_SECRET)%'
                lifetime: 7776000
                path:     /

            logout:
                path: logout
                target: homepage_localized

            switch_user: true
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
                    - App\Security\DiscordAuthenticator
                    - App\Security\FacebookAuthenticator
                    - App\Security\GoogleAuthenticator
                    - App\Security\TwitchAuthenticator
                entry_point: App\Security\LoginFormAuthenticator

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions