getBadge example

$request = Request::create('/login/link/check?stuff=1&user=weaverryan');
        $user = $this->createMock(UserInterface::class);
        $this->loginLinkHandler->expects($this->once())
            ->method('consumeLoginLink')
            ->with($request)
            ->willReturn($user);

        $passport = $this->authenticator->authenticate($request);
        $this->assertInstanceOf(SelfValidatingPassport::class$passport);
        /** @var UserBadge $userBadge */
        $userBadge = $passport->getBadge(UserBadge::class);
        $this->assertSame($user$userBadge->getUser());
        $this->assertSame('weaverryan', $userBadge->getUserIdentifier());
    }

    public function testUnsuccessfulAuthenticate()
    {
        $this->expectException(InvalidLoginLinkAuthenticationException::class);
        $this->setUpAuthenticator();

        $request = Request::create('/login/link/check?stuff=1&user=weaverryan');
        $this->loginLinkHandler->expects($this->once())
            
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'));
        $this->listener->checkPassport($this->createEvent($passport));

        $this->assertTrue($passport->hasBadge(PasswordUpgradeBadge::class));
        $this->assertEquals('ThePa$$word', $passport->getBadge(PasswordUpgradeBadge::class)->getAndErasePlaintextPassword());
    }

    public function testAddsNoPasswordUpgradeBadgeIfItAlreadyExists()
    {
        $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 = $this->getMockBuilder(Passport::class)
            ->onlyMethods(['addBadge'])
            
public function testExtractCredentialsAndUserFromRequest()
    {
        $request = new Request([][][][][][
            'PHP_AUTH_USER' => 'TheUsername',
            'PHP_AUTH_PW' => 'ThePassword',
        ]);

        $this->userProvider->createUser($user = new InMemoryUser('TheUsername', 'ThePassword'));

        $passport = $this->authenticator->authenticate($request);
        $this->assertEquals('ThePassword', $passport->getBadge(PasswordCredentials::class)->getPassword());

        $this->assertTrue($user->isEqualTo($passport->getUser()));
    }

    /** * @dataProvider provideMissingHttpBasicServerParameters */
    public function testHttpBasicServerParametersMissing(array $serverParameters)
    {
        $request = new Request([][][][][]$serverParameters);

        
$this->userProvider = $userProvider;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(UserBadge::class)) {
            return;
        }

        /** @var UserBadge $badge */
        $badge = $passport->getBadge(UserBadge::class);
        if (null !== $badge->getUserLoader()) {
            return;
        }

        $badge->setUserLoader($this->userProvider->loadUserByIdentifier(...));
    }
}
$this->hasherFactory = $hasherFactory;
    }

    public function onLoginSuccess(LoginSuccessEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(PasswordUpgradeBadge::class)) {
            return;
        }

        /** @var PasswordUpgradeBadge $badge */
        $badge = $passport->getBadge(PasswordUpgradeBadge::class);
        $plaintextPassword = $badge->getAndErasePlaintextPassword();

        if ('' === $plaintextPassword) {
            return;
        }

        $user = $passport->getUser();
        if (!$user instanceof PasswordAuthenticatedUserInterface || null === $user->getPassword()) {
            return;
        }

        
$passport = $event->getPassport();
        if (!$passport->hasBadge(RememberMeBadge::class)) {
            $this->logger?->debug('Remember me skipped: your authenticator does not support it.', ['authenticator' => $event->getAuthenticator()::class]);

            return;
        }

        // Make sure any old remember-me cookies are cancelled         $this->rememberMeHandler->clearRememberMeCookie();

        /** @var RememberMeBadge $badge */
        $badge = $passport->getBadge(RememberMeBadge::class);
        if (!$badge->isEnabled()) {
            $this->logger?->debug('Remember me skipped: the RememberMeBadge is not enabled.');

            return;
        }

        $this->logger?->debug('Remember-me was requested; setting cookie.');

        $this->rememberMeHandler->createRememberMeCookie($event->getUser());
    }

    
return 's$cr$t';
            }
        };

        $request = Request::create('/login_check', 'POST', ['_username' => 'foo', '_password' => $passwordObject]);
        $request->setSession($this->createSession());

        $this->setUpAuthenticator(['post_only' => $postOnly]);
        $passport = $this->authenticator->authenticate($request);

        /** @var PasswordCredentials $credentialsBadge */
        $credentialsBadge = $passport->getBadge(PasswordCredentials::class);
        $this->assertSame('s$cr$t', $credentialsBadge->getPassword());
    }

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

    public function testCsrfProtection()
    {
        

        $passport = $event->getPassport();
        if ($passport->hasBadge(PasswordCredentials::class)) {
            // Use the password hasher to validate the credentials             $user = $passport->getUser();

            if (!$user instanceof PasswordAuthenticatedUserInterface) {
                throw new \LogicException(sprintf('Class "%s" must implement "%s" for using password-based authentication.', get_debug_type($user), PasswordAuthenticatedUserInterface::class));
            }

            /** @var PasswordCredentials $badge */
            $badge = $passport->getBadge(PasswordCredentials::class);

            if ($badge->isResolved()) {
                return;
            }

            $presentedPassword = $badge->getPassword();
            if ('' === $presentedPassword) {
                throw new BadCredentialsException('The presented password cannot be empty.');
            }

            if (null === $user->getPassword()) {
                
$this->assertFalse($passport->hasBadge(RememberMeBadge::class));
    }

    public function testSuccessfulLoginWithoutRequestParameter()
    {
        $this->request = Request::create('/login');
        $this->response = new Response();
        $passport = $this->createPassport([new RememberMeBadge()]);

        $this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

        $this->assertFalse($passport->getBadge(RememberMeBadge::class)->isEnabled());
    }

    public function testSuccessfulHttpLoginWhenRememberMeAlwaysIsTrue()
    {
        $this->createHttpRequest();

        $passport = $this->createPassport();

        $this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

        $this->assertTrue($passport->getBadge(RememberMeBadge::class)->isEnabled());
    }
$this->addBadge($badge);
        }
    }

    public function getUser(): UserInterface
    {
        if (!isset($this->user)) {
            if (!$this->hasBadge(UserBadge::class)) {
                throw new \LogicException('Cannot get the Security user, no username or UserBadge configured for this passport.');
            }

            $this->user = $this->getBadge(UserBadge::class)->getUser();
        }

        return $this->user;
    }

    /** * Adds a new security badge. * * A passport can hold only one instance of the same security badge. * This method replaces the current badge if it is already set on this * passport. * * @param string|null $badgeFqcn A FQCN to which the badge should be mapped to. * This allows replacing a built-in badge by a custom one using * e.g. addBadge(new MyCustomUserBadge(), UserBadge::class) * * @return $this */
