Nodejs authentication using JWT a.k.a JSON web token is very useful when you are developing cross-device authentication mechanism.

Here is how token based authentication works:

  • User logins to the system and upon successful authentication, the user are assigned a token which is unique and bounded by time limit say 15 minutes
  • On every subsequent API calls, the user provides the access token in order to consume the system resources.
  • When time is expired, the user has to login again to get new token

The last step is frustrating, we can’t ask users to log in each and every single time once the token is expired.

There are two ways to solve this:

  1. Increase the time of the token
  2. Use refresh token to extend the token

JWT Keys:

  1. jwt.sign 
  2. jwt.verify

/**     jwt.sign is used to genrate token using below expression:  **/

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

ex:

Synchronous Sign with default Algorithm (HMAC SHA256)

var jwt = require(jsonwebtoken); // node module require to install
var token = jwt.sign({ tokendata: ‘ data here }, shhhhh);
with Expiry time:
jwt.sign({
  exp: Math.floor(Date.now() / 1000) + (60 * 60),
tokendata: ‘ data here
}, secret);

Sign asynchronously with Algorithm (HMAC SHA256)

jwt.sign({ foo: bar },  { algorithm: RS256 }, function(err, token) {
  console.log(token);
});

 

/**     jwt.verify is used to validate token using below expression:  **/

 

// verify a token symmetric – synchronous
var decoded = jwt.verify(token, shhhhh);
console.log(decoded.foo) // bar
 
// verify a token symmetric
jwt.verify(token, shhhhh, function(err, decoded) {
  console.log(decoded.foo) // bar
});