jwtEncode()

Returns an encoded JSON Web Token (JWT).

Synopsis

string jwtEncode(string payload, string key [, string algorithm ]);

Parameters

Parameter Description
payload

A valid JSON object.

Note:
The validity of the object is not checked by this function.
key

The encoding key.

Note:
It must be at least 32 characters long.
algorithm The optional parameter to specify the signing algorithm used to sign the JWT. The following values are supported (see also here):
  • HS256
  • HS384
  • HS512
  • RS256
  • RS384
  • RS512
The default value is "HS256" to stay backwards compatible. When using "RSxxx" values, the key must contain a valid private RSA key.
Note:
Encoding a JWT without signing it (i.e.: setting algorithm as "none") is not supported.

Return value

Encoded and signed token.

Details

The function jwtEncode() returns an encoded JWT token containing "payload", signed with "key". The parameter "payload" must contain a valid JSON object, but this is not checked by this function. "HS256" is used as the default signing algorithm. If any problems are encountered (e.g:. the key being too short), an empty string is returned. The error details can be read with getLastError().

When using one of the RSxxx algorithms, jwtEncode() accepts the key parameter in two formats:

  • PKCS #8 (as before, typically PEM Base64 encoded)
  • JWK (JSON Web Key, as JSON string)

All key types are passed to the function as strings that are automatically recognized.

For further details and examples of valid key formats refer to the associated jwtDecode() function.

Assignment

File function

Availability

UI