InMemoryUser example

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)
    {
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()
    {
        
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class AccessTokenHandler implements AccessTokenHandlerInterface
{
    public function getUserBadgeFrom(string $accessToken): UserBadge
    {
        return match ($accessToken) {
            'VALID_ACCESS_TOKEN' => new UserBadge('dunglas'),
            'SELF_CONTAINED_ACCESS_TOKEN' => new UserBadge('dunglas', fn () => new InMemoryUser('dunglas', null, ['ROLE_USER'])),
            default => throw new BadCredentialsException('Invalid credentials.'),
        };
    }
}
use Symfony\Component\Security\Core\User\InMemoryUser;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Http\Authenticator\HttpBasicAuthenticator;

class UserAuthenticatorTest extends TestCase
{
    public function testThrowsLogicExceptionIfCurrentRequestIsNull()
    {
        $container = new Container();
        $firewallMap = new FirewallMap($container[]);
        $requestStack = new RequestStack();
        $user = new InMemoryUser('username', 'password');
        $userProvider = new InMemoryUserProvider();
        $authenticator = new HttpBasicAuthenticator('name', $userProvider);
        $request = new Request();

        $userAuthenticator = new UserAuthenticator($firewallMap$container$requestStack);

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('Cannot determine the correct Symfony\Bundle\SecurityBundle\Security\UserAuthenticator to use: there is no active Request and so, the firewall cannot be determined. Try using a specific Symfony\Bundle\SecurityBundle\Security\UserAuthenticator service.');

        $userAuthenticator->authenticateUser($user$authenticator$request);
    }
}
->with($user)
            ->willReturn($mockHasher);

        $passwordHasher = new UserPasswordHasher($mockPasswordHasherFactory);

        $isValid = $passwordHasher->isPasswordValid($user, 'plainPassword');
        $this->assertTrue($isValid);
    }

    public function testNeedsRehash()
    {
        $user = new InMemoryUser('username', null);
        $hasher = new NativePasswordHasher(4, 20000, 4);

        $mockPasswordHasherFactory = $this->createMock(PasswordHasherFactoryInterface::class);
        $mockPasswordHasherFactory->expects($this->any())
            ->method('getPasswordHasher')
            ->with($user)
            ->will($this->onConsecutiveCalls($hasher$hashernew NativePasswordHasher(5, 20000, 5)$hasher));

        $passwordHasher = new UserPasswordHasher($mockPasswordHasherFactory);

        \Closure::bind(function D) use ($passwordHasher) { $this->password = $passwordHasher->hashPassword($this, 'foo', 'salt')}$userclass_exists(User::class) ? User::class D InMemoryUser::class)();
        

        $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', []);
        

        $provider = $this->createProvider();

        $user = $provider->loadUserByIdentifier('fabien');
        $this->assertEquals('foo', $user->getPassword());
        $this->assertEquals(['ROLE_USER']$user->getRoles());
        $this->assertFalse($user->isEnabled());
    }

    public function testRefresh()
    {
        $user = new InMemoryUser('fabien', 'bar');

        $provider = $this->createProvider();

        $refreshedUser = $provider->refreshUser($user);
        $this->assertEquals('foo', $refreshedUser->getPassword());
        $this->assertEquals(['ROLE_USER']$refreshedUser->getRoles());
        $this->assertFalse($refreshedUser->isEnabled());
    }

    protected function createProvider(): InMemoryUserProvider
    {
        
return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class)$passport$this->createMock(TokenInterface::class)$this->request, $this->response, 'main_firewall');
    }

    private function createPassport(array $badges = null)
    {
        if (null === $badges) {
            $badge = new RememberMeBadge();
            $badge->enable();
            $badges = [$badge];
        }

        return new SelfValidatingPassport(new UserBadge('test', fn ($username) => new InMemoryUser($username, null))$badges);
    }
}
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(
            
$serverVars = [];
        if ('' !== $username) {
            $serverVars['SSL_CLIENT_S_DN_Email'] = $username;
        }
        if ('' !== $credentials) {
            $serverVars['SSL_CLIENT_S_DN'] = $credentials;
        }

        $request = $this->createRequest($serverVars);
        $this->assertTrue($this->authenticator->supports($request));

        $this->userProvider->createUser(new InMemoryUser($username, null));

        $passport = $this->authenticator->authenticate($request);
        $this->assertEquals($username$passport->getUser()->getUserIdentifier());
    }

    public static function provideServerVars()
    {
        yield ['TheUser', 'TheCredentials'];
        yield ['TheUser', ''];
    }

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

    

    public function testLoginLinkSuccess()
    {
        $client = $this->createClient(['test_case' => 'LoginLink', 'root_config' => 'config.yml', 'debug' => true]);

        // we need an active request that is under the firewall to use the linker         $request = Request::create('/get-login-link');
        self::getContainer()->get(RequestStack::class)->push($request);

        /** @var LoginLinkHandlerInterface $loginLinkHandler */
        $loginLinkHandler = self::getContainer()->get(LoginLinkHandlerInterface::class);
        $user = new InMemoryUser('weaverryan', 'foo');
        $loginLink = $loginLinkHandler->createLoginLink($user);
        $this->assertStringContainsString('user=weaverryan', $loginLink);
        $this->assertStringContainsString('hash=', $loginLink);
        $this->assertStringContainsString('expires=', $loginLink);
        $client->request('GET', $loginLink->getUrl());
        $response = $client->getResponse();

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame(['message' => 'Welcome weaverryan!']json_decode($response->getContent(), true));

        $client->request('GET', $loginLink->getUrl());
        

    public function testGetUserIdentifier($user, string $username)
    {
        $token = new ConcreteToken(['ROLE_FOO']);
        $token->setUser($user);
        $this->assertEquals($username$token->getUserIdentifier());
    }

    public static function provideUsers()
    {
        yield [new InMemoryUser('fabien', null), 'fabien'];
    }

    public function testEraseCredentials()
    {
        $token = new ConcreteToken(['ROLE_FOO']);

        $user = $this->createMock(UserInterface::class);
        $user->expects($this->once())->method('eraseCredentials');
        $token->setUser($user);

        $token->eraseCredentials();
    }
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,
                


        $event = $this->createEvent(new SelfValidatingPassport(new UserBadge('test', [$userLoader, 'loadUserByIdentifier'])[new PasswordUpgradeBadge('pa$$word')]));
        $this->listener->onLoginSuccess($event);

        $event = $this->createEvent(new SelfValidatingPassport(new UserBadge('test', $userLoader->loadUserByIdentifier(...))[new PasswordUpgradeBadge('pa$$word')]));
        $this->listener->onLoginSuccess($event);
    }

    public function testUserWithoutPassword()
    {
        $this->user = new InMemoryUser('test', null);

        $this->hasherFactory->expects($this->never())->method('getPasswordHasher');

        $event = $this->createEvent(new SelfValidatingPassport(new UserBadge('test', fn () => $this->user)[new PasswordUpgradeBadge('pa$$word')]));
        $this->listener->onLoginSuccess($event);
    }

    private static function createPasswordUpgrader()
    {
        return new DummyTestMigratingUserProvider();
    }

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