简体   繁体   English

Express:如何使用JSON Web令牌保护多条路由

[英]Express: How to protect multiple routes with JSON web token

I'm really just looking for a way to clean up my code here. 我真的只是在寻找一种方法来清理我的代码。 I have several routes like this, note that each route individually goes through the JSON web token verification process. 我有几条这样的路由,请注意,每条路由都分别经过JSON Web令牌验证过程。

router.route('/some-route').post((req, res) => {
  jwt.verify(req.body.token, secret, (err, decoded) => {
    if (err) return console.log(err);
    // do something
    res.json({ some: 'response data' });
  });
});

router.route('/some-other-route').post((req, res) => {
  jwt.verify(req.body.token, secret, (err, decoded) => {
    if (err) return console.log(err);
    // do something else
    res.json({ some: 'response data' });
  });
});

Is there some other way? 还有其他方法吗? Some of my routes are approaching callback-hell levels of nesting, so it would be nice to eliminate this from every route. 我的某些路由接近嵌套的回调地狱级别,因此最好从每条路由中消除这种情况。

Pretty sure you can tell the router to use the function as middleware. 敢肯定你可以告诉路由器use该功能的中间件。 The function will be called for every route in router . 将为router每个路由调用该函数。

router.use((req, res, next) => {
  if(!req.body.token)
    return res.json({ message: 'Missing token.' });

  jwt.verify(req.body.token, secret, (err, decoded) => {
    if (err) return res.json({ message: 'Failed to authenticate token.' });
    // do something else
    req.decoded = decoded
    next();
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM