Final Class Yiisoft\Csrf\Hmac\HmacCsrfToken
| Inheritance | Yiisoft\Csrf\Hmac\HmacCsrfToken |
|---|---|
| Implements | Yiisoft\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.
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\Csrf\Hmac\HmacCsrfToken | |
| getValue() | Yiisoft\Csrf\Hmac\HmacCsrfToken | |
| validate() | Yiisoft\Csrf\Hmac\HmacCsrfToken |
Method Details
| 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;
}
| public getValue( ): string |
public function getValue(): string
{
return $this->generateToken(
$this->lifetime === null ? null : (time() + $this->lifetime),
);
}
| 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();
}
Signup or Login in order to comment.