$this->logger = $logger;
    }

    public function onSuccessfulLogin(LoginSuccessEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(RememberMeBadge::class)) {
            return;
        }

        /** @var RememberMeBadge $badge */
        $badge = $passport->getBadge(RememberMeBadge::class);
        if (!$this->options['always_remember_me']) {
            $parameter = ParameterBagUtils::getRequestParameterValue($event->getRequest()$this->options['remember_me_parameter']$badge->parameters);
            if (!filter_var($parameter, \FILTER_VALIDATE_BOOL)) {
                $this->logger?->debug('Remember me disabled; request does not contain remember me parameter ("{parameter}").', ['parameter' => $this->options['remember_me_parameter']]);

                return;
            }
        }

        $badge->enable();
    }

    
/** * @return void */
    public function onCheckPassport(CheckPassportEvent $event)
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(LdapBadge::class)) {
            return;
        }

        /** @var LdapBadge $ldapBadge */
        $ldapBadge = $passport->getBadge(LdapBadge::class);
        if ($ldapBadge->isResolved()) {
            return;
        }

        if (!$passport->hasBadge(PasswordCredentials::class)) {
            throw new \LogicException(sprintf('LDAP authentication requires a passport containing password credentials, authenticator "%s" does not fulfill these requirements.', $event->getAuthenticator()::class));
        }

        /** @var PasswordCredentials $passwordCredentials */
        $passwordCredentials = $passport->getBadge(PasswordCredentials::class);
        if ($passwordCredentials->isResolved()) {
            
$user = new InMemoryUser('wouter', null);
        $this->userProvider->createUser($user);
        $this->assertTrue($user->isEqualTo($passport->getUser()));
    }

    /** * @dataProvider provideCompletePassports */
    public function testNotOverrideUserLoader($passport)
    {
        $badgeBefore = $passport->hasBadge(UserBadge::class) ? $passport->getBadge(UserBadge::class) : null;
        $this->listener->checkPassport(new CheckPassportEvent($this->createMock(AuthenticatorInterface::class)$passport));

        $this->assertEquals($passport->hasBadge(UserBadge::class) ? $passport->getBadge(UserBadge::class) : null, $badgeBefore);
    }

    public static function provideCompletePassports()
    {
        yield [new SelfValidatingPassport(new UserBadge('wouter', function D) {}))];
    }
}
$this->csrfTokenManager = $csrfTokenManager;
    }

    public function checkPassport(CheckPassportEvent $event): void
    {
        $passport = $event->getPassport();
        if (!$passport->hasBadge(CsrfTokenBadge::class)) {
            return;
        }

        /** @var CsrfTokenBadge $badge */
        $badge = $passport->getBadge(CsrfTokenBadge::class);
        if ($badge->isResolved()) {
            return;
        }

        $csrfToken = new CsrfToken($badge->getCsrfTokenId()$badge->getCsrfToken());

        if (false === $this->csrfTokenManager->isTokenValid($csrfToken)) {
            throw new InvalidCsrfTokenException('Invalid CSRF token.');
        }

        $badge->markResolved();
    }

        yield [Request::create('/api/login', 'GET', [][][]['HTTP_CONTENT_TYPE' => 'application/json']), true];
        yield [Request::create('/login', 'GET', [][][]['HTTP_CONTENT_TYPE' => 'application/json']), false];
    }

    public function testAuthenticate()
    {
        $this->setUpAuthenticator();

        $request = new Request([][][][][]['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}');
        $passport = $this->authenticator->authenticate($request);
        $this->assertEquals('foo', $passport->getBadge(PasswordCredentials::class)->getPassword());
    }

    public function testAuthenticateWithCustomPath()
    {
        $this->setUpAuthenticator([
            'username_path' => 'authentication.username',
            'password_path' => 'authentication.password',
        ]);

        $request = new Request([][][][][]['HTTP_CONTENT_TYPE' => 'application/json'], '{"authentication": {"username": "dunglas", "password": "foo"}}');
        $passport = $this->authenticator->authenticate($request);
        
Home | Imprint | This part of the site doesn't use cookies.