anvarik
anvarik

Reputation: 6487

Json web token does not expire

I just implemented a json web token authentication, on my backend I send the token which is created by jsonwebtoken to the client as following:

var token = jwt.sign(user, secret.secretToken, { expiresInMinutes: 1 });
return res.json({ token: token });

and on the client side I simply store this token to the SessionStorage. The thing is that the token does not expire after a minute, am I missing something?

EDIT: I implemented same thing which is shown in this post.

Upvotes: 9

Views: 24530

Answers (3)

ashwath hegde
ashwath hegde

Reputation: 656

//use this to create the token

  var token = jwt.sign({
  exp: "1h",
  data: "payload"
   }, "secret");

/*while checking the token ,Throws error if the token is expired else you will get the decoded data*/

jwt.verify(token, 'secret', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

Upvotes: 0

Marius de Vries
Marius de Vries

Reputation: 361

I found myself having the same problem when not providing an object as the first argument to jwt.sign, e.g. jwt.sign('testuser', secret.secretToken, { expiresIn: '1h' });.

This wrong usage of jwt.sign does work even though it is wrong, it just ignores the provided settings. https://github.com/auth0/node-jsonwebtoken/issues/64

Be sure to provide an object as first argument, like jwt.sign({user: 'testuser'}, secret.secretToken, { expiresIn: '1h' });

Update: There have been reported problems with usage of non standard javascript objects, such as from mongoose. Version 5.5.2 has a fix for this. More details here. Thanks @gugol for the notice. Make sure you pass a plain object with the properties you need, not a direct database object or similar.

Upvotes: 23

Davin Tryon
Davin Tryon

Reputation: 67336

The token will not automatically be deleted from the Session storage. However, if you try to verify that the token is valid, the expired token should be invalid.

From this tutorial, the validity check should throw an exception:

if (token) {
  try {
    var decoded = jwt.decode(token, app.get('jwtTokenSecret'));

    // handle token here

  } catch (err) {
    return next();
  }
} else {
  next();
}

Verify is also included in the jsonwebtoken package. And this is from the docs:

(Synchronous with callback) Returns the payload decoded if the signature (and optionally expiration, audience, issuer) are valid. If not, it will return the error.

Upvotes: 5

Related Questions