0

Final Class Yiisoft\Csrf\Hmac\HmacCsrfToken

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

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 \Yiisoft\Csrf\MaskedCsrfToken} to prevent BREACH attack.

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( Yiisoft\Csrf\Hmac\IdentityGenerator\CsrfTokenIdentityGeneratorInterface $identityGenerator, string $secretKey, string $algorithm = 'sha256', ?int $lifetime = null )
$identityGenerator Yiisoft\Csrf\Hmac\IdentityGenerator\CsrfTokenIdentityGeneratorInterface
$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;
}

            
getValue() public method

public string getValue ( )

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

            
validate() public method

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;
    }
}