在Cookie或本地存储(node/angular 2网站)中保存JWT
问题描述:
我知道jwt可以保存在本地存储或cookie中。但我无法在网上找到一份好的材料以获得指导。我如何指示服务器识别未来会话的用户。在Cookie或本地存储(node/angular 2网站)中保存JWT
//authenticating users by username
router.route('/authentication').post(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) {
// check if password matches
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
} else {
// if user is found and password is right
// create a token
var token = jwt.sign({usern : user.username}, app.get('superSecret'), {
//expiresInMinutes: 1440 // expires in 24 hours
});
res.cookie('auth',token);
// return the information including token as JSON
res.setHeader('token', token);
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
})
app.use('/api', router);
答
令牌不需要在服务器上保存,这是令牌最好的事情之一。 在服务器中,您需要检查“嘿,这个标记是由我签署的吗?这个标记已过期?”。 这样的代码:
nJwt.verify(token, secretKey, function(err, jwt){
if (err) {
// something wrong
}
}
是的但是服务器如何检索令牌?创建一个令牌后,它保存在客户端? –
创建令牌后,发送给客户端。在客户端,您应该将令牌保存在变量中,并将每个请求再次发送给服务器。 – farbod
我试过res.cookie('auth',令牌),它不工作。你的建议是什么? –