[英]Node.js JWT, get user_id from token
strong textI am building node.js + mongodb rest api.强文本我正在构建 node.js + mongodb rest api。 I use jwt user auth and I have a problem.
我使用 jwt 用户身份验证,但遇到问题。 I need to get details of authenticated user (user_id, name), think they can be obtained from token, but I dont know how to do this.
我需要获取经过身份验证的用户(user_id,名称)的详细信息,认为可以从令牌中获取它们,但我不知道该怎么做。 How is it possible to do?
这怎么可能呢?
UPDATED更新
I am doing a post request我正在做一个帖子请求
router.route('/articles')
.post(function (req, res) {
var article= new Article();
article.user_id = ???; // here needs user_id
article.imdb_id = req.body.imdb_id;
article.title = req.body.title;
article.thumb = req.body.thumb;
article.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Added' });
});
});
I need to insert into articles collection authors id (user_id), but I dont know how to get the authenticated user_id.我需要插入文章集合作者 ID (user_id),但我不知道如何获取经过身份验证的 user_id。
Tried to do this:试图这样做:
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
console.log(decoded);
next();
}
});
decoded returns all info about user (name, password, _id).已解码返回有关用户的所有信息(名称、密码、_id)。 Is it possible to get only user_id and name from here?
是否可以从这里只获取 user_id 和 name?
When you sign a JSON web token you can pass it a user object. 当您签署JSON Web令牌时,您可以将其传递给用户对象。 Here you can store whatever user data you need.
在这里,您可以存储您需要的任何用户数据。 This object is then signed and encoded and set as the token.
然后对该对象进行签名和编码,并将其设置为令牌。 When you send a request to your API passing the JWT in the auth header your validation function should return this user object back to you if the JWT is valid.
当您向API传递请求时,如果JWT有效,则验证函数应将此用户对象返回给您。
I like to use the Hapi framework for creating my Restful APIs so I will give an example using Hapi. 我喜欢使用Hapi框架来创建我的Restful API,所以我将使用Hapi给出一个例子。
In your server.js file you need to register the hapi-auth-jwt2 package: 在server.js文件中,您需要注册hapi-auth-jwt2包:
server.register(require('hapi-auth-jwt2'), (err) => {
if (err) {
throw err;
}
server.auth.strategy('jwt', 'jwt', {
key: config.jwt.secret,
validateFunc: auth.validate,
verifyOptions: { algorithms: ['HS256'] }
});
server.auth.default('jwt');
});
Your validation function: 你的验证功能:
export default {
validate: (tokenObject, req, callback) => {
validateToken(tokenObject.user_id, (err, user) => {
if (err) {
callback(Boom.unauthorized('User is unauthorized.'), false);
} else {
req.user = user;
callback(null, true);
}
});
}
};
The validateToken function should take the user id that you got from the token and query for the user. validateToken函数应该使用您从令牌获取的用户ID并查询该用户。 If a user is found then you know the token is valid and you can return and store the rest of the user information.
如果找到用户,则表示您知道该令牌有效,您可以返回并存储其余的用户信息。
To create a token I use "jsonwebtoken" package: 要创建令牌,我使用“jsonwebtoken”包:
generateToken: (user_id, name, callback) => {
'use strict';
callback(null, JWT.sign({
user_id: user_id,
name: name
}, config.JWT.SECRET, {
expiresIn: 86400
}));
}
Let's say you need to verify if the token sent from user In the headers already In your Database or not (we're going to call it protect )假设您需要验证从用户发送的令牌是否已经在您的数据库中的标头中(我们将其称为protect )
const {promisify} = require('util');
const jwt = require('jsonwebtoken');
const User = require('./../models/userModel');
...
exports.protect = catchAsync(async(req, res, next) => {
// 1) Getting token and check if it's there in headers
let token;
//authorization is the name of the header token
if (req.headers.authorization) {
token = req.headers.authorization;
}
if (!token) {
return next(new AppError('You are not logged in! Please Login To get Access.', 401));
}
// 2) Verification Token is a valid token
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
// WE CAN GET THE USER ID FROM DECODED
// 3) Check if user still exists not deleted
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next(new AppError('the user does not exist.', 401));
}else{
// WHAT EVER YOU WANT TO DO AFTER CHECKING USER FOUND IN DATABASE
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.