UsernamePasswordToken example

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

    public static function provider()
    {
        $roles = ['ROLE_USER', 'ROLE_ADMIN'];
        $user = new InMemoryUser('username', 'password', $roles);

        $noToken = null;
        $rememberMeToken = new RememberMeToken($user, 'firewall-name', 'firewall');
        $usernamePasswordToken = new UsernamePasswordToken($user, 'firewall-name', $roles);

        return [
            [$noToken, 'is_authenticated()', false],
            [$noToken, 'is_fully_authenticated()', false],
            [$noToken, 'is_remember_me()', false],

            [$rememberMeToken, 'is_authenticated()', true],
            [$rememberMeToken, 'is_fully_authenticated()', false],
            [$rememberMeToken, 'is_remember_me()', true],
            [$rememberMeToken, "is_granted('ROLE_FOO')", false],
            [$rememberMeToken, "is_granted('ROLE_USER')", true],

            [
$controller = $this->createController();
        $controller->setContainer($container);

        $response = $controller->forward('a_controller');
        $this->assertEquals('xml--fr', $response->getContent());
    }

    public function testGetUser()
    {
        $user = new InMemoryUser('user', 'pass');
        $token = new UsernamePasswordToken($user, 'default', ['ROLE_USER']);

        $controller = $this->createController();
        $controller->setContainer($this->getContainerWithTokenStorage($token));

        $this->assertSame($controller->getUser()$user);
    }

    public function testGetUserWithEmptyTokenStorage()
    {
        $controller = $this->createController();
        $controller->setContainer($this->getContainerWithTokenStorage(null));

        
class SecurityTest extends AbstractWebTestCase
{
    public function testServiceIsFunctional()
    {
        $kernel = self::createKernel(['test_case' => 'SecurityHelper', 'root_config' => 'config.yml']);
        $kernel->boot();
        $container = $kernel->getContainer();

        // put a token into the storage so the final calls can function         $user = new InMemoryUser('foo', 'pass');
        $token = new UsernamePasswordToken($user, 'provider', ['ROLE_USER']);
        $container->get('functional.test.security.token_storage')->setToken($token);

        $security = $container->get('functional_test.security.helper');
        $this->assertTrue($security->isGranted('ROLE_USER'));
        $this->assertSame($token$security->getToken());
        $request = new Request();
        $request->server->set('REQUEST_URI', '/main/foo');
        $this->assertInstanceOf(FirewallConfig::class$firewallConfig = $security->getFirewallConfig($request));
        $this->assertSame('main', $firewallConfig->getName());
    }

    
$passport = new Passport($userBadgenew PasswordCredentials($credentials['password'])[new RememberMeBadge((array) $data)]);

        if ($this->userProvider instanceof PasswordUpgraderInterface) {
            $passport->addBadge(new PasswordUpgradeBadge($credentials['password']$this->userProvider));
        }

        return $passport;
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return new UsernamePasswordToken($passport->getUser()$firewallName$passport->getUser()->getRoles());
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        if (null === $this->successHandler) {
            return null; // let the original request continue         }

        return $this->successHandler->onAuthenticationSuccess($request$token);
    }

    


        if ($this->userProvider instanceof PasswordUpgraderInterface) {
            $passport->addBadge(new PasswordUpgradeBadge($credentials['password']$this->userProvider));
        }

        return $passport;
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return new UsernamePasswordToken($passport->getUser()$firewallName$passport->getUser()->getRoles());
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return $this->successHandler->onAuthenticationSuccess($request$token);
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
    {
        return $this->failureHandler->onAuthenticationFailure($request$exception);
    }

    
public function testUserProvidersNeedToImplementAnInterface()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface');
        $this->handleEventWithPreviousSession([new \stdClass()]);
    }

    public function testOnKernelResponseWillAddSession()
    {
        $session = $this->runSessionOnKernelResponse(
            new UsernamePasswordToken(new InMemoryUser('test1', 'pass1'), 'phpunit', ['ROLE_USER']),
            null
        );

        $token = unserialize($session->get('_security_session'));
        $this->assertInstanceOf(UsernamePasswordToken::class$token);
        $this->assertEquals('test1', $token->getUserIdentifier());
    }

    public function testOnKernelResponseWillReplaceSession()
    {
        $session = $this->runSessionOnKernelResponse(
            
$this->assertTrue($collector->supportsRoleHierarchy());
        $this->assertCount(0, $collector->getRoles());
        $this->assertCount(0, $collector->getInheritedRoles());
        $this->assertEmpty($collector->getUser());
        $this->assertNull($collector->getFirewall());
    }

    /** @dataProvider provideRoles */
    public function testCollectAuthenticationTokenAndRoles(array $roles, array $normalizedRoles, array $inheritedRoles)
    {
        $tokenStorage = new TokenStorage();
        $tokenStorage->setToken(new UsernamePasswordToken(new InMemoryUser('hhamon', 'P4$$w0rD', $roles), 'provider', $roles));

        $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->assertFalse($collector->isImpersonated());
        $this->assertNull($collector->getImpersonatorUser());
        $this->assertNull($collector->getImpersonationExitPath());
        $this->assertSame(UsernamePasswordToken::class$collector->getTokenClass()->getValue());
        
$manager->authenticateRequest($this->request);
    }

    public function testAllRequiredBadgesPresent()
    {
        $authenticator = $this->createAuthenticator();
        $this->request->attributes->set('_security_authenticators', [$authenticator]);

        $csrfBadge = new CsrfTokenBadge('csrfid', 'csrftoken');
        $csrfBadge->markResolved();
        $authenticator->expects($this->any())->method('authenticate')->willReturn(new SelfValidatingPassport(new UserBadge('wouter')[$csrfBadge]));
        $authenticator->expects($this->any())->method('createToken')->willReturn(new UsernamePasswordToken($this->user, 'main'));

        $authenticator->expects($this->once())->method('onAuthenticationSuccess');

        $manager = $this->createManager([$authenticator], 'main', true, [CsrfTokenBadge::class]);
        $manager->authenticateRequest($this->request);
    }

    /** * @dataProvider provideEraseCredentialsData */
    public function testEraseCredentials($eraseCredentials)
    {
$tokenStorage,
            $accessDecisionManager,
            $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])
        ;

        
$passport = new Passport($userBadgenew PasswordCredentials($password));

        if ($this->userProvider instanceof PasswordUpgraderInterface) {
            $passport->addBadge(new PasswordUpgradeBadge($password$this->userProvider));
        }

        return $passport;
    }

    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return new UsernamePasswordToken($passport->getUser()$firewallName$passport->getUser()->getRoles());
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        $this->logger?->info('Basic authentication failed for user.', ['username' => $request->headers->get('PHP_AUTH_USER'), 'exception' => $exception]);

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

/** * 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,
                

        $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);
        $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', []);
        
namespace Symfony\Component\Security\Core\Tests\Authentication\Token;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\InMemoryUser;

class UsernamePasswordTokenTest extends TestCase
{
    public function testConstructor()
    {
        $token = new UsernamePasswordToken(new InMemoryUser('foo', 'bar', ['ROLE_FOO']), 'key', ['ROLE_FOO']);
        $this->assertEquals(['ROLE_FOO']$token->getRoleNames());
        $this->assertEquals('key', $token->getFirewallName());
    }

    public function testToString()
    {
        $token = new UsernamePasswordToken(new InMemoryUser('foo', '', ['A', 'B']), 'foo', ['A', 'B']);
        $this->assertEquals('UsernamePasswordToken(user="foo", roles="A, B")', (string) $token);
    }
}
protected function setUp(): void
    {
        $this->configuration = [
            'test_is_granted' => 'is_granted("something")',
            'test_is_valid' => 'is_valid(subject)',
            'test_expression' => [
                new GuardExpression(new Transition('name', 'from', 'to'), '!is_valid(subject)'),
                new GuardExpression(new Transition('name', 'from', 'to'), 'is_valid(subject)'),
            ],
        ];
        $expressionLanguage = new ExpressionLanguage();
        $token = new UsernamePasswordToken(new InMemoryUser('username', 'credentials', ['ROLE_USER']), 'provider', ['ROLE_USER']);
        $tokenStorage = $this->createMock(TokenStorageInterface::class);
        $tokenStorage->expects($this->any())->method('getToken')->willReturn($token);
        $this->authenticationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $trustResolver = $this->createMock(AuthenticationTrustResolverInterface::class);
        $this->validator = $this->createMock(ValidatorInterface::class);
        $roleHierarchy = new RoleHierarchy([]);
        $this->listener = new GuardListener($this->configuration, $expressionLanguage$tokenStorage$this->authenticationChecker, $trustResolver$roleHierarchy$this->validator);
    }

    public function testWithNotSupportedEvent()
    {
        
public function testConstructWithSAfeMessage()
    {
        $e = new CustomUserMessageAuthenticationException('SAFE MESSAGE', ['foo' => true]);

        $this->assertEquals('SAFE MESSAGE', $e->getMessageKey());
        $this->assertEquals(['foo' => true]$e->getMessageData());
        $this->assertEquals('SAFE MESSAGE', $e->getMessage());
    }

    public function testSharedSerializedData()
    {
        $token = new UsernamePasswordToken(new InMemoryUser('foo', 'bar', ['ROLE_USER']), 'main', ['ROLE_USER']);

        $exception = new CustomUserMessageAuthenticationException();
        $exception->setToken($token);
        $exception->setSafeMessage('message', ['token' => $token]);

        $processed = unserialize(serialize($exception));
        $this->assertEquals($token$processed->getToken());
        $this->assertEquals($token$processed->getMessageData()['token']);
        $this->assertSame($processed->getToken()$processed->getMessageData()['token']);
    }

    
Home | Imprint | This part of the site doesn't use cookies.