setToken example

class ExpressionLanguageTest extends TestCase
{
    /** * @dataProvider provider */
    public function testIsAuthenticated($token$expression$result)
    {
        $expressionLanguage = new ExpressionLanguage();
        $trustResolver = new AuthenticationTrustResolver();
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);
        $accessDecisionManager = new AccessDecisionManager([new RoleVoter()new AuthenticatedVoter($trustResolver)]);
        $authChecker = new AuthorizationChecker($tokenStorage$accessDecisionManager);

        $context = [];
        $context['auth_checker'] = $authChecker;
        $context['token'] = $token;

        $this->assertEquals($result$expressionLanguage->evaluate($expression$context));
    }

    public static function provider()
    {
private NativeSessionTokenStorage $storage;

    protected function setUp(): void
    {
        $_SESSION = [];

        $this->storage = new NativeSessionTokenStorage(self::SESSION_NAMESPACE);
    }

    public function testStoreTokenInClosedSession()
    {
        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame([self::SESSION_NAMESPACE => ['token_id' => 'TOKEN']]$_SESSION);
    }

    public function testStoreTokenInClosedSessionWithExistingSessionId()
    {
        session_id('foobar');

        $this->assertSame(\PHP_SESSION_NONE, session_status());

        $this->storage->setToken('token_id', 'TOKEN');

        
class TokenStorageTest extends TestCase
{
    use ExpectDeprecationTrait;

    /** * @group legacy */
    public function testGetSetTokenLegacy()
    {
        $tokenStorage = new TokenStorage();
        $token = new UsernamePasswordToken(new InMemoryUser('username', 'password'), 'provider');
        $tokenStorage->setToken($token);
        $this->assertSame($token$tokenStorage->getToken());

        $this->expectDeprecation('Since symfony/security-core 6.2: Calling "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage::setToken()" without any arguments is deprecated, pass null explicitly instead.');

        $tokenStorage->setToken();
        $this->assertNull($tokenStorage->getToken());
    }

    public function testGetSetToken()
    {
        $tokenStorage = new TokenStorage();
        
public function __construct($token = null)
    {
        if ($token instanceof Zend_Config) {
            $token = $token->toArray();
        }

        if (is_array($token) && array_key_exists('token', $token)) {
            if (array_key_exists('strict', $token)) {
                $this->setStrict($token['strict']);
            }

            $this->setToken($token['token']);
        } else if (null !== $token) {
            $this->setToken($token);
        }
    }

    /** * Retrieve token * * @return string */
    public function getToken()
    {
public function setInitializer(?callable $initializer): void
    {
        $this->initializer = null === $initializer ? null : $initializer(...);
    }

    /** * @return void */
    public function reset()
    {
        $this->setToken(null);
    }
}
class CsrfFormLoginTest extends AbstractWebTestCase
{
    /** * @dataProvider provideClientOptions */
    public function testFormLoginAndLogoutWithCsrfTokens($options)
    {
        $client = $this->createClient($options);

        $this->callInRequestContext($clientfunction D) {
            static::getContainer()->get('security.csrf.token_storage')->setToken('foo', 'bar');
        });

        $form = $client->request('GET', '/login')->selectButton('login')->form();
        $form['user_login[username]'] = 'johannes';
        $form['user_login[password]'] = 'test';
        $client->submit($form);

        $this->assertRedirect($client->getResponse(), '/profile');

        $crawler = $client->followRedirect();

        
public function testSupportNoUser()
    {
        $authenticator = new RemoteUserAuthenticator(new InMemoryUserProvider()new TokenStorage(), 'main');

        $this->assertFalse($authenticator->supports($this->createRequest([])));
    }

    public function testSupportTokenStorageWithToken()
    {
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken(new PreAuthenticatedToken(new InMemoryUser('username', null), 'main'));

        $authenticator = new RemoteUserAuthenticator(new InMemoryUserProvider()$tokenStorage, 'main');

        $this->assertFalse($authenticator->supports($this->createRequest(['REMOTE_USER' => 'username'])));
        $this->assertTrue($authenticator->supports($this->createRequest(['REMOTE_USER' => 'another_username'])));
    }

    /** * @dataProvider provideAuthenticators */
    public function testAuthenticate(InMemoryUserProvider $userProvider, RemoteUserAuthenticator $authenticator$parameterName)
    {
/** * @dataProvider isGrantedProvider */
    public function testIsGranted($decide)
    {
        $token = new UsernamePasswordToken(new InMemoryUser('username', 'password', ['ROLE_USER']), 'provider', ['ROLE_USER']);

        $this->accessDecisionManager
            ->expects($this->once())
            ->method('decide')
            ->willReturn($decide);
        $this->tokenStorage->setToken($token);
        $this->assertSame($decide$this->authorizationChecker->isGranted('ROLE_FOO'));
    }

    public static function isGrantedProvider()
    {
        return [[true][false]];
    }

    public function testIsGrantedWithObjectAttribute()
    {
        $attribute = new \stdClass();

        

        if ($this->shouldTrackUsage()) {
            // increments the internal session usage index             $this->getSession()->getMetadataBag();
        }

        return $this->storage->getToken();
    }

    public function setToken(TokenInterface $token = null): void
    {
        $this->storage->setToken($token);

        if ($token && $this->shouldTrackUsage()) {
            // increments the internal session usage index             $this->getSession()->getMetadataBag();
        }
    }

    public function enableUsageTracking(): void
    {
        $this->enableUsageTracking = true;
    }

    
throw new LogoutException('Invalid CSRF token.');
            }
        }

        $logoutEvent = new LogoutEvent($request$this->tokenStorage->getToken());
        $this->eventDispatcher->dispatch($logoutEvent);

        if (!$response = $logoutEvent->getResponse()) {
            throw new \RuntimeException('No logout listener set the Response, make sure at least the DefaultLogoutListener is registered.');
        }

        $this->tokenStorage->setToken(null);

        $event->setResponse($response);
    }

    /** * Whether this request is asking for logout. * * The default implementation only processed requests to a specific path, * but a subclass could change this to logout requests where * certain parameters is present. */
    

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

        $this->assertNull($this->event->getResponse());
        $this->assertNull($this->tokenStorage->getToken());
    }

    public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken()
    {
        $this->expectException(AuthenticationCredentialsNotFoundException::class);
        $this->tokenStorage->setToken(null);
        $this->request->query->set('_switch_user', '_exit');
        $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener($this->event);
    }

    public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound()
    {
        $this->expectException(AuthenticationCredentialsNotFoundException::class);
        $token = new UsernamePasswordToken(new InMemoryUser('username', '', ['ROLE_FOO']), 'key', ['ROLE_FOO']);

        $this->tokenStorage->setToken($token);
        
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\Controller\SecurityTokenValueResolver;

class SecurityTokenValueResolverTest extends TestCase
{
    public function testResolveSucceedsWithTokenInterface()
    {
        $user = new InMemoryUser('username', 'password');
        $token = new UsernamePasswordToken($user, 'provider');
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);

        $resolver = new SecurityTokenValueResolver($tokenStorage);
        $metadata = new ArgumentMetadata('foo', TokenInterface::class, false, false, null);

        $this->assertSame([$token]$resolver->resolve(Request::create('/')$metadata));
    }

    public function testResolveSucceedsWithSubclassType()
    {
        $user = new InMemoryUser('username', 'password');
        $token = new UsernamePasswordToken($user, 'provider');
        
if ($response instanceof Response) {
            return $response;
        }

        $this->logger?->debug('Authenticator set no success response: request continues.', ['authenticator' => ($authenticator instanceof TraceableAuthenticator ? $authenticator->getAuthenticator() : $authenticator)::class]);

        return null;
    }

    private function handleAuthenticationSuccess(TokenInterface $authenticatedToken, Passport $passport, Request $request, AuthenticatorInterface $authenticator, ?TokenInterface $previousToken): ?Response
    {
        $this->tokenStorage->setToken($authenticatedToken);

        $response = $authenticator->onAuthenticationSuccess($request$authenticatedToken$this->firewallName);
        if ($authenticator instanceof InteractiveAuthenticatorInterface && $authenticator->isInteractive()) {
            $loginEvent = new InteractiveLoginEvent($request$authenticatedToken);
            $this->eventDispatcher->dispatch($loginEvent, SecurityEvents::INTERACTIVE_LOGIN);
        }

        $this->eventDispatcher->dispatch($loginSuccessEvent = new LoginSuccessEvent($authenticator$passport$authenticatedToken$request$response$this->firewallName, $previousToken));

        return $loginSuccessEvent->getResponse();
    }

    
$accessMap,
            false
        );

        $listener(new RequestEvent($this->createMock(HttpKernelInterface::class)$request, HttpKernelInterface::MAIN_REQUEST));
    }

    public function testHandleWhenPublicAccessWhileAuthenticated()
    {
        $token = new UsernamePasswordToken(new InMemoryUser('Wouter', null, ['ROLE_USER']), 'main', ['ROLE_USER']);
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken($token);
        $request = new Request();

        $accessMap = $this->createMock(AccessMapInterface::class);
        $accessMap->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->willReturn([[AuthenticatedVoter::PUBLIC_ACCESS], null])
        ;

        $accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $accessDecisionManager->expects($this->once())
            
public function testGetLogoutPathWithoutLogoutListenerRegisteredForKeyThrowsException()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('No LogoutListener found for firewall key "unregistered_key".');
        $this->generator->registerListener('secured_area', '/logout', null, null, null);

        $this->generator->getLogoutPath('unregistered_key');
    }

    public function testGuessFromToken()
    {
        $this->tokenStorage->setToken(new UsernamePasswordToken(new InMemoryUser('user', 'password'), 'secured_area'));
        $this->generator->registerListener('secured_area', '/logout', null, null);

        $this->assertSame('/logout', $this->generator->getLogoutPath());
    }

    public function testGuessFromCurrentFirewallKey()
    {
        $this->generator->registerListener('secured_area', '/logout', null, null);
        $this->generator->setCurrentFirewall('secured_area');

        $this->assertSame('/logout', $this->generator->getLogoutPath());
    }
Home | Imprint | This part of the site doesn't use cookies.