Site icon Tutorial

JSON Web Tokens (JWT)

JSON web tokens are text strings that can be used by client and server to authenticate and share information easily. If you remember the necessary authentication, we do write information to the client by writing the cookie as a session variable. However, in JWT, a token is encoded from a data payload using a secret. That token is passed to the client. Whenever the client sends that token along with a request, the server validates it and sends back the response. See this diagram for a clear picture.

We can summarise above picture into following points:

jsonwebtoken

An implementation of JSON Web Tokens. This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws

Installation – $ npm install jsonwebtoken

Usage

jwt.sign(payload, secretOrPrivateKey, [options, callback])

(Asynchronous) If a callback is supplied, the callback is called with the err or the JWT.

(Synchronous) Returns the JsonWebToken as string

payload could be an object literal, buffer or string representing valid JSON.

Please note that exp or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity. If payload is not a buffer or a string, it will be coerced into a string using JSON.stringify.

secretOrPrivateKey is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.

options:

There are no default values for expiresIn, notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, but you can’t include in both places. Remember that exp, nbf and iat are NumericDate, see related Token Expiration (exp claim)

The header can be customized via the options.header object. Generated jwts will include an iat (issued at) claim by default unless noTimestamp is specified. If iat is inserted in the payload, it will be used instead of the real timestamp for calculating other things like exp given a timespan in options.expiresIn.

Synchronous Sign with default (HMAC SHA256)

var jwt = require(‘jsonwebtoken’);

var token = jwt.sign({ foo: ‘bar’ }, ‘shhhhh’);

Synchronous Sign with RSA SHA256

// sign with RSA SHA256

var cert = fs.readFileSync(‘private.key’);

var token = jwt.sign({ foo: ‘bar’ }, cert, { algorithm: ‘RS256’});

Sign asynchronously

jwt.sign({ foo: ‘bar’ }, cert, { algorithm: ‘RS256’ }, function(err, token) {

console.log(token);

});

 

Backdate a jwt 30 seconds

var older_token = jwt.sign({ foo: ‘bar’, iat: Math.floor(Date.now() / 1000) – 3

Exit mobile version