简体   繁体   中英

How can i expire a jwt in node js?

I'm using the jsonwebtoken module in npm and I'm trying to expire the token but it seems that it doesn't expire. Here's my code:

app.post('/token', function(req, res) {
  name = 'Name'
  var token = jwt2.sign(name, secret, { expiresInMinutes: 5 });
  res.end(token);
});

I use this token later here:

app.post('/feed', function(req, res) { 
  console.log('hiiiiii');
  token = req.body.token;

  console.log('access-token :' + token);
  jwt2.verify(token, 'secret', function(err, decoded) {
    if (err) {
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
      console.log(err.name);
    } else {
      console.log('decoded token:' + decoded);
      res.end(decoded);
    }
  });
});

Here's a minimal test case to show an example of it working as intended:

'use strict';
var jwt = require('jsonwebtoken');

var token = jwt.sign({ foo: 'bar' }, 'shhhhh', { expiresInMinutes: 1});

console.log(token);

setTimeout(function() {
    jwt.verify(token, 'shhhhh', function(err, decoded) {
        if(err) {
            console.error('err: ', err);
        } else {
            console.log('decoded: ', decoded);
        }
    });
}, 1000 * 62);

When running this test case I get the following output:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE0MTQ5Mzk5MTYsImV4cCI6MTQxNDkzOTk3Nn0.O5zrNrkrhPk_2RekdRwm-nTbHvDIWhsjf_uSWLPfdJQ
  err:  { [TokenExpiredError: jwt expired]
  name: 'TokenExpiredError',
  message: 'jwt expired',
  expiredAt: Sun Nov 02 2014 09:52:56 GMT-0500 (EST) }

You're signing the token with a variable secret while verifying it with the string 'secret'. Could this be the issue?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM