1

我正在尝试使用 Json Web 令牌(在本文的帮助下)对我的 nodejs api 进行身份验证,但问题是令牌永不过期。

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');




mongoose.connect('mongodb://localhost/gd');
var schema = mongoose.Schema;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var router = express.Router();

app.use('/api', router);

var userSchema = new schema({
   username: String,
   password: String
},{
    collection: 'users'
});

var User = mongoose.model('User', userSchema);



router.post('/authenticate', function(req, res) {

  User.findOne({
    username: req.body.username
  }, function(err, user) {

    if (err) throw err;

    if (!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {

      if (user.password != req.body.password) {
        res.json({ success: false, message: 'Authentication failed. Wrong password.' });
      } else {

        var token = jwt.sign(user, "secret", {
          expiresIn: 60
        });

        res.json({
          success: true,
          message: 'Enjoy your token!',
          token: token
        });
      }   

    }

  });
});



router.use(function(req, res, next) {

  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  if (token) {

    jwt.verify(token, "secret", function(err, decoded) {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        req.decoded = decoded;    
        next();
      }
    });

  } else {

    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });

  }
});

router.get('/users', function(req, res) {
  User.find({}, function(err, users) {
    res.json(users);
  });
});  

var server = app.listen(3001, function () {
  var host = server.address().address;
  var port = server.address().port;

});
4

3 回答 3

3

为了知道令牌的到期时间,jwtexp向有效负载添加了一个属性。但是,当您将其传递给您的有效负载时,它jwt.sign是一个 mongoose 对象,它将(默默地)不允许您添加架构中未定义的属性。

解决方案应该是在将用户作为有效负载传递之前将其转换为普通对象:

var token = jwt.sign(user.toObject(), "secret", {
  expiresIn: 60
});
于 2015-10-22T08:41:16.357 回答
0

同意@ploutch,这很好用!

var token = jwt.sign(user.toObject(), "secret", {
  expiresIn: 60
});
于 2019-03-21T10:47:37.930 回答
0

下面的片段对我有用..

var token = jwt.encode({ iss: 'user', expiresIn: 60 }, 'secretToken');

于 2017-03-27T21:42:32.177 回答