我尝试使用Json Web Token(在article的帮助下)验证我的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;
});
答案 0 :(得分:3)
为了知道令牌的到期,jwt会向有效负载添加exp
属性。但是,将其传递给jwt.sign
时的有效负载是一个猫鼬对象,它将(静默地)不允许您添加未在架构中定义的属性。
解决方案应该是在将用户作为有效负载传递之前将用户转换为普通对象:
var token = jwt.sign(user.toObject(), "secret", {
expiresIn: 60
});
答案 1 :(得分:0)
var token = jwt.encode({ iss:' user', 到期时间:60 },' secretToken');
答案 2 :(得分:0)
同意@ploutch,效果很好!
var token = jwt.sign(user.toObject(), "secret", {
expiresIn: 60
});