J-Mose J-Mose - 2 months ago 32
PHP Question

Symfony 2 - Simulate login and security context in console command

I am currently coding a custom console command on Symfony2.

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,
J

Answer

You can programatically authenticate a user in Symfony2 like this:

// create the authentication token
$token = new UsernamePasswordToken(
    $user,
    null,
    'main',
    $user->getRoles());
// give it to the security context
$this->container->get('security.context')->setToken($token);

EDIT based on comment:

  • Security context is deprecated as of Symfony 2.6. Use this instead:

$this->container->get('security.token_storage')->setToken($t‌​oken);

thanks andrea-sprega

Comments