Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony - Simulate login and security context in console command

Tags:

php

symfony

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,

like image 597
j-guyon Avatar asked Mar 24 '14 10:03

j-guyon


1 Answers

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);
    }
}
like image 103
Thomas Dulcamara Avatar answered Sep 22 '22 16:09

Thomas Dulcamara