如何访问护照“完成”使用 Passport.js 进行身份验证时从其余代码中调用函数?
我正在尝试使用Passport.js和Passport_jwt策略在API中实现身份验证。代码附加在下面
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
const User = require('../models/user_model')
const dotenv = require('dotenv')
module.exports = function(passport) {
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
在这里,我已通过完成成功身份验证的功能。对于我的帖子路线,我使用 Passport.authenticate 作为下面的路线中间件。
app.use('/api/v1/posts', passport.authenticate('jwt', { session : false }), postRoutes)
现在的问题是,在创建邮政路线时,如何访问以前在完成功能上发送的用户?太感谢了。
I am trying to implement authentication in my API using passport.js with passport_jwt strategy. the code is attached below
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
const User = require('../models/user_model')
const dotenv = require('dotenv')
module.exports = function(passport) {
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
here I have passed the user on the done function on successful authentication. For my post routes I used passport.authenticate as a route middleware like below.
app.use('/api/v1/posts', passport.authenticate('jwt', { session : false }), postRoutes)
Now the question is how can I access the user, previously sent on the done function, while creating the post routes? Thank you so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 poStroutes 方法中访问 user ,如下:
You can access user in your postRoutes method as code below: