我正在尝试使用 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;
});