我正在尝试获取用户 ID,以便我可以在 mongoose 中连接模型并跟踪每个用户发布的内容。但是为了做到这一点,我需要从 jwt 令牌中获取用户 ID,我不知道如何。 这是一个 MERN 应用程序,我试图从响应中获取 id,但没有成功。这是我的代码:
jwt 认证
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const util = require("util");
const passwordHash = require("../../config/passwordHash")
//get middleware
const authenticateUser = require("../middleware/authenticateUser");
const validateBodyWith = require("../middleware/validateUserWith");
//data validators
const { loginValidator, registerValidator } = require("../validation");
//load User model
const { User } = require("../../models");
const jwtSign = util.promisify( jwt.sign );
//get currently validated user
router.post("/authenticated", authenticateUser, (req,res)=>{
// console.log(req.user);
res.json(req.user);
});
//log in an existent user by signing and returning a secure json web token
// for the client application to store and include with requests
router.post("/login", validateBodyWith(loginValidator), async(req,res)=>{
const {email,password} = req.body;
console.log(req.body);
try{
const user =
await User
.findOne({email})
// .populate('records');
if(!user){
//user not found by email
return res.status(404).json({default:"your email or password is invalid"})
}
const {
password: encryptedPassword,
// User object without the password
...secureUser
} = user._doc;
console.log("user----:",secureUser)
const isMatch = await bcrypt.compare( password, encryptedPassword );
if( !isMatch ) {
// User's password is invalid.
return res.status(404).json({ default: "Email or password is invalid." });
}
const payload = {
id:secureUser._id,
email:secureUser.email
};
console.log(payload);
//create a signed web token to send back to the client for reauthentication
const token = await jwtSign(
payload,
process.env.JWT_SECRET,
{
expiresIn:31556926 //one year in seconds
}
);
return res.json({
sucess:true,
token: "Bearer " + token,
user:secureUser
})
}catch(err){
console.log(err);
res.status(500).json({default:"something went wrong trying to log in "})
}
});
// creates a new user for authentication
router.post("/register", validateBodyWith(registerValidator), async(req,res)=>{
console.log(req.body)
try{
const { name, email, password } = req.body;
const user = await User.findOne({ email });
if (user) {
// User already exists error.
return res.status(400).json({ email: "Email already exists." });
}
const newUser = new User({
name,
email,
password: await passwordHash( password )
});
await newUser.save();
const {
password: encryptedPassword,
// User object without the password
...secureUser
} = newUser._doc;
res.json( secureUser );
}catch(err){
console.log(err);
res.status(500).json({ default: "Something went wrong creating your account." });
}
});
module.exports = router;
中间件:
const passport = require('passport');
const authenticateUser = passport.authenticate('jwt',{session:false});
module.exports = authenticateUser;
const mapValidationErrors = errors => errors.reduce( (errors, {field, message}) => ({ ...errors, [field]: message }), {} );
const validateBodyWith = validator => ( req, res, next ) => {
const result = validator( req.body );
// Body data valid! Continue to the next step...
if( true === result ) return next();
// Validation failed! Send and error response.
res.status(400).json( mapValidationErrors(result) );
}
module.exports = validateBodyWith;
const validatorFactory = require("./validatorFactory");
const loginValidator = validatorFactory({
email: { type: "email" },
password: { type: "string", empty: false }
});
module.exports = loginValidator;
const validatorFactory = require("./validatorFactory");
const registerValidator = validatorFactory({
name:{type:"string", empty:false},
email: { type: "email" },
password: { type: "string", empty: false }
});
module.exports = registerValidator;
const Validator = require("fastest-validator");
const { ObjectID } = require("mongodb");
const v = new Validator({
defaults: {
objectID: {
ObjectID
}
}
});
const validatorFactory = schema => v.compile({
$$strict: "remove",
...schema
});
module.exports = validatorFactory;
答案 0 :(得分:0)
如果您使用护照,则可以从 req.user.id
我会建议您详细阅读@http://www.passportjs.org/packages/passport-jwt/,因为您可以将 JWT 代码从授权标头或 cookie 从客户端传递到服务器端。
<块引用>策略会先检查请求 对于标准授权标头。如果此标头存在并且 该方案匹配 options.authScheme 或 'JWT' 如果没有身份验证方案 指定那么令牌将从它检索。例如
授权:JWT JSON_WEB_TOKEN_STRING..... 如果授权 未找到具有预期方案的标头,请求正文将是 检查匹配 options.tokenBodyField 或的字段 如果未指定选项,则为 auth_token。
最后,将检查 URL 查询参数中是否存在匹配的字段 options.tokenQueryParameterName 或 auth_token 如果选项是 未指定。