首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在快速路由上应用jwt而不会引发错误

在快速路由上应用jwt而不会引发错误
EN

Stack Overflow用户
提问于 2018-09-10 07:46:09
回答 1查看 296关注 0票数 0

有没有一种方法可以通过中间件将jwt应用到我的所有快速路由上,而不是在令牌丢失或无效时引发错误,而是使用null填充req.user

我目前的解决方案是:

代码语言:javascript
复制
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'));

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-10 08:47:50

根据documentation,您可以在options对象中指定"credentialsRequired“属性:

代码语言:javascript
复制
app.use(jwt({
  credentialsRequired: false
}));

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

代码语言:javascript
复制
if (!token) {
  if (credentialsRequired) {
    return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' }));
  } else {
    return next();
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52249505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档