jwtDecode()

The function decodes a JSON Web Token (JWT).

Synopsis

string jwtDecode(string jwt, string key [, string algorithm] [, bool ignoreSignature = false]);

Parameters

Parameter Description
jwt The JWT token.
key The key, which was used to sign the JWT token.
algorithm The optional parameter specifying the expected signing algorithm used to decode the JWT. Decoding will only work if these algorithms match. Possible values and the default value are the same as forjwtEncode(). Similarly, the use of "RSxxx" values means that the key must contain the public RSA key matching the private RSA key used for signing.
ignoreSignature Decides if the signature is used or not.

Description

The function returns the payload contained in the string "jwt", if it has been signed with "key", using the signing algorithm "HS256". If any problems are encountered (e.g.: invalid signature, wrong key, token not correctly encoded), an empty string is returned. The error details can be read with getLastError().

If the parameter "ignoreSignature" is set to "true", the the payload of the JWT token is also returned when key is wrong (or just an empty string). When this flag is set, it is not checked whether the JWT token contains valid information or has been manipulated, so the information in the payload cannot be trusted.

"algorithm":

Although the JWT header contains the name of the algorithm that was used for signing, this alone is not sufficient to securely determine the signing algorithm used, because attackers could modify this information and create a token signed with a different algorithm. For backwards compatibility, all the following combinations of parameters are valid:
  • jwtDecode(jwt, key);
  • jwtDecode(jwt, key, ignoreSignature);
  • jwtDecode(jwt, key, algorithm);
  • jwtDecode(jwt, key, algorithm, ignoreSignature);
For "RSxx" algorithms, a RSA public/private key pair is needed. These will normally be read from a file, e.g.:
string priKey, pubKey;
fileToString(getPath(DATA_REL_PATH, "jwt_private_key.pem"), priKey);
fileToString(getPath(DATA_REL_PATH, "jwt_public_key.pem"), pubKey);

string jwt = jwtEncode(payloadToEncode, priKey, "RS256");
string payload = jwtDecode(jwtToDecode, pubKey, "RS256");
VORSICHT: In a production system, the private key must not be stored within the project directory structure.

Assignment

File function

Availability

UI