UserBadge example

use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Authenticator\Token\PostAuthenticationToken;

class AbstractAuthenticatorTest extends TestCase
{
    public function testCreateToken()
    {
        $authenticator = new ConcreteAuthenticator();
        $this->assertInstanceOf(
            PostAuthenticationToken::class,
            $authenticator->createToken(new SelfValidatingPassport(new UserBadge('dummy', fn () => new InMemoryUser('robin', 'hood'))), 'dummy')
        );
    }
}

class ConcreteAuthenticator extends AbstractAuthenticator
{
    public function createToken(Passport $passport, string $firewallName): TokenInterface
    {
        return parent::createToken($passport$firewallName);
    }

    
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)
    {
        
for ($i = 0; $i < 6; ++$i) {
            $this->listener->checkPassport($this->createCheckPassportEvent($passports[$i % 2]));
            $this->listener->onFailedLogin($this->createLoginFailedEvent($passports[$i % 2]));
        }

        $this->expectException(TooManyLoginAttemptsAuthenticationException::class);
        $this->listener->checkPassport($this->createCheckPassportEvent($passports[0]));
    }

    private function createPassport($username)
    {
        return new SelfValidatingPassport(new UserBadge($username));
    }

    private function createLoginFailedEvent($passport)
    {
        return new LoginFailureEvent($this->createMock(AuthenticationException::class)$this->createMock(AuthenticatorInterface::class)$this->requestStack->getCurrentRequest(), null, 'main', $passport);
    }

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

    
use Symfony\Component\Ldap\Security\LdapBadge;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;

class LdapAuthenticatorTest extends TestCase
{
    public function testAuthenticate()
    {
        $decorated = $this->createMock(AuthenticatorInterface::class);
        $passport = new Passport(new UserBadge('test')new PasswordCredentials('s3cret'));
        $decorated
            ->expects($this->once())
            ->method('authenticate')
            ->willReturn($passport)
        ;

        $authenticator = new LdapAuthenticator($decorated, 'serviceId');
        $request = new Request();

        $authenticator->authenticate($request);

        
namespace Symfony\Component\Security\Http\Tests\Authenticator\Passport\Badge;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class UserBadgeTest extends TestCase
{
    public function testUserNotFound()
    {
        $badge = new UserBadge('dummy', fn () => null);
        $this->expectException(UserNotFoundException::class);
        $badge->getUser();
    }
}
$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()
    {
        
        return null;
    }

    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
    {
        
// Call the OIDC server to retrieve the user info             // If the token is invalid or expired, the OIDC server will return an error             $claims = $this->client->request('GET', '', [
                'auth_bearer' => $accessToken,
            ])->toArray();

            if (empty($claims[$this->claim])) {
                throw new MissingClaimException(sprintf('"%s" claim not found on OIDC server response.', $this->claim));
            }

            // UserLoader argument can be overridden by a UserProvider on AccessTokenAuthenticator::authenticate             return new UserBadge($claims[$this->claim]new FallbackUserLoader(fn () => $this->createUser($claims))$claims);
        } catch (\Exception $e) {
            $this->logger?->error('An error occurred on OIDC server.', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw new BadCredentialsException('Invalid credentials.', $e->getCode()$e);
        }
    }
}
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);
    }
}

        $this->urlGenerator = $urlGenerator;
    }

    public function authenticate(Request $request): Passport
    {
        $username = $request->request->get('_username', '');

        $request->getSession()->set(SecurityRequestAttributes::LAST_USERNAME, $username);

        return new Passport(
            new UserBadge($username),
            new PasswordCredentials($request->request->get('_password', '')),
            []
        );
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token$firewallName): ?Response
    {
        return new RedirectResponse($this->urlGenerator->generate('security_'.$firewallName.'_profile'));
    }

    protected function getLoginUrl(Request $request): string
    {
private InMemoryUserProvider $userProvider;
    private UserProviderListener $listener;

    protected function setUp(): void
    {
        $this->userProvider = new InMemoryUserProvider();
        $this->listener = new UserProviderListener($this->userProvider);
    }

    public function testSetUserProvider()
    {
        $passport = new SelfValidatingPassport(new UserBadge('wouter'));

        $this->listener->checkPassport(new CheckPassportEvent($this->createMock(AuthenticatorInterface::class)$passport));

        $user = new InMemoryUser('wouter', null);
        $this->userProvider->createUser($user);
        $this->assertTrue($user->isEqualTo($passport->getUser()));
    }

    /** * @dataProvider provideCompletePassports */
    
public static function provideSupportsWithCustomHeaderParameter(): iterable
    {
        yield [new Request([][][][][]['HTTP_X_FOO' => 'Bearer VALID_ACCESS_TOKEN']), null];
        yield [new Request([][][][][]['HTTP_X_FOO' => 'Bearer INVALID_ACCESS_TOKEN']), null];
        yield [new Request([][][][][]['HTTP_AUTHORIZATION' => 'Bearer VALID_ACCESS_TOKEN']), false];
        yield [new Request([][][][][]['HTTP_AUTHORIZATION' => 'Bearer INVALID_ACCESS_TOKEN']), false];
    }

    public function testAuthenticate()
    {
        $this->accessTokenHandler->add('VALID_ACCESS_TOKEN', new UserBadge('foo'));
        $this->setUpAuthenticator();

        $request = new Request([][][][][]['HTTP_AUTHORIZATION' => 'Bearer VALID_ACCESS_TOKEN']);
        $passport = $this->authenticator->authenticate($request);
        $this->assertInstanceOf(SelfValidatingPassport::class$passport);
    }

    public function testAuthenticateWithCustomTokenType()
    {
        $this->accessTokenHandler->add('VALID_ACCESS_TOKEN', new UserBadge('foo'));
        $this->setUpAuthenticator('Authorization', 'JWT');

        
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;

class TraceableAuthenticatorTest extends TestCase
{
    public function testGetInfo()
    {
        $request = new Request();
        $passport = new SelfValidatingPassport(new UserBadge('robin', function D) {}));

        $authenticator = $this->createMock(AuthenticatorInterface::class);
        $authenticator
            ->expects($this->once())
            ->method('authenticate')
            ->with($request)
            ->willReturn($passport);

        $traceable = new TraceableAuthenticator($authenticator);
        $this->assertSame($passport$traceable->authenticate($request));
        $this->assertSame($passport$traceable->getInfo()['passport']);
    }
$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
            
$request = Request::create('/test');

        $this->accessTokenExtractor
            ->expects($this->once())
            ->method('extractAccessToken')
            ->with($request)
            ->willReturn('test');
        $this->accessTokenHandler
            ->expects($this->once())
            ->method('getUserBadgeFrom')
            ->with('test')
            ->willReturn(new UserBadge('john', fn () => new InMemoryUser('john', null)));

        $authenticator = new AccessTokenAuthenticator(
            $this->accessTokenHandler,
            $this->accessTokenExtractor,
            $this->userProvider,
        );

        $passport = $authenticator->authenticate($request);

        $this->assertEquals('john', $passport->getUser()->getUserIdentifier());
    }

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