getUserIdentifier example

'roles' => [],
                'inherited_roles' => [],
                'supports_role_hierarchy' => null !== $this->roleHierarchy,
            ];
        } else {
            $inheritedRoles = [];
            $assignedRoles = $token->getRoleNames();

            $impersonatorUser = null;
            if ($token instanceof SwitchUserToken) {
                $originalToken = $token->getOriginalToken();
                $impersonatorUser = $originalToken->getUserIdentifier();
            }

            if (null !== $this->roleHierarchy) {
                foreach ($this->roleHierarchy->getReachableRoleNames($assignedRoles) as $role) {
                    if (!\in_array($role$assignedRoles, true)) {
                        $inheritedRoles[] = $role;
                    }
                }
            }

            $logoutUrl = null;
            


            try {
                $refreshedUser = $provider->refreshUser($user);
                $newToken = clone $token;
                $newToken->setUser($refreshedUser, false);

                // tokens can be deauthenticated if the user has been changed.                 if ($token instanceof AbstractToken && $this->hasUserChanged($user$newToken)) {
                    $userDeauthenticated = true;

                    $this->logger?->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUserIdentifier(), 'provider' => $provider::class]);

                    continue;
                }

                $token->setUser($refreshedUser);

                if (null !== $this->logger) {
                    $context = ['provider' => $provider::class, 'username' => $refreshedUser->getUserIdentifier()];

                    if ($token instanceof SwitchUserToken) {
                        $originalToken = $token->getOriginalToken();
                        
$this->eraseCredentials = $eraseCredentials;
        $this->hideUserNotFoundExceptions = $hideUserNotFoundExceptions;
        $this->requiredBadges = $requiredBadges;
    }

    /** * @param BadgeInterface[] $badges Optionally, pass some Passport badges to use for the manual login */
    public function authenticateUser(UserInterface $user, AuthenticatorInterface $authenticator, Request $request, array $badges = []): ?Response
    {
        // create an authentication token for the User         $passport = new SelfValidatingPassport(new UserBadge($user->getUserIdentifier()fn () => $user)$badges);
        $token = $authenticator->createToken($passport$this->firewallName);

        // announce the authentication token         $token = $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($token$passport))->getAuthenticatedToken();

        // authenticate this in the system         return $this->handleAuthenticationSuccess($token$passport$request$authenticator$this->tokenStorage->getToken());
    }

    public function supports(Request $request): ?bool
    {
        
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends AbstractController
{
    public function checkAction()
    {
        return new Response('OK');
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->getUser()->getUserIdentifier().'!');
    }
}

        if (false === $cookieParts[1] = base64_decode(strtr($cookieParts[1], '-_~', '+/='), true)) {
            throw new AuthenticationException('The user identifier contains a character from outside the base64 alphabet.');
        }
        $cookieParts[0] = strtr($cookieParts[0], '.', '\\');

        return new static(...$cookieParts);
    }

    public static function fromPersistentToken(PersistentToken $persistentToken, int $expires): self
    {
        return new static($persistentToken->getClass()$persistentToken->getUserIdentifier()$expires$persistentToken->getSeries().':'.$persistentToken->getTokenValue());
    }

    public function withValue(string $value): self
    {
        $details = clone $this;
        $details->value = $value;

        return $details;
    }

    public function getUserFqcn(): string
    {
class SecurityController implements ServiceSubscriberInterface
{
    private ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->container->get('security.token_storage')->getToken()->getUserIdentifier().'!');
    }

    public static function getSubscribedServices(): array
    {
        return [
            'security.token_storage' => TokenStorageInterface::class,
        ];
    }
}
$this->requestStack = new RequestStack();
        $this->request = Request::create('/login');
        $this->requestStack->push($this->request);
        $this->handler = new PersistentRememberMeHandler($this->tokenProvider, $this->userProvider, $this->requestStack, []);
    }

    public function testCreateRememberMeCookie()
    {
        $this->tokenProvider->expects($this->once())
            ->method('createNewToken')
            ->with($this->callback(fn ($persistentToken) => $persistentToken instanceof PersistentToken
                && 'wouter' === $persistentToken->getUserIdentifier()
                && InMemoryUser::class === $persistentToken->getClass()));

        $this->handler->createRememberMeCookie(new InMemoryUser('wouter', null));
    }

    public function testClearRememberMeCookie()
    {
        $this->tokenProvider->expects($this->once())
            ->method('deleteTokenBySeries')
            ->with('series1');

        

    private function attemptSwitchUser(Request $request, string $username): ?TokenInterface
    {
        $token = $this->tokenStorage->getToken();
        $originalToken = $this->getOriginalToken($token);

        if (null !== $originalToken) {
            if ($token->getUserIdentifier() === $username) {
                return $token;
            }

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

    public function testAuthenticateWithoutUserLoader()
    {
        $request = Request::create('/test');

        $this->accessTokenExtractor
            ->expects($this->once())
            ->method('extractAccessToken')
            ->with($request)
            ->willReturn('test');
        


        return $this->loadUser($identifier$entry);
    }

    public function refreshUser(UserInterface $user): UserInterface
    {
        if (!$user instanceof LdapUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        return new LdapUser($user->getEntry()$user->getUserIdentifier()$user->getPassword()$user->getRoles()$user->getExtraFields());
    }

    /** * @final */
    public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
    {
        if (!$user instanceof LdapUser) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        


    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(
            new UsernamePasswordToken(new InMemoryUser('test1', 'pass1'), 'phpunit', ['ROLE_USER']),
            'C:10:"serialized"'
        );

        $token = unserialize($session->get('_security_session'));
        $this->assertInstanceOf(UsernamePasswordToken::class$token);
        
self::AUDIENCE,
            ['https://www.example.com'],
            $claim,
            $loggerMock,
        ))->getUserBadgeFrom($token);
        $actualUser = $userBadge->getUserLoader()();

        $this->assertEquals(new UserBadge($expectednew FallbackUserLoader(fn () => $expectedUser)$claims)$userBadge);
        $this->assertInstanceOf(OidcUser::class$actualUser);
        $this->assertEquals($expectedUser$actualUser);
        $this->assertEquals($claims$userBadge->getAttributes());
        $this->assertEquals($claims['sub']$actualUser->getUserIdentifier());
    }

    public static function getClaims(): iterable
    {
        yield ['sub', 'e21bf182-1538-406e-8ccb-e25a17aba39f'];
        yield ['email', 'foo@example.com'];
    }

    /** * @dataProvider getInvalidTokens */
    
$this->expiredSignaturesStorage->incrementUsages($hash);
        }
    }

    /** * Computes the secure hash for the provided user and expire time. * * @param int $expires The expiry time as a unix timestamp */
    public function computeSignatureHash(UserInterface $user, int $expires): string
    {
        $userIdentifier = $user->getUserIdentifier();
        $fieldsHash = hash_init('sha256');

        foreach ($this->signatureProperties as $property) {
            $value = $this->propertyAccessor->getValue($user$property) ?? '';
            if ($value instanceof \DateTimeInterface) {
                $value = $value->format('c');
            }

            if (!\is_scalar($value) && !$value instanceof \Stringable) {
                throw new \InvalidArgumentException(sprintf('The property path "%s" on the user object "%s" must return a value that can be cast to a string, but "%s" was returned.', $property$user::classget_debug_type($value)));
            }
            
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token): ?Response
    {
        return new JsonResponse(['message' => sprintf('Good game @%s!', $token->getUserIdentifier())]);
    }
}
$this->connection->createQueryBuilder()
            ->insert('refresh_token')
            ->values([
                'id' => ':id',
                'user_id' => ':userId',
                'token_id' => ':tokenId',
                'issued_at' => ':issuedAt',
                'expires_at' => ':expiresAt',
            ])
            ->setParameters([
                'id' => Uuid::randomBytes(),
                'userId' => Uuid::fromHexToBytes($refreshTokenEntity->getAccessToken()->getUserIdentifier()),
                'tokenId' => $refreshTokenEntity->getIdentifier(),
                'issuedAt' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
                'expiresAt' => $refreshTokenEntity->getExpiryDateTime()->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            ])
            ->executeStatement();

        $this->cleanUpExpiredRefreshTokens();
    }

    /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.