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,
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With