使用节点将令牌保存在本地存储中 [英] Save Token in local Storage using node
问题描述
我正在使用带有Express 4和Jade的JWT ("jsonwebtoken": "^5.4.0")
.
我能够创建正确的令牌,但是如何在每次通话中传递此令牌?
我必须在哪里存储此令牌?在标题中还是在localStorage中?
I'm using JWT ("jsonwebtoken": "^5.4.0")
with express 4 and jade.
I'm able to create the right Token, but How can i Pass this token in each call?
Where I have to store this token ? in headers or in localStorage?
现在我将CURL与Postman一起使用,并在标头中设置令牌
For now I'm using CURL with Postman, and Set token in header in
x-access-token
我是否创建了一种中间件,该中间件从数据库中检索令牌并在每次调用中使用该令牌?
Have I Do create a middleware that retrieve a token from Database and use this in each call?
谢谢
推荐答案
您无需保存并从数据库中检查令牌.这种令牌这种机制只能用您的服务器来解码,并且如果已完成,则该令牌是有效的.您想要执行的代码应如下所示.
You do not need to save and check the token from the database. This token such a mechanism can be decoded with only your-server, and if it was done that the token is valid. The code that you want to do should look like.
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.get('/login', function(req, res, next) {
var user = {name:'test'}; //!! find the user and check user from db then
var token = jwt.sign(user, 'secret', {
expiresInMinutes: 1440
});
res.cookie('auth',token);
res.send('ok');
});
app.use(function(req, res, next) {
var token = req.cookies.auth;
// decode token
if (token) {
jwt.verify(token, 'secret', function(err, token_data) {
if (err) {
return res.status(403).send('Error');
} else {
req.user_data = token_data;
next();
}
});
} else {
return res.status(403).send('No token');
}
});
在这里您可以找到非常不错的文章: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
Here you can find very nice article : https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
这篇关于使用节点将令牌保存在本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!