lexik / LexikJWTAuthenticationBundle

JWT authentication for your Symfony API
MIT License
2.53k stars 610 forks source link

Login programmatically does not work #1113

Open darkopetreski opened 1 year ago

darkopetreski commented 1 year ago

As described in the official documentation https://symfony.com/doc/current/security.html#login-programmatically I am trying to login a user automatically as suggested in the official documentation for Symfony 6.2:

    use Symfony\Bundle\SecurityBundle\Security;

    public function autoLogin(Security $security): Response 
    {
        $user = ....
        $security->login($user);
        ....
    }

But I get the following error:

"Lexik\\Bundle\\JWTAuthenticationBundle\\Security\\Authenticator\\Token\\JWTPostAuthenticationToken::__construct(): 
Argument #4 ($token) must be of type string, null given, called in 
/project/vendor/lexik/jwt-authentication-bundle/Security/Authenticator/JWTAuthenticator.php on line 272"

I am using this bundle with cookie token extractor. The login method was introduced in 6.2 so maybe this bundle is not compatible with this method or more setup is needed ?

darkopetreski commented 1 year ago

For now I have solved the problem by the following code:

    use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler;

    #[Route('/autologin', methods: ['GET'])]
    public function autologin(AuthenticationSuccessHandler $authenticationSuccessHandler): Response 
    {
        $user = ....
        return $authenticationSuccessHandler->handleAuthenticationSuccess($user);
    }
BooleanType commented 1 year ago

Had the same. @darkopetreski approach works for me too and is even described in bundle's documentation:

public function fooAction(UserInterface $user)
{
    $authenticationSuccessHandler = $this->container->get('lexik_jwt_authentication.handler.authentication_success');

    return $authenticationSuccessHandler->handleAuthenticationSuccess($user);
}

Hope login programmatically will work with $security->login($user); as well one day.

chalasr commented 4 months ago

Thanks for the issue. https://github.com/symfony/symfony/pull/57495 will help