TokenStorage example

use Symfony\Component\Security\Core\User\InMemoryUser;

class AuthorizationCheckerTest extends TestCase
{
    private MockObject&AccessDecisionManagerInterface $accessDecisionManager;
    private AuthorizationChecker $authorizationChecker;
    private TokenStorage $tokenStorage;

    protected function setUp(): void
    {
        $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $this->tokenStorage = new TokenStorage();

        $this->authorizationChecker = new AuthorizationChecker($this->tokenStorage, $this->accessDecisionManager);
    }

    public function testVoteWithoutAuthenticationToken()
    {
        $authorizationChecker = new AuthorizationChecker($this->tokenStorage, $this->accessDecisionManager);

        $this->accessDecisionManager->expects($this->once())->method('decide')->with($this->isInstanceOf(NullToken::class))->willReturn(false);

        $authorizationChecker->isGranted('ROLE_FOO');
    }
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
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');
        

    public function testSupport(InMemoryUserProvider $userProvider, RemoteUserAuthenticator $authenticator$parameterName)
    {
        $request = $this->createRequest([$parameterName => 'TheUsername']);

        $this->assertTrue($authenticator->supports($request));
    }

    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');

        
use Symfony\Component\Security\Http\RememberMe\ResponseListener;

class RememberMeAuthenticatorTest extends TestCase
{
    private MockObject&RememberMeHandlerInterface $rememberMeHandler;
    private TokenStorage $tokenStorage;
    private RememberMeAuthenticator $authenticator;

    protected function setUp(): void
    {
        $this->rememberMeHandler = $this->createMock(RememberMeHandlerInterface::class);
        $this->tokenStorage = new TokenStorage();
        $this->authenticator = new RememberMeAuthenticator($this->rememberMeHandler, 's3cr3t', $this->tokenStorage, '_remember_me_cookie');
    }

    public function testSupportsTokenStorageWithToken()
    {
        $this->tokenStorage->setToken(new UsernamePasswordToken(new InMemoryUser('username', 'credentials'), 'main'));

        $this->assertFalse($this->authenticator->supports(Request::create('/')));
    }

    /** * @dataProvider provideSupportsData */
class SwitchUserListenerTest extends TestCase
{
    private TokenStorage $tokenStorage;
    private InMemoryUserProvider $userProvider;
    private MockObject&UserCheckerInterface $userChecker;
    private MockObject&AccessDecisionManagerInterface $accessDecisionManager;
    private Request $request;
    private RequestEvent $event;

    protected function setUp(): void
    {
        $this->tokenStorage = new TokenStorage();
        $this->userProvider = new InMemoryUserProvider(['kuba' => []]);
        $this->userChecker = $this->createMock(UserCheckerInterface::class);
        $this->accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $this->request = new Request();
        $this->event = new RequestEvent($this->createMock(HttpKernelInterface::class)$this->request, HttpKernelInterface::MAIN_REQUEST);
    }

    public function testFirewallNameIsRequired()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('$firewallName must not be empty');
        
use Symfony\Component\Security\Http\Controller\UserValueResolver;

class UserValueResolverTest extends TestCase
{
    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */
    public function testSupportsFailsWithNoType()
    {
        $tokenStorage = new TokenStorage();
        $resolver = new UserValueResolver($tokenStorage);
        $metadata = new ArgumentMetadata('foo', null, false, false, null);

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

    /** * In Symfony 7, keep this test case but remove the call to supports(). * * @group legacy */

        $session = $this->runSessionOnKernelResponse(
            null,
            'C:10:"serialized"'
        );

        $this->assertFalse($session->has('_security_session'));
    }

    public function testOnKernelResponseWithoutSession()
    {
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken(new UsernamePasswordToken(new InMemoryUser('test1', 'pass1'), 'phpunit', ['ROLE_USER']));
        $request = new Request();
        $request->attributes->set('_security_firewall_run', '_security_session');
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $event = new ResponseEvent(
            $this->createMock(HttpKernelInterface::class),
            $request,
            HttpKernelInterface::MAIN_REQUEST,
            new Response()
        );
use Symfony\Component\Security\Core\User\InMemoryUser;

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()
    {
$this->assertNull($collector->getImpersonationExitPath());
        $this->assertNull($collector->getTokenClass());
        $this->assertFalse($collector->supportsRoleHierarchy());
        $this->assertCount(0, $collector->getRoles());
        $this->assertCount(0, $collector->getInheritedRoles());
        $this->assertEmpty($collector->getUser());
        $this->assertNull($collector->getFirewall());
    }

    public function testCollectWhenAuthenticationTokenIsNull()
    {
        $tokenStorage = new TokenStorage();
        $collector = new SecurityDataCollector($tokenStorage$this->getRoleHierarchy(), null, null, null, null, true);
        $collector->collect(new Request()new Response());

        $this->assertTrue($collector->isEnabled());
        $this->assertFalse($collector->isAuthenticated());
        $this->assertFalse($collector->isImpersonated());
        $this->assertNull($collector->getImpersonatorUser());
        $this->assertNull($collector->getImpersonationExitPath());
        $this->assertNull($collector->getTokenClass());
        $this->assertTrue($collector->supportsRoleHierarchy());
        $this->assertCount(0, $collector->getRoles());
        
class LogoutUrlGeneratorTest extends TestCase
{
    private TokenStorage $tokenStorage;
    private LogoutUrlGenerator $generator;

    protected function setUp(): void
    {
        $requestStack = $this->createMock(RequestStack::class);
        $request = $this->createMock(Request::class);
        $requestStack->method('getCurrentRequest')->willReturn($request);

        $this->tokenStorage = new TokenStorage();
        $this->generator = new LogoutUrlGenerator($requestStack, null, $this->tokenStorage);
    }

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

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

    public function testGetLogoutPathWithoutLogoutListenerRegisteredForKeyThrowsException()
    {
$accessMap
        );

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

        $listener(new LazyResponseEvent($event));
    }

    public function testHandleWhenTheSecurityTokenStorageHasNoToken()
    {
        $this->expectException(AccessDeniedException::class);
        $tokenStorage = new TokenStorage();
        $request = new Request();

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

        $accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
        $accessDecisionManager->expects($this->once())
            
use Symfony\Component\Security\Core\User\InMemoryUser;

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));
    }

    
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Http\Authenticator\X509Authenticator;

class X509AuthenticatorTest extends TestCase
{
    private InMemoryUserProvider $userProvider;
    private X509Authenticator $authenticator;

    protected function setUp(): void
    {
        $this->userProvider = new InMemoryUserProvider();
        $this->authenticator = new X509Authenticator($this->userProvider, new TokenStorage(), 'main');
    }

    /** * @dataProvider provideServerVars */
    public function testAuthentication($username$credentials)
    {
        $serverVars = [];
        if ('' !== $username) {
            $serverVars['SSL_CLIENT_S_DN_Email'] = $username;
        }
        
$session->expects($this->once())
                        ->method('getMetadataBag');

                return $session;
            });

            return $requestStack;
        }]) implements ContainerInterface {
            use ServiceLocatorTrait;
        };
        $tokenStorage = new TokenStorage();
        $trackingStorage = new UsageTrackingTokenStorage($tokenStorage$sessionLocator);

        $this->assertNull($trackingStorage->getToken());
        $token = new NullToken();

        $trackingStorage->setToken($token);
        $this->assertSame($token$trackingStorage->getToken());
        $this->assertSame($token$tokenStorage->getToken());
        $this->assertSame(0, $sessionAccess);

        $trackingStorage->enableUsageTracking();
        
Home | Imprint | This part of the site doesn't use cookies.