missing jwt options in token using nodejs jsonwebtoken

I am using jsonwebtoken to handle the token generation and verification on the server side.

The way I did it is once user auth successfully, I sign the ‘user’ object directly to generate the token like this:

var token = jwt.sign(user, secret.secretToken, {expiresInMinutes: 60, issuer: 'cccg', algorithm:'HS384'});

I found my token never expires. After debugging(you can jwt decode you token here), i found no ‘exp’ is included in the token.  So i tried to sign the id instead.

var token = jwt.sign(user._id, secret.secretToken, {expiresInMinutes: 1, issuer: 'cccg', algorithm:'HS384'});

Still not working. So i had to dive into the jwt source code, in the sign function, it checks the existence of the option and assign it directly to the payload object.

module.exports.sign = function(payload, secretOrPrivateKey, options) {
  options = options || {};

  var header = {typ: 'JWT', alg: options.algorithm || 'HS256'};

  payload.iat = Math.round(Date.now() / 1000);

  if (options.expiresInMinutes) {
    var ms = options.expiresInMinutes * 60;
    payload.exp = payload.iat + ms;

  if (options.audience)
    payload.aud = options.audience;

  if (options.issuer)
    payload.iss = options.issuer;

  if (options.subject)
    payload.sub = options.subject;

  var signed = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey});

  return signed;


Now we could do it in the right way by passing a js object as a payload so that the exp/issuer/etc could be picked up.

var token = jwt.sign({id:user._id}, secret.secretToken, {expiresInMinutes: 1, issuer: 'cccg', algorithm:'HS384'});


PS the token generation in the ‘jws’ module’s jwssign function is pretty straight forward. It just turn the header and payload into base64 and concatenate with ‘.’, then generate signature and turn into base64 and concatenate, so that the 3 parts of the token is generated. See my other POST’s bottom for detail jwt structure


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s