computeSignatureHash example

public function __construct(SignatureHasher $signatureHasher, UserProviderInterface $userProvider, RequestStack $requestStack, array $options, LoggerInterface $logger = null)
    {
        parent::__construct($userProvider$requestStack$options$logger);

        $this->signatureHasher = $signatureHasher;
    }

    public function createRememberMeCookie(UserInterface $user): void
    {
        $expires = time() + $this->options['lifetime'];
        $value = $this->signatureHasher->computeSignatureHash($user$expires);

        $details = new RememberMeDetails($user::class$user->getUserIdentifier()$expires$value);
        $this->createCookie($details);
    }

    public function consumeRememberMeCookie(RememberMeDetails $rememberMeDetails): UserInterface
    {
        try {
            $this->signatureHasher->acceptSignatureHash($rememberMeDetails->getUserIdentifier()$rememberMeDetails->getExpires()$rememberMeDetails->getValue());
        } catch (InvalidSignatureException $e) {
            throw new AuthenticationException('The cookie\'s hash is invalid.', 0, $e);
        }
$this->request = Request::create('/login');
        $this->requestStack->push($this->request);
        $this->handler = new SignatureRememberMeHandler($this->signatureHasher, $this->userProvider, $this->requestStack, []);
    }

    /** * @group time-sensitive */
    public function testCreateRememberMeCookie()
    {
        $user = new InMemoryUser('wouter', null);
        $signature = $this->signatureHasher->computeSignatureHash($user$expire = time() + 31536000);
        $this->userProvider->createUser(new InMemoryUser('wouter', null));

        $this->handler->createRememberMeCookie($user);

        $this->assertTrue($this->request->attributes->has(ResponseListener::COOKIE_ATTR_NAME));

        /** @var Cookie $cookie */
        $cookie = $this->request->attributes->get(ResponseListener::COOKIE_ATTR_NAME);
        $this->assertEquals(strtr(InMemoryUser::class, '\\', '.').':d291dGVy:'.$expire.':'.$signature$cookie->getValue());
    }

    
$request = Request::create('/login/verify?user=weaverryan&hash=thehash');

        $linker = $this->createLinker();
        $linker->consumeLoginLink($request);
    }

    private function createSignatureHash(string $username, int $expires, array $extraFields = ['emailProperty' => 'ryan@symfonycasts.com', 'passwordProperty' => 'pwhash']): string
    {
        $hasher = new SignatureHasher($this->propertyAccessor, array_keys($extraFields), 's3cret');
        $user = new TestLoginLinkHandlerUser($username$extraFields['emailProperty'] ?? '', $extraFields['passwordProperty'] ?? '', $extraFields['lastAuthenticatedAt'] ?? null);

        return $hasher->computeSignatureHash($user$expires);
    }

    private function createLinker(array $options = [], array $extraProperties = ['emailProperty', 'passwordProperty']): LoginLinkHandler
    {
        $options = array_merge([
            'lifetime' => 600,
            'route_name' => 'app_check_login_link_route',
        ]$options);

        return new LoginLinkHandler($this->router, $this->userProvider, new SignatureHasher($this->propertyAccessor, $extraProperties, 's3cret', $this->expiredLinkStorage, $options['max_uses'] ?? null)$options);
    }
}
 $options);
    }

    public function createLoginLink(UserInterface $user, Request $request = null, int $lifetime = null): LoginLinkDetails
    {
        $expires = time() + ($lifetime ?: $this->options['lifetime']);
        $expiresAt = new \DateTimeImmutable('@'.$expires);

        $parameters = [
            'user' => $user->getUserIdentifier(),
            'expires' => $expires,
            'hash' => $this->signatureHasher->computeSignatureHash($user$expires),
        ];

        if ($request) {
            $currentRequestContext = $this->urlGenerator->getContext();
            $this->urlGenerator->setContext(
                (new RequestContext())
                    ->fromRequest($request)
                    ->setParameter('_locale', $request->getLocale())
            );
        }

        

    public function verifySignatureHash(UserInterface $user, int $expires, string $hash): void
    {
        if ($expires < time()) {
            throw new ExpiredSignatureException('Signature has expired.');
        }

        if (!hash_equals($hash$this->computeSignatureHash($user$expires))) {
            throw new InvalidSignatureException('Invalid or expired signature.');
        }

        if ($this->expiredSignaturesStorage && $this->maxUses) {
            if ($this->expiredSignaturesStorage->countUsages($hash) >= $this->maxUses) {
                throw new ExpiredSignatureException(sprintf('Signature can only be used "%d" times.', $this->maxUses));
            }

            $this->expiredSignaturesStorage->incrementUsages($hash);
        }
    }

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