SwitchUserToken example

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Tests\Authentication\Token\Fixtures\CustomUser;
use Symfony\Component\Security\Core\User\InMemoryUser;

class SwitchUserTokenTest extends TestCase
{
    public function testSerialize()
    {
        $originalToken = new UsernamePasswordToken(new InMemoryUser('user', 'foo', ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH']), 'provider-key', ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH']);
        $token = new SwitchUserToken(new InMemoryUser('admin', 'bar', ['ROLE_USER']), 'provider-key', ['ROLE_USER']$originalToken, 'https://symfony.com/blog');

        $unserializedToken = unserialize(serialize($token));

        $this->assertInstanceOf(SwitchUserToken::class$unserializedToken);
        $this->assertSame('admin', $unserializedToken->getUserIdentifier());
        $this->assertSame('provider-key', $unserializedToken->getFirewallName());
        $this->assertEquals(['ROLE_USER']$unserializedToken->getRoleNames());
        $this->assertSame('https://symfony.com/blog', $unserializedToken->getOriginatedFromUri());

        $unserializedOriginalToken = $unserializedToken->getOriginalToken();

        
/** * Tests the SwitchUserTokenProcessor. * * @author Igor Timoshenko <igor.timoshenko@i.ua> */
class SwitchUserTokenProcessorTest extends TestCase
{
    public function testProcessor()
    {
        $originalToken = new UsernamePasswordToken(new InMemoryUser('original_user', 'password', ['ROLE_SUPER_ADMIN']), 'provider', ['ROLE_SUPER_ADMIN']);
        $switchUserToken = new SwitchUserToken(new InMemoryUser('user', 'passsword', ['ROLE_USER']), 'provider', ['ROLE_USER']$originalToken);
        $tokenStorage = $this->createMock(TokenStorageInterface::class);
        $tokenStorage->method('getToken')->willReturn($switchUserToken);

        $processor = new SwitchUserTokenProcessor($tokenStorage);
        $record = RecordFactory::create();
        $record = $processor($record);

        $expected = [
            'impersonator_token' => [
                'authenticated' => true,
                'roles' => ['ROLE_SUPER_ADMIN'],
                
$this->assertTrue($collector->supportsRoleHierarchy());
        $this->assertSame($normalizedRoles$collector->getRoles()->getValue(true));
        $this->assertSame($inheritedRoles$collector->getInheritedRoles()->getValue(true));
        $this->assertSame('hhamon', $collector->getUser());
    }

    public function testCollectSwitchUserToken()
    {
        $adminToken = new UsernamePasswordToken(new InMemoryUser('yceruto', 'P4$$w0rD', ['ROLE_ADMIN']), 'provider', ['ROLE_ADMIN']);

        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken(new SwitchUserToken(new InMemoryUser('hhamon', 'P4$$w0rD', ['ROLE_USER', 'ROLE_PREVIOUS_ADMIN']), 'provider', ['ROLE_USER', 'ROLE_PREVIOUS_ADMIN']$adminToken));

        $collector = new SecurityDataCollector($tokenStorage$this->getRoleHierarchy(), null, null, null, null, true);
        $collector->collect(new Request()new Response());
        $collector->lateCollect();

        $this->assertTrue($collector->isEnabled());
        $this->assertTrue($collector->isAuthenticated());
        $this->assertTrue($collector->isImpersonated());
        $this->assertSame('yceruto', $collector->getImpersonatorUser());
        $this->assertSame(SwitchUserToken::class$collector->getTokenClass()->getValue());
        $this->assertTrue($collector->supportsRoleHierarchy());
        
throw $exception;
        }

        $this->logger?->info('Attempting to switch to user.', ['username' => $username]);

        $this->userChecker->checkPostAuth($user);

        $roles = $user->getRoles();
        $roles[] = 'ROLE_PREVIOUS_ADMIN';
        $originatedFromUri = str_replace('/&', '/?', preg_replace('#[&?]'.$this->usernameParameter.'=[^&]*#', '', $request->getRequestUri()));
        $token = new SwitchUserToken($user$this->firewallName, $roles$token$originatedFromUri);

        if (null !== $this->dispatcher) {
            $switchEvent = new SwitchUserEvent($request$token->getUser()$token);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            // use the token from the event in case any listeners have replaced it.             $token = $switchEvent->getToken();
        }

        return $token;
    }

    
$this->tokenStorage->setToken($token);
        $this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);

        $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener($this->event);
    }

    public function testExitUserUpdatesToken()
    {
        $originalToken = new UsernamePasswordToken(new InMemoryUser('username', '', []), 'key', []);
        $this->tokenStorage->setToken(new SwitchUserToken(new InMemoryUser('username', '', ['ROLE_USER']), 'key', ['ROLE_USER']$originalToken));

        $this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);

        $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener($this->event);

        $this->assertSame([]$this->request->query->all());
        $this->assertSame('', $this->request->server->get('QUERY_STRING'));
        $this->assertInstanceOf(RedirectResponse::class$this->event->getResponse());
        $this->assertSame($this->request->getUri()$this->event->getResponse()->getTargetUrl());
        $this->assertSame($originalToken$this->tokenStorage->getToken());
    }
Home | Imprint | This part of the site doesn't use cookies.