jwt module

The jwt module offers a set of APIs to create and validate a JSON Web Token (JWT).

To access the functions in the jwt module, use the require('jwt') statement.

The encoder object is a constructor for the JWT encoder, which provides functions to create a JWT.
The decoder object is a constructor for JWT decoder, which provides functions to validate and extract claims from a JWT.

Encoder.addOperation()

Adds a sign or encrypt operation to the JWT creation process.

Encoder.addOperation(operation, param)

Parameters

operation
The JWT creation operation name. The valid, case-sensitive values are 'sign' and 'encrypt'.
param
Parameters that are associated with the operation.

Guidelines

The Encoder.addOperation() method returns the encoder object.
  • When the operation is 'sign', the parameter must be a JWSHeader object.
  • When the operation parameter is 'encrypt', the parameter must be a JWEHeader object.

Encoder.encode()

An asynchronous function that performs the JWT creating operations that is added through the addOperation() calls and passes the creation to the function callback.

Encoder.encode(callback)

Parameters

callback
The function that receives the JWT creation result.

Guidelines

The order in which operations are added is the order that they are run.

The callback function takes two arguments.
error
Not null, if there is an error during the asynchronous encoding process.
token
The created JWT, if there is no error.

jwt.Encoder()

Creates a new JWT encoder.

jwt.Encoder(claims)

Parameters

claims
A JSON object that contains the claims to be conveyed by the created JWT. A claim is represented as a name-value pair that consists of a claim name and a claim value. A claim name is always a string. A claim value can be any JSON value.

Example

Creating a JWT.
var jose = require('jose');
var jwt = require('jwt');

var claims = { 'iss': 'ibm',
               'aud': ['datapower','gatewayscript'],
               'exp': (new Date()/1000) + 60*60,  // expire in 60 mins
             };

// use HS256 algorithm and key 'Alice' to sign
var jwsHeader = jose.createJWSHeader('Alice', 'HS256');

// use A128CBC-HS256 algorithm and key '32bytes' to encrypt
var jweHeader = jose.createJWEHeader('A128CBC-HS256')
                    .setProtected('alg', 'dir')
                    .setKey('32bytes');

var encoder = new jwt.Encoder(claims);

// create a nest JWT - sign then encrypt
// set 'cty' header to "JWT" to comply with the JWT spec
encoder.addOperation('sign', jwsHeader)
       .addOperation('encrypt', jweHeader.setProtected('cty', 'JWT'))
       .encode(function(error, token) {
          if (error) {
            session.output.write('error creating JWT: ' + error);
          } else {
            // write the JWT token to output
            session.output.write(token);
          }
       });

Decoder.addOperation()

Adds a verify, decrypt, or validate operation to the JWT claims extraction process.

Decoder.addOperation([options, ]operation, param)

Parameters

options
An optional parameter that changes the behavior of the added operation.
operation
The JWT claims extraction operation name. The valid, case-sensitive values are 'verify', 'decrypt', and 'validate'.
param
Parameters that are associated with the operation.

Guidelines

The Decoder.addOperation() method returns the decoder object.

Rules for the options parameter.

  • If the operation is 'validate', the options parameter must be a JSON object with the following defaults.
    {
      validateDataType: true,
      validateAudience: true,
      validateExpiration: true,
      validateNotBefore: true,
    }
    • When validateDataType is true, the validate operation performs data type validation on the registered claim names. The 'iss' and 'jti' claim value must be a string; the 'aud' claim value must be a case-sensitive string or an array of case-sensitive strings; the 'exp', 'nbf', and 'iat' claim value must be a number that represents the date/time.
    • When validateAudience is true, the validate operation validates the JWT 'aud' claim, which identifies the recipients that the JWT is intended for. The 'aud' claim value must be a case-sensitive string or an array of case-sensitive strings. If the 'aud' claim of JWT object for the param parameter does not exist or does not match a value in the JWT 'aud' claim, the validation fails.
    • When validateExpiration is true, the validate operation will validate the JWT 'exp' claim, which identifies the expiration time on or after the JWT must not be accepted for processing. If the current date/time is after or equal to the 'exp' claim date/time, the validation will fail.
    • When validateNotBefore is true, the validate operation validates the JWT 'nbf' claim and identifies the time before the JWT must not be accepted for processing. If the current date/time is before to the 'nbf' claim date/time, the validation fails.
  • Rules for the param parameter.
    • If the operation is 'verify' or 'decrypt', the param parameter must be a key to verify or decrypt the JWT. The key material can be a string, Buffer, Buffers, JWK, JWK Set, or and an object that contains the 'key' and 'passphrase' properties.
    • If the operation is 'validate' , the param parameter is optional. If it is present, it must be a JWT object. The 'aud' claim must be a case-sensitive string. When the validateAudience property of the JSON object for the options parameter is true, the validate operation checks whether the 'aud' claim of JWT object for the param parameter value matches a value in the JWT 'aud' claim.

Examples

  • Validate the JWT claims successfully when the param parameter has a matched 'aud' claim value. In this example, the 'aud' claim must contain datapower.
    decoder.addOperation('verify', 'Alice2048RSA')
        .addOperation('validate', {'aud': 'datapower'}) 
        .decode(function(error, claims){...});
  • Validate the JWT claims successfully when the param parameter has a matched 'aud' claim value. In this example, the 'aud' claim must contain both datapower and hugo.
    decoder.addOperation('verify', 'Alice2048RSA')
           .addOperation('validate', {'aud': 'datapower'})
           .addOperation('validate', {'aud': 'hugo'})
           .decode(function(error, claims) {...});
    

Decoder.decode()

An asynchronous function. It performs the JWT extracting operations added through the addOperation() calls and returns the extraction to the function callback.

Decoder.decode(callback)

Parameters

callback
The function that receives the JWT extracting result.

Guidelines

The order in which operations are added is the order that they are run.

The callback function takes two arguments.
error
Not null, if there is an error during the asynchronous decoding process.
token
The claims that are conveyed in the JWT, if there is no error.

jwt.Decoder()

jwt.Decoder(token)

Parameters

token
A JWT.

Example

Validating a JWT token.
var jwt = require('jwt');
session.input.readAsBuffer(function(error, buff) {
  if (error) {
    session.output.write('unable to read from input: ' + error);
  } else {
    var jwtToken = buff.toString();
    var decoder = new jwt.Decoder(jwtToken);
    decoder.addOperation('decrypt', '32bytes') // decrypt with key '32bytes'
           .addOperation('verify', 'Alice')    // verify with key 'Alice'
           .addOperation('validate', {'aud': 'datapower'}) // validate JWT
           .decode(function(error, claims) {
              if (error) {
                session.output.write('error validating JWT ' + error);
              } else {
                // write the JWT claims to output
                session.output.write(claims);
              }
           });
  }
});