J-Mose J-Mose - 1 month ago 19x
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 ||

My command is a classic console command that extends ContainerAwareCommand

Best regards,


You can programatically authenticate a user in Symfony2 like this:

// create the authentication token
$token = new UsernamePasswordToken(
// give it to the security context

EDIT based on comment:

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


thanks andrea-sprega