0 follower

Final Class Yiisoft\Csrf\Hmac\HmacCsrfToken

InheritanceYiisoft\Csrf\Hmac\HmacCsrfToken
ImplementsYiisoft\Csrf\CsrfTokenInterface

Stateless CSRF token that does not require any storage. The token is a hash from session ID and a timestamp (to prevent replay attacks). It is added to forms. When the form is submitted, we re-generate the token from the current session ID and a timestamp from the original token. If two hashes match, we check that timestamp is less than HmacCsrfToken::$lifetime.

The algorithm is also known as "HMAC Based Token".

Do not forget to decorate the token with Yiisoft\Csrf\MaskedCsrfToken to prevent BREACH attack.

Method Details

Hide inherited methods

__construct() public method

public __construct( Yiisoft\Csrf\Hmac\IdentityGenerator\CsrfTokenIdentityGeneratorInterface $identityGenerator, string $secretKey, string $algorithm 'sha256', integer|null $lifetime null ): mixed
$identityGenerator Yiisoft\Csrf\Hmac\IdentityGenerator\CsrfTokenIdentityGeneratorInterface
$secretKey string
$algorithm string
$lifetime integer|null

                public function __construct(
    CsrfTokenIdentityGeneratorInterface $identityGenerator,
    string $secretKey,
    string $algorithm = 'sha256',
    ?int $lifetime = null
) {
    $this->identityGenerator = $identityGenerator;
    $this->mac = new Mac($algorithm);
    $this->secretKey = $secretKey;
    $this->lifetime = $lifetime;
}

            
getValue() public method

public getValue( ): string

                public function getValue(): string
{
    return $this->generateToken(
        $this->lifetime === null ? null : (time() + $this->lifetime),
    );
}

            
validate() public method

public validate( string $token ): boolean
$token string

                public function validate(string $token): bool
{
    $data = $this->extractData($token);
    if ($data === null) {
        return false;
    }
    [$expiration, $identity] = $data;
    if ($expiration !== null && time() > $expiration) {
        return false;
    }
    return $identity === $this->identityGenerator->generate();
}