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:

  • A client sends username/password combination to the server
  • The server validates the authentication
  • If authentication is successful, the server creates a JWT token else establishes an error response
  • On successful authentication, the client gets JWT token in the response body
  • Client stores that token in local storage or session storage.
  • From next time, the client for making any request supplies the JWT token in request headers like this. Authorization: Bearer <jwt_token>
  • Server upon receiving the JWT validates it and sends the successful response else error.

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:

  • algorithm (default: HS256)
  • expiresIn: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, “2 days”, “10h”, “7d”. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (“120” is equal to “120ms”).
  • notBefore: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, “2 days”, “10h”, “7d”. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (“120” is equal to “120ms”).
  • audience
  • issuer
  • jwtid
  • subject
  • noTimestamp
  • header
  • keyid
  • mutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.

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

Share this post
[social_warfare]
Authentication
Secure Coding

Get industry recognized certification – Contact us

keyboard_arrow_up