loadUserByIdentifier example

public function supports(Request $request): bool
    {
        return ($this->options['post_only'] ? $request->isMethod('POST') : true)
            && $this->httpUtils->checkRequestPath($request$this->options['check_path'])
            && ($this->options['form_only'] ? 'form' === $request->getContentTypeFormat() : true);
    }

    public function authenticate(Request $request): Passport
    {
        $credentials = $this->getCredentials($request);

        $userBadge = new UserBadge($credentials['username']$this->userProvider->loadUserByIdentifier(...));
        $passport = new Passport($userBadgenew PasswordCredentials($credentials['password'])[new RememberMeBadge()]);

        if ($this->options['enable_csrf']) {
            $passport->addBadge(new CsrfTokenBadge($this->options['csrf_token_id']$credentials['csrf_token']));
        }

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

        return $passport;
    }


    public function authenticate(Request $request): Passport
    {
        $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
    {
$this->uidKey = $uidKey;
        $this->defaultSearch = str_replace('{uid_key}', $uidKey$filter);
        $this->passwordAttribute = $passwordAttribute;
        $this->extraFields = $extraFields;
    }

    /** * @internal for compatibility with Symfony 5.4 */
    public function loadUserByUsername(string $username): UserInterface
    {
        return $this->loadUserByIdentifier($username);
    }

    public function loadUserByIdentifier(string $identifier): UserInterface
    {
        try {
            $this->ldap->bind($this->searchDn, $this->searchPassword);
        } catch (InvalidCredentialsException) {
            throw new InvalidSearchCredentialsException();
        }

        $identifier = $this->ldap->escape($identifier, '', LdapInterface::ESCAPE_FILTER);
        
// User already switched, exit before seamlessly switching to another user             $token = $this->attemptExitUser($request);
        }

        $currentUsername = $token->getUserIdentifier();
        $nonExistentUsername = '_'.hash('xxh128', random_bytes(8).$username);

        // To protect against user enumeration via timing measurements         // we always load both successfully and unsuccessfully         try {
            $user = $this->provider->loadUserByIdentifier($username);

            try {
                $this->provider->loadUserByIdentifier($nonExistentUsername);
            } catch (\Exception) {
            }
        } catch (AuthenticationException $e) {
            $this->provider->loadUserByIdentifier($currentUsername);

            throw $e;
        }

        

        $this->expectException(ConnectionException::class);

        $ldap = $this->createMock(LdapInterface::class);
        $ldap
            ->expects($this->once())
            ->method('bind')
            ->willThrowException(new ConnectionException())
        ;

        $provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
        $provider->loadUserByIdentifier('foo');
    }

    public function testLoadUserByIdentifierFailsIfNoLdapEntries()
    {
        $this->expectException(UserNotFoundException::class);

        $result = $this->createMock(CollectionInterface::class);
        $query = $this->createMock(QueryInterface::class);
        $query
            ->expects($this->once())
            ->method('execute')
            
$userLoader = $this->getMockForAbstractClass(TestMigratingUserProvider::class);
        $userLoader->expects($this->any())->method('loadUserByIdentifier')->willReturn($this->user);

        $userLoader->expects($this->exactly(2))
            ->method('upgradePassword')
            ->with($this->user, 'new-hash')
        ;

        $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);
    }
