Tuesday, December 28, 2021

[FIXED] Symfony - Simulate login and security context in console command

Issue

I am currently coding a custom console command on Symfony (2+).

My command call one service that use the security context with dependency injection (check role).

In order to keep that security check in my service, i would like to create a specific user and log this user in my console command.

How can i simulate that login and have a usable security context in my command ?

My service check :

if ($this->securityContext->getToken() == null ||
    !$this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')
)

My command is a classic console command that extends ContainerAwareCommand

Best regards,


Solution

To complete the previous answer, this is the right way for Symfony 5.

class LoginProvider
{
    private TokenStorageInterface $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function login(User $user): void
    {
        $token = new UsernamePasswordToken(
            $user,
            $user->getEmail(),   // Your $credentials
            'main',
            $user->getRoles()    // Don't forget
        );

        $this->tokenStorage->setToken($token);
    }

    public function logout(): void
    {
        $this->tokenStorage->setToken(null);
    }
}


Answered By - Thomas Dulcamara

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.