SelfValidatingPassport example


        $accessToken = $this->accessTokenExtractor->extractAccessToken($request);
        if (!$accessToken) {
            throw new BadCredentialsException('Invalid credentials.');
        }

        $userBadge = $this->accessTokenHandler->getUserBadgeFrom($accessToken);
        if ($this->userProvider && (null === $userBadge->getUserLoader() || $userBadge->getUserLoader() instanceof FallbackUserLoader)) {
            $userBadge->setUserLoader($this->userProvider->loadUserByIdentifier(...));
        }

        return new SelfValidatingPassport($userBadge);
    }

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

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

    
$this->sessionAuthenticationStrategy->expects($this->never())->method('onAuthentication');

        $token = $this->createMock(NullToken::class);
        $token->expects($this->once())
            ->method('getUserIdentifier')
            ->willReturn('test');
        $previousToken = $this->createMock(NullToken::class);
        $previousToken->expects($this->once())
            ->method('getUserIdentifier')
            ->willReturn('test');

        $event = new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class)new SelfValidatingPassport(new UserBadge('test', function D) {}))$token$this->request, null, 'main_firewall', $previousToken);

        $this->listener->onSuccessfulLogin($event);
    }

    private function createEvent($firewallName)
    {
        return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class)new SelfValidatingPassport(new UserBadge('test', fn ($username) => new InMemoryUser($username, null)))$this->token, $this->request, null, $firewallName);
    }

    private function configurePreviousSession()
    {
        

    public function testUnsupportedEvents($event)
    {
        $this->hasherFactory->expects($this->never())->method('getPasswordHasher');

        $this->listener->onLoginSuccess($event);
    }

    public static function provideUnsupportedEvents()
    {
        // no password upgrade badge         yield [self::createEvent(new SelfValidatingPassport(new UserBadge('test', fn () => new DummyTestPasswordAuthenticatedUser())))];

        // blank password         yield [self::createEvent(new SelfValidatingPassport(new UserBadge('test', fn () => new DummyTestPasswordAuthenticatedUser())[new PasswordUpgradeBadge('', self::createPasswordUpgrader())]))];
    }

    public function testUpgradeWithUpgrader()
    {
        $passwordUpgrader = $this->getMockForAbstractClass(TestMigratingUserProvider::class);
        $passwordUpgrader->expects($this->once())
            ->method('upgradePassword')
            ->with($this->user, 'new-hash')
        ;

        $email = $request->headers->get('X-USER-EMAIL');
        if (!str_contains($email, '@')) {
            throw new BadCredentialsException('Email is not a valid email address.');
        }

        $userLoader = null;
        if ($this->selfLoadingUser) {
            $userLoader = fn ($username) => new InMemoryUser($username, 'test', ['ROLE_USER']);
        }

        return new SelfValidatingPassport(new UserBadge($email$userLoader));
    }

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

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse([
            'error' => $exception->getMessageKey(),
        ],
$userBadge = new UserBadge($usernamefunction D) use ($request) {
            try {
                $user = $this->loginLinkHandler->consumeLoginLink($request);
            } catch (InvalidLoginLinkExceptionInterface $e) {
                throw new InvalidLoginLinkAuthenticationException('Login link could not be validated.', 0, $e);
            }

            return $user;
        });

        return new SelfValidatingPassport($userBadge[new RememberMeBadge()]);
    }

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

    

        $this->loginUrl = $loginUrl;
    }

    protected function getLoginUrl(Request $request): string
    {
        return $this->loginUrl;
    }

    public function authenticate(Request $request): Passport
    {
        return new SelfValidatingPassport(new UserBadge('dummy'));
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null;
    }
}
$event->setResponse($response = new Response());

        $supportingAuthenticator = $this->createMock(DummyAuthenticator::class);
        $supportingAuthenticator
            ->method('supports')
            ->with($request)
            ->willReturn(true);
        $supportingAuthenticator
            ->expects($this->once())
            ->method('authenticate')
            ->with($request)
            ->willReturn(new SelfValidatingPassport(new UserBadge('robin', function D) {})));
        $supportingAuthenticator
            ->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->willReturn($response);
        $supportingAuthenticator
            ->expects($this->once())
            ->method('createToken')
            ->willReturn($this->createMock(TokenInterface::class));

        $notSupportingAuthenticator = $this->createMock(DummyAuthenticator::class);
        $notSupportingAuthenticator
            
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);
    }
}
/** * @dataProvider provideMatchingAuthenticatorIndex */
    public function testAuthenticateRequest($matchingAuthenticatorIndex)
    {
        $authenticators = [$this->createAuthenticator(0 === $matchingAuthenticatorIndex)$this->createAuthenticator(1 === $matchingAuthenticatorIndex)];
        $this->request->attributes->set('_security_authenticators', $authenticators);
        $matchingAuthenticator = $authenticators[$matchingAuthenticatorIndex];

        $authenticators[($matchingAuthenticatorIndex + 1) % 2]->expects($this->never())->method('authenticate');

        $matchingAuthenticator->expects($this->any())->method('authenticate')->willReturn(new SelfValidatingPassport(new UserBadge('wouter', fn () => $this->user)));

        $listenerCalled = false;
        $this->eventDispatcher->addListener(CheckPassportEvent::classfunction DCheckPassportEvent $event) use (&$listenerCalled$matchingAuthenticator) {
            if ($event->getAuthenticator() === $matchingAuthenticator && $event->getPassport()->getUser() === $this->user) {
                $listenerCalled = true;
            }
        });
        $matchingAuthenticator->expects($this->any())->method('createToken')->willReturn($this->token);

        $this->tokenStorage->expects($this->once())->method('setToken')->with($this->token);

        
