class CsrfTokenGenerator (View source)

Generates and validates CSRF tokens.

Properties

protected PrivateKey $privateKey

The private key service.

protected MetadataBag $sessionMetadata

The session metadata bag.

Methods

__construct(PrivateKey $private_key, MetadataBag $session_metadata)

Constructs the token generator.

string
get(string $value = '')

Generates a token based on $value, the user session, and the private key.

bool
validate(string $token, string $value = '')

Validates a token based on $value, the user session, and the private key.

string
computeToken(string $seed, string $value = '')

Generates a token based on $value, the token seed, and the private key.

Details

__construct(PrivateKey $private_key, MetadataBag $session_metadata)

Constructs the token generator.

Parameters

PrivateKey $private_key

The private key service.

MetadataBag $session_metadata

The session metadata bag.

string get(string $value = '')

Generates a token based on $value, the user session, and the private key.

The generated token is based on the session of the current user. Normally, anonymous users do not have a session, so the generated token will be different on every page request. To generate a token for users without a session, manually start a session prior to calling this function.

Parameters

string $value

(optional) An additional value to base the token on.

Return Value

string

A 43-character URL-safe token for validation, based on the token seed, the hash salt provided by Settings::getHashSalt(), and the 'drupal_private_key' configuration variable.

See also

Settings::getHashSalt
\Symfony\Component\HttpFoundation\Session\SessionInterface::start()

bool validate(string $token, string $value = '')

Validates a token based on $value, the user session, and the private key.

Parameters

string $token

The token to be validated.

string $value

(optional) An additional value to base the token on.

Return Value

bool

TRUE for a valid token, FALSE for an invalid token.

protected string computeToken(string $seed, string $value = '')

Generates a token based on $value, the token seed, and the private key.

Parameters

string $seed

The per-session token seed.

string $value

(optional) An additional value to base the token on.

Return Value

string

A 43-character URL-safe token for validation, based on the token seed, the hash salt provided by Settings::getHashSalt(), and the site private key.

See also

Settings::getHashSalt