Piwik\

Nonce

Nonce class.

A cryptographic nonce -- "number used only once" -- is often recommended as part of a robust defense against cross-site request forgery (CSRF/XSRF). This class provides static methods that create and manage nonce values.

Nonces in Matomo (formerly Piwik) are stored as a session variable and have a configurable expiration.

Learn more about nonces here.

Methods

The class defines the following methods:

getNonce()

Returns an existing nonce by ID.

If none exists, a new nonce will be generated.

Signature

  • It accepts the following parameter(s):
    • $id (string) — Unique id to avoid namespace conflicts, e.g., 'ModuleName.ActionName'.
    • $ttl (int) — Optional time-to-live in seconds; default is 5 minutes. (ie, in 5 minutes, the nonce will no longer be valid).
  • It returns a string value.

verifyNonce()

Returns if a nonce is valid and comes from a valid request.

A nonce is valid if it matches the current nonce and if the current nonce has not expired.

The request is valid if the referrer is a local URL (see Url::isLocalUrl()) and if the HTTP origin is valid (see getAcceptableOrigins()).

Signature

  • It accepts the following parameter(s):

    • $id (string) — The nonce's unique ID. See getNonce().
    • $cnonce (string) — Nonce sent from client.
  • Returns: booltrue if valid; false otherwise.

discardNonce()

Force expiration of the current nonce.

Signature

  • It accepts the following parameter(s):
    • $id (string) — The unique nonce ID.
  • It does not return anything.

getOrigin()

Returns the Origin HTTP header or false if not found.

Signature

  • Returns: string|bool

getAcceptableOrigins()

Returns a list acceptable values for the HTTP Origin header.

Signature

  • It returns a array value.

checkNonce()

Verifies and discards a nonce.

Signature

  • It accepts the following parameter(s):
    • $nonceName (string) — The nonce's unique ID. See getNonce().
    • $nonce (string|null) — The nonce from the client. If null, the value from the nonce query parameter is used.
  • It does not return anything.
  • It throws one of the following exceptions:
    • Exception — if the nonce is invalid. See {@link verifyNonce()}.