public static function provideCustomAuthenticatedResults()
    {
        yield [true];
        yield [false];
    }

    public function testNoCredentialsBadgeProvided()
    {
        $this->hasherFactory->expects($this->never())->method('getPasswordHasher');

        $event = $this->createEvent(new SelfValidatingPassport(new UserBadge('wouter', fn () => $this->user)));
        $this->listener->checkPassport($event);
    }

    public function testAddsPasswordUpgradeBadge()
    {
        $hasher = $this->createMock(PasswordHasherInterface::class);
        $hasher->expects($this->any())->method('verify')->with('password-hash', 'ThePa$$word')->willReturn(true);

        $this->hasherFactory->expects($this->any())->method('getPasswordHasher')->with($this->identicalTo($this->user))->willReturn($hasher);

        $passport = new Passport(new UserBadge('wouter', fn () => $this->user)new PasswordCredentials('ThePa$$word'));
        
$event = $this->createEvent($this->createPassport(new CsrfTokenBadge('authenticator_token_id', 'abc123')));
        $this->listener->checkPassport($event);
    }

    private function createEvent($passport)
    {
        return new CheckPassportEvent($this->createMock(AuthenticatorInterface::class)$passport);
    }

    private function createPassport(?CsrfTokenBadge $badge)
    {
        $passport = new SelfValidatingPassport(new UserBadge('wouter', fn ($username) => new InMemoryUser($username, 'pass')));
        if ($badge) {
            $passport->addBadge($badge);
        }

        return $passport;
    }
}

        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('LDAP authentication requires a passport containing password credentials, authenticator "'.TestAuthenticator::class.'" does not fulfill these requirements.');

        $listener = $this->createListener();
        $listener->onCheckPassport(new CheckPassportEvent(new TestAuthenticator()$passport));
    }

    public static function provideWrongPassportData()
    {
        // no password credentials         yield [new SelfValidatingPassport(new UserBadge('test')[new LdapBadge('app.ldap')])];
    }

    public function testEmptyPasswordShouldThrowAnException()
    {
        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('The presented password cannot be empty.');

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent(''));
    }

    
public function testPreAuth()
    {
        $this->userChecker->expects($this->once())->method('checkPreAuth')->with($this->user);

        $this->listener->preCheckCredentials($this->createCheckPassportEvent());
    }

    public function testPreAuthenticatedBadge()
    {
        $this->userChecker->expects($this->never())->method('checkPreAuth');

        $this->listener->preCheckCredentials($this->createCheckPassportEvent(new SelfValidatingPassport(new UserBadge('test', fn () => $this->user)[new PreAuthenticatedUserBadge()])));
    }

    public function testPostAuthValidCredentials()
    {
        $this->userChecker->expects($this->once())->method('checkPostAuth')->with($this->user);

        $this->listener->postCheckCredentials(new AuthenticationSuccessEvent(new PostAuthenticationToken($this->user, 'main', [])));
    }

    private function createCheckPassportEvent($passport = null)
    {
        


        $request->attributes->set('_pre_authenticated_username', $username);

        return true;
    }

    public function authenticate(Request $request): Passport
    {
        $userBadge = new UserBadge($request->attributes->get('_pre_authenticated_username')$this->userProvider->loadUserByIdentifier(...));

        return new SelfValidatingPassport($userBadge[new PreAuthenticatedUserBadge()]);
    }

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

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

    
public function authenticate(Request $request): Passport
    {
        if (!$rawCookie = $request->cookies->get($this->cookieName)) {
            throw new \LogicException('No remember-me cookie is found.');
        }

        $rememberMeCookie = RememberMeDetails::fromRawCookie($rawCookie);

        $userBadge = new UserBadge($rememberMeCookie->getUserIdentifier()fn () => $this->rememberMeHandler->consumeRememberMeCookie($rememberMeCookie));

        return new SelfValidatingPassport($userBadge);
    }

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

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

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