Jwt

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.

Table of content

Object Jwt
Functions sign
verify
decode

Object Jwt.Key
Functions fromSecret
fromEcRaw
fromPem
toPem
toPemPublic

Reference Error Codes

Jwt

sign

Generates a signed JWT string using the specified payload and key.

Parameters

object payloadThe 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.

Return value

stringThe 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" });
verify

Verifies a JWT signature and validates standard claims.

Parameters

string tokenThe 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.

Return value

objectThe decoded payload object if verification is successful.

Remarks

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);
}
decode

Decodes a JWT without verifying the signature. Use with caution.

Parameters

string tokenThe 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.

Return value

objectThe 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);

Jwt.Key

Helper object to create standardized key structures for use with Jwt functions.

Key Object Structure

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().

Common Properties

ktyKey Type. Set to "oct" for symmetric keys (HS256) or "EC" for elliptic curve keys (ES256).
algAlgorithm. Set to "HS256" for HMAC-SHA256 or "ES256" for ECDSA with P-256 curve.
usePublic Key Use. Always set to "sig" (signature) for JWT signing/verification keys.
kidKey ID (optional). A string identifier for the key, useful when managing multiple keys. Automatically included in JWT header if present.

HS256 (Symmetric) Key Properties

secretThe 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" }

ES256 (Elliptic Curve) Key Properties

privateKeyThe EC private key as a Uint8Array (32 bytes for P-256). Required for signing, set to null if not available.
publicKeyThe 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 }

Remarks

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.

fromSecret

Creates a key object for symmetric algorithms (HS256).

Parameters

string/Uint8Array secretThe shared secret.
object opts Optional parameters.
kid (Optional): Key ID to associate with this key.

Return value

objectA Key object configured for HS256.
var hmacKey = Jwt.Key.fromSecret("secretPassword", { kid: "k1" });
fromEcRaw

Creates a key object for Elliptic Curve algorithms (ES256).

Parameters

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.

Return value

objectA Key object configured for ES256.

Remarks

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("...") 
});
fromPem

Creates an ES256 EC key object from a PEM-encoded key.

Parameters

string pemThe 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".

Return value

objectAn EC Key object configured for ES256, with privateKey and/or publicKey populated from the PEM contents.

Remarks

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"]
});
toPem

Exports an EC (ES256) key object to a standard PEM-encoded string.

Parameters

object keyAn EC key object as returned by Jwt.Key.fromEcRaw or Jwt.Key.fromPem (with kty: "EC" and alg: "ES256").

Return value

stringA 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.

Remarks

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()
toPemPublic

Exports only the public part of an EC key object to a PEM-encoded string.

Parameters

object keyAn EC key object with a populated publicKey field.

Return value

stringA -----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();
}

Error Codes

When an error occurs, the Error object thrown will contain a code property with one of the following values:

malformed_tokenThe 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_requiredThe options object or the key property is missing.
key_errorThe provided key is invalid or missing a required component (e.g. missing privateKey for signing).
invalid_keyThe 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_mismatchIn Jwt.sign(), the key algorithm (key.alg) does not match the requested algorithm (options.alg).
unsupported_algorithmThe 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_invalidThe signature verification failed.
token_expiredThe current time is past the "exp" claim (plus clock tolerance).
token_not_yet_validThe current time is before the "nbf" claim (minus clock tolerance).
issuer_invalidThe "iss" claim does not match the expected issuer.
audience_invalidThe "aud" claim does not match the expected audience.
subject_invalidThe "sub" claim does not match the expected subject.
invalid_pemThe provided PEM string does not contain recognizable EC key material or is missing header/footer lines.
pem_unsupported_keyPEM 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_materialThe EC key has neither privateKey nor publicKey material to export. Thrown by Jwt.Key.toPem() when attempting to export an empty key.
pem_no_publicThe EC key has no publicKey material. Thrown by Jwt.Key.toPemPublic() when attempting to export a public key that doesn't exist.
pem_der_errorAn internal error occurred during DER encoding for PEM export (e.g., negative length value).