Final Class Yiisoft\Csrf\Hmac\HmacCsrfToken
| Inheritance | Yiisoft\ |
|---|---|
| Implements | Yiisoft\ |
Stateless CSRF token that does not require any storage. The token contains an expiration timestamp and is signed with an identity-bound key. It is added to forms. When the form is submitted, we verify the token signature, check that it belongs to the current identity, and check that it has not expired.
Do not forget to decorate the token with {@see \
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __construct() | Yiisoft\ |
|
| getValue() | Yiisoft\ |
|
| validate() | Yiisoft\ |
Method Details
| public mixed __construct ( Yiisoft\ | ||
| $identityGenerator | Yiisoft\ |
|
| $secretKey | string | |
| $algorithm | string | |
| $lifetime | ?int | |
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->hashLength = $this->calcHashLength();
$this->lifetime = $lifetime;
}
| public string getValue ( ) |
public function getValue(): string
{
return $this->generateToken(
$this->lifetime === null ? null : (time() + $this->lifetime),
);
}
| public boolean validate ( string $token ) | ||
| $token | string | |
public function validate(string $token): bool
{
$raw = $this->decode($token);
$message = $this->extractMessage($raw);
if ($message === null) {
return false;
}
if ($message !== '') {
$expiration = (int) $message;
if ((string) $expiration !== $message || time() > $expiration) {
return false;
}
}
try {
$this->mac->getMessage($raw, $this->generateActualSecretKey(), true);
return true;
} catch (DataIsTamperedException $e) {
return false;
}
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.