public function loadUserByIdentifier(string $identifier): UserInterface
    {
        $repository = $this->getRepository();
        if (null !== $this->property) {
            $user = $repository->findOneBy([$this->property => $identifier]);
        } else {
            if (!$repository instanceof UserLoaderInterface) {
                throw new \InvalidArgumentException(sprintf('You must either make the "%s" entity Doctrine Repository ("%s") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.', $this->classOrAlias, get_debug_type($repository)));
            }

            $user = $repository->loadUserByIdentifier($identifier);
        }

        if (null === $user) {
            $e = new UserNotFoundException(sprintf('User "%s" not found.', $identifier));
            $e->setUserIdentifier($identifier);

            throw $e;
        }

        return $user;
    }

    

    abstract protected function processRememberMe(RememberMeDetails $rememberMeDetails, UserInterface $user): void;

    public function consumeRememberMeCookie(RememberMeDetails $rememberMeDetails): UserInterface
    {
        try {
            $user = $this->userProvider->loadUserByIdentifier($rememberMeDetails->getUserIdentifier());
        } catch (AuthenticationException $e) {
            throw $e;
        }

        if (!$user instanceof UserInterface) {
            throw new \LogicException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_debug_type($user)));
        }

        $this->processRememberMe($rememberMeDetails$user);

        $this->logger?->info('Remember-me cookie accepted.');

        

        $this->inner = $inner;
    }

    public function loadUserByUsername($username): UserInterface
    {
        return $this->changeUser($this->inner->loadUserByUsername($username));
    }

    public function loadUserByIdentifier(string $userIdentifier): UserInterface
    {
        return $this->changeUser($this->inner->loadUserByIdentifier($userIdentifier));
    }

    public function refreshUser(UserInterface $user): UserInterface
    {
        return $this->changeUser($this->inner->refreshUser($user));
    }

    public function supportsClass($class): bool
    {
        return $this->inner->supportsClass($class);
    }

    
if (!$data instanceof \stdClass) {
                throw new BadRequestHttpException('Invalid JSON.');
            }

            $credentials = $this->getCredentials($data);
        } catch (BadRequestHttpException $e) {
            $request->setRequestFormat('json');

            throw $e;
        }

        $userBadge = new UserBadge($credentials['username']$this->userProvider->loadUserByIdentifier(...));
        $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
    {
        
if (!$hash = $request->get('hash')) {
            throw new InvalidLoginLinkException('Missing "hash" parameter.');
        }
        if (!$expires = $request->get('expires')) {
            throw new InvalidLoginLinkException('Missing "expires" parameter.');
        }

        try {
            $this->signatureHasher->acceptSignatureHash($userIdentifier$expires$hash);

            $user = $this->userProvider->loadUserByIdentifier($userIdentifier);

            $this->signatureHasher->verifySignatureHash($user$expires$hash);
        } catch (UserNotFoundException $e) {
            throw new InvalidLoginLinkException('User not found.', 0, $e);
        } catch (ExpiredSignatureException $e) {
            throw new ExpiredLoginLinkException(ucfirst(str_ireplace('signature', 'login link', $e->getMessage())), 0, $e);
        } catch (InvalidSignatureException $e) {
            throw new InvalidLoginLinkException(ucfirst(str_ireplace('signature', 'login link', $e->getMessage())), 0, $e);
        }

        return $user;
    }

        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);

        $user = new User(1, 1, 'user1');

        $em->persist($user);
        $em->flush();

        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        $this->assertSame($user$provider->loadUserByIdentifier('user1'));
    }

    public function testLoadUserByIdentifierWithUserLoaderRepositoryAndWithoutProperty()
    {
        $user = new User(1, 1, 'user1');

        $repository = $this->createMock(UserLoaderRepository::class);
        $repository
            ->expects($this->once())
            ->method('loadUserByIdentifier')
            ->with('user1')
            
$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(...));
    }
}
return false;
        }

        $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
    {
        
class TestLoginLinkHandlerUserProvider implements UserProviderInterface
{
    private array $users = [];

    public function createUser(TestLoginLinkHandlerUser $user): void
    {
        $this->users[$user->getUserIdentifier()] = $user;
    }

    public function loadUserByUsername($username): TestLoginLinkHandlerUser
    {
        return $this->loadUserByIdentifier($username);
    }

    public function loadUserByIdentifier(string $userIdentifier): TestLoginLinkHandlerUser
    {
        if (!isset($this->users[$userIdentifier])) {
            throw new UserNotFoundException();
        }

        return clone $this->users[$userIdentifier];
    }

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