This document describes the Jwt library available in the JavaScript environment for app services. It provides functionality for handling JSON Web Tokens (JWT), including signing, verifying, and decoding.
| Object | Jwt |
| Functions |
sign verify decode |
| Object |
Jwt.Key |
| Functions |
fromSecret fromEcRaw fromPem toPem toPemPublic |
| Reference |
Error Codes |
Generates a signed JWT string using the specified payload and key.
| object payload | The JSON object to be signed as the token payload. |
| object options |
An object containing configuration for the signing process. key (Required): The key to use for signing. Can be a Key object created via Jwt.Key, a raw key (private key for ES256, secret for HS256), or for ES256 an EC private key in PEM format (string starting with -----BEGIN ...).alg (Optional): The algorithm to use. Supported values are "ES256" (default) and "HS256". header (Optional): An object containing additional header fields to be merged with the default header. |
| string | The compact JWT string (header.payload.signature). |
var key = Jwt.Key.fromSecret("mySuperSecret", { kid: "key1" });
var token = Jwt.sign({ sub: "user123", role: "admin" }, { key: key, alg: "HS256" });
Verifies a JWT signature and validates standard claims.
| string token | The JWT string to verify. |
| object options |
Required. An object containing verification parameters. key (Required): The key used to verify the signature. Can be a Key object, a raw key (public key for ES256, secret for HS256), or for ES256 an EC public/private key in PEM format (string starting with -----BEGIN ...).algorithms (Optional): An array of strings specifying allowed algorithms (e.g. ["ES256", "HS256"]). If provided, the token's algorithm must be in this list. issuer (Optional): A string or array of strings. If provided, checks if the "iss" claim matches one of the values. audience (Optional): A string or array of strings. If provided, checks if the "aud" claim matches (supports intersection of arrays). subject (Optional): A string. If provided, checks if the "sub" claim matches exactly. clockTolerance (Optional): Number of seconds to tolerate when checking "exp" and "nbf" claims. Defaults to 0. |
| object | The decoded payload object if verification is successful. |
This function validates exp (Expiration), nbf (Not Before), iss (Issuer), aud (Audience), and sub (Subject) if the corresponding options are provided. See Error Codes for failure conditions.
try {
var payload = Jwt.verify(token, {
key: publicKey,
algorithms: ["ES256"],
issuer: "my-auth-server",
audience: "my-app"
});
log("Verified user: " + payload.sub);
} catch (e) {
log("Verification failed: code=" + e.code + " message=" + e.message);
}
Decodes a JWT without verifying the signature. Use with caution.
| string token | The JWT string to decode. Jwt.decode() accepts tokens that have at least a header and payload part; the signature part is optional. |
| object options |
Optional configuration. complete (Optional): If true, returns an object containing the header, payload, and signature. If false (default), returns only the payload. |
| object | The payload object (default) or the complete token structure. |
// Get just the payload
var payload = Jwt.decode(token);
// Get the full structure
var decoded = Jwt.decode(token, { complete: true });
log("Algorithm used: " + decoded.header.alg);
Helper object to create standardized key structures for use with Jwt functions.
Key objects returned by the Jwt.Key helper functions are plain JavaScript objects with a standardized structure. These objects can be inspected, serialized, or passed directly to Jwt.sign() and Jwt.verify().
| kty | Key Type. Set to "oct" for symmetric keys (HS256) or "EC" for elliptic curve keys (ES256). |
| alg | Algorithm. Set to "HS256" for HMAC-SHA256 or "ES256" for ECDSA with P-256 curve. |
| use | Public Key Use. Always set to "sig" (signature) for JWT signing/verification keys. |
| kid | Key ID (optional). A string identifier for the key, useful when managing multiple keys. Automatically included in JWT header if present. |
| secret | The shared secret (string or Uint8Array) used for HMAC signing and verification. |
// Example HS256 Key Object structure:
var key = Jwt.Key.fromSecret("mySecret", { kid: "key1" });
// Returns: { kty: "oct", alg: "HS256", use: "sig", secret: "mySecret", kid: "key1" }
| privateKey | The EC private key as a Uint8Array (32 bytes for P-256). Required for signing, set to null if not available. |
| publicKey | The EC public key as a Uint8Array (65 bytes for uncompressed P-256 point). Required for verification, set to null if not available. |
// Example ES256 Key Object structure:
var key = Jwt.Key.fromEcRaw({
privateKey: privateKeyBytes, // Uint8Array, 32 bytes
publicKey: publicKeyBytes, // Uint8Array, 65 bytes
kid: "ec-key-1"
});
// Returns: { kty: "EC", alg: "ES256", use: "sig", privateKey: ..., publicKey: ..., kid: "ec-key-1" }
// Key with only public part (for verification):
var pubKey = Jwt.Key.fromEcRaw({ publicKey: publicKeyBytes });
// Returns: { kty: "EC", alg: "ES256", use: "sig", privateKey: null, publicKey: ..., kid: undefined }
Key objects are designed to be interoperable and can be serialized to JSON (except for Uint8Array properties, which should be converted to hex or base64 for storage).
The Jwt.Key helper functions normalize various input formats (raw keys, PEM strings) into this standardized structure.
When a Key object is passed to Jwt.sign() or Jwt.verify(), the library validates that the required key material (secret, privateKey, or publicKey) is present for the requested operation.
Creates a key object for symmetric algorithms (HS256).
| string/Uint8Array secret | The shared secret. |
| object opts |
Optional parameters. kid (Optional): Key ID to associate with this key. |
| object | A Key object configured for HS256. |
var hmacKey = Jwt.Key.fromSecret("secretPassword", { kid: "k1" });
Creates a key object for Elliptic Curve algorithms (ES256).
| object opts |
Configuration object. privateKey (Optional): The private key. Uint8Array is preferred, but hex strings are accepted. publicKey (Optional): The public key. Uint8Array is preferred, but hex strings are accepted. kid (Optional): Key ID to associate with this key. |
| object | A Key object configured for ES256. |
While this function accepts hex strings, it is recommended to use Encoding.hexToBin() to pass explicit Uint8Arrays, as this avoids ambiguity and matches the underlying Crypto library expectations.
var ecKey = Jwt.Key.fromEcRaw({
privateKey: Encoding.hexToBin("..."),
publicKey: Encoding.hexToBin("...")
});
Creates an ES256 EC key object from a PEM-encoded key.
| string pem | The PEM string, including header and footer lines such as -----BEGIN PRIVATE KEY-----, -----BEGIN EC PRIVATE KEY-----, or -----BEGIN PUBLIC KEY-----. |
| object opts |
Optional parameters. kid (Optional): Key ID to associate with this key. alg (Optional): Algorithm name. Defaults to "ES256". |
| object | An EC Key object configured for ES256, with privateKey and/or publicKey populated from the PEM contents. |
The PEM parser supports standard PKCS#8 (PrivateKeyInfo) and RFC 5915 (ECPrivateKey) formats for EC P-256 keys, as well as SubjectPublicKeyInfo for public keys. The implementation relies on Encoding.base64ToBin being available. If both private and public key material are present in the PEM, both will be extracted.
var pem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----";
var key = Jwt.Key.fromPem(pem, { kid: "ec1" });
var payload = Jwt.verify(token, {
key: key,
algorithms: ["ES256"]
});
Exports an EC (ES256) key object to a standard PEM-encoded string.
| object key | An EC key object as returned by Jwt.Key.fromEcRaw or Jwt.Key.fromPem (with kty: "EC" and alg: "ES256"). |
| string | A PEM string containing the key material. If both privateKey and publicKey are present, they are encoded in a single standard PKCS#8 -----BEGIN PRIVATE KEY----- block which embeds the public key. If only the public key is present, a -----BEGIN PUBLIC KEY----- block is returned. |
The output format is a private key with embedded public key, the resulting PEM uses the PKCS#8 format wrapping an RFC 5915 structure.
var key = Jwt.Key.fromEcRaw({
privateKey: Encoding.hexToBin("..."),
publicKey: Encoding.hexToBin("...")
});
var pem = Jwt.Key.toPem(key);
// pem can now be stored or transported and later re-imported with Jwt.Key.fromPem()
Exports only the public part of an EC key object to a PEM-encoded string.
| object key | An EC key object with a populated publicKey field. |
| string | A -----BEGIN PUBLIC KEY----- PEM string containing only the public key material. |
// Example: Generate a key pair and export to separate PEM files
try {
var ecdsa = Crypto.ecdsa("ES256", null, null);
var privateKeyRaw = ecdsa.private(true); // true for Uint8Array output
var publicKeyRaw = ecdsa.public(true);
var keyPair = Jwt.Key.fromEcRaw({
privateKey: privateKeyRaw,
publicKey: publicKeyRaw,
kid: "my-app-jwt-key"
});
var publicKeyPem = Jwt.Key.toPemPublic(keyPair);
// Store or transmit publicKeyPem for token verification
} catch (error) {
log("PEM conversion error: " + error.message);
} finally {
ecdsa.close();
}
When an error occurs, the Error object thrown will contain a code property with one of the following values:
| malformed_token | The token string is not a valid JWT (for example, it has an invalid number of parts for the given operation—verify() expects exactly three parts, while decode() requires at least two—or it contains invalid Base64 or invalid JSON). |
| key_required | The options object or the key property is missing. |
| key_error | The provided key is invalid or missing a required component (e.g. missing privateKey for signing). |
| invalid_key | The key material could not be interpreted for the requested algorithm (use Jwt.Key helpers, a supported raw key type, or for ES256 a supported PEM key). |
| alg_mismatch | In Jwt.sign(), the key algorithm (key.alg) does not match the requested algorithm (options.alg). |
| unsupported_algorithm | The algorithm is not supported or not permitted (e.g. the header alg is not in options.algorithms, the algorithm is not implemented by this library, or in verify() a key with a different alg than the token header is provided). |
| signature_invalid | The signature verification failed. |
| token_expired | The current time is past the "exp" claim (plus clock tolerance). |
| token_not_yet_valid | The current time is before the "nbf" claim (minus clock tolerance). |
| issuer_invalid | The "iss" claim does not match the expected issuer. |
| audience_invalid | The "aud" claim does not match the expected audience. |
| subject_invalid | The "sub" claim does not match the expected subject. |
| invalid_pem | The provided PEM string does not contain recognizable EC key material or is missing header/footer lines. |
| pem_unsupported_key | PEM export is only supported for EC keys. Thrown by Jwt.Key.toPem() and Jwt.Key.toPemPublic() when the key type is not "EC". |
| pem_no_key_material | The EC key has neither privateKey nor publicKey material to export. Thrown by Jwt.Key.toPem() when attempting to export an empty key. |
| pem_no_public | The EC key has no publicKey material. Thrown by Jwt.Key.toPemPublic() when attempting to export a public key that doesn't exist. |
| pem_der_error | An internal error occurred during DER encoding for PEM export (e.g., negative length value). |