了解Passport/JwtStrategy更好的身份验证 [英] knowing better authentication with Passport / JwtStrategy
问题描述
在一个我从Internet下载的工作项目中...
On one working project I downloaded from internet...
在代码的一个位置,我有以下内容:
In one location of the code I have the following:
passport.use(new JwtStrategy({
secretOrKey: credentials.secret,
jwtFromRequest: ExtractJwt.fromAuthHeader(),
},
function(payload, done) {
User.findById(
payload._id,
function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
}
);
}
));
在代码的其他位置,我有以下内容:
In other location of the code I have the following:
var requireAuth = passport.authenticate('jwt', { session: false });
//...
module.exports = function(app) {
//...
authRoutes.get('/protected', requireAuth, function(req, res) {
res.send({ content: 'Success' });
});
//...
}
我在这里有2个问题:
1-如果执行以下操作: return done(err,false);
我们要做的是: done(err,false);
没有返回
?
1- What about if instead doing: return done(err, false);
we do: done(err, false);
without return
?
2-是否始终调用第三个参数(该中间件函数): authRoutes.get(*,*,*)
在函数内部: function(payload,done){}
(第二个参数位于: new JwtStrategy(*,*)
?),请注意中间件函数(第三个参数)返回一个成功
响应.如果在 JWT
身份验证过程中出现问题,怎么办?
2- Is the 3rd argument (that middleware function) in the call of: authRoutes.get(*, *, *)
always reached no matter what's going on inside the function: function(payload, done){}
(second argument on: new JwtStrategy(*, *)
? Notice that middleware function (that 3rd argument) returns a Success
response. What about if something goes wrong inside the JWT
authentication process?
推荐答案
- 很好.两种情况都会导致始终返回
undefined
. - 按照定义中间件的顺序执行中间件.因此,
requireAuth
将始终先执行,然后再执行function(req,res){}
.但是,如果requireAuth
由于某种原因而失败,则function(req,res){}
将在中间件堆栈中被跳过.任何错误都应在错误中间件中进行处理.如果不处理它们,那么整个应用程序将崩溃.
- That's fine. Both cases will result in
undefined
being returned anyways. - Middleware is executed in the order in which they are defined. So
requireAuth
will always execute first and thenfunction(req, res){}
. But ifrequireAuth
fails for whatever reason,function(req, res){}
will be skipped in the middleware stack. Any errors should be handled in error middleware. If you do not handle them, then the whole application will crash.
这篇关于了解Passport/JwtStrategy更好的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!