PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 28, 2021

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

 December 28, 2021     php, symfony     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing