【问题标题】:Apply jwt on express routes without raising an error在快速路由上应用 jwt 而不会引发错误
【发布时间】:2019-02-14 09:34:43
【问题描述】:

有没有办法使用中间件在我的所有快速路由上应用 jwt,但如果令牌丢失或无效则不会引发错误,而是使用 null 填充 req.user

我目前的解决方案:

var jwt = require('express-jwt');
var router = express.Router();

router.use(jwt({ secret: 'secret'}));

///////////////////////////////////////////
// This is the piece I would like to avoid
router.use((err, req, res, next) => {
    if (err.code === 'UnauthorizedError') {
        req.user = null;
    }
    next();
})
///////////////////////////////////////////

router.use('/products', require('./products/products_router'));

在我的路线中,如果令牌丢失或无效,我希望有req.user === null,如果令牌有效,我希望有正确的req.user。目前,如果没有我要删除的代码,我的路由不会在没有令牌的情况下执行。如果我使用unless(),即使使用有效令牌也不会填充 req.user

【问题讨论】:

  • 为什么要删除它?你应该做的是继续,如果好的话,或者在它们应该出现的地方抛出错误,而不是继续,否则如果你的代码依赖于 req.user 被设置,你不必要地需要处理它而不是在你的代码中。
  • 是不是因为你不想把它应用到每条路线上?
  • 哦,不抱歉,我的意思是如果有一个内置标志或选项我可以设置而不是自定义代码,我会更喜欢

标签: javascript node.js express jwt express-jwt


【解决方案1】:

根据documentation,您可以在选项对象中指定“credentialsRequired”属性:

app.use(jwt({
  credentialsRequired: false
}));

您可以在原始源代码中看到这是如何工作的:

if (!token) {
  if (credentialsRequired) {
    return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' }));
  } else {
    return next();
  }
}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多