我正在使用passport-jwt,并且有一个端点,如果 header 中不存在jwt token ,则该端点应该从数据库返回一些数据。 是否可以应用一些逻辑而不只是发送未经授权的 401?
router.get(
'/get/items',
passport.authenticate('jwt', {session: false}),
(req, res) => {
// reaches this point only after validating token
...
}
);
因此,如果 jwt token 存在,基于它的端点应该返回一些数据。如果没有,则应返回数据库中的一些其他数据
最佳答案
我认为custom callback是一个选项。它作为最后一个参数传递给 authenticate(strategy, options,callback)
方法,它将允许您设置您想要的行为。
您的代码将如下所示:
app.get('/get/items', (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (!user) {
/*
Unauthorized accees.
Handle here the request as u wish
*/
/* Do some custom logic and return your desired result */
return res.status(401).json({ success: false, message: 'Unauthorized access!' });
}
/* User is authorized. Do other stuff here and return your desired result*/
return res.status(200).json({ success: true, message: 'Congratulations!' });
})(req, res, next);
});
In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.
If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.
The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.
关于node.js - 如果 header 中不存在 JWT token ,如何执行某些逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55813060/