【问题标题】:difference between using jwt使用 jwt 的区别
【发布时间】:2021-05-08 17:33:33
【问题描述】:

问题一:第一种方法和第二种方法有什么区别

问题 2:它们的用例是什么?

jwtMW:

const jwtMW = exjwt({
  secret: "keyboard cat 4 ever",
  algorithms: ["HS256"],
  credentialsRequired: true,
});

接近一个

router.post("/authRequest", jwtMW, async (req, res) => {
  let toeken = req.headers.authorization;
  // use the decoded infomation for further verification
});

接近二

router.post("/authRequest2", async (req, res) => {
  const reqToken = req.headers.authorization.split(" ")[1];
  const secret = "keyboard cat 4 ever";
  var decoded = jwt.verify(reqToken, secret);
  // use the decoded infomation for further verification
});

提前致谢。

【问题讨论】:

  • 通常,回答者希望得到某种反馈,要么是对你不起作用的评论,要么是赞成并接受它。我注意到您从未接受任何答案。如果答案已解决您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您找到了解决方案,并为回答者和您自己赢得了一些声誉。
  • 如果你的问题没有解决,请留言,否则接受我的回答

标签: node.js express jwt express-jwt


【解决方案1】:

第一种方法是不正确的,因为在路径中的路径之后你可以使用中间件,但jwtMW 不是中间件,如果你想使用中间件试试这样:

check-auth.js

const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer TOKEN'
    if (!token) {
      throw new Error('Authentication failed!');
    }
    const decodedToken = jwt.verify(token, 'supersecret_dont_share');
    req.userData = { userId: decodedToken.userId };
    next();// it's important line
  } catch (err) {
    throw new Error('Authentication failed!');
  }
};

之后在路由文件中需要中间件

const checkAuth = require('../middleware/check-auth');//it's a exmple

router.post('/authRequest', checkAuth  , async (req, res) => {
       // do somethings
});

在第二种方法中,您不使用中间件

【讨论】:

    猜你喜欢
    • 2018-02-07
    • 2017-01-09
    • 2021-07-16
    • 2015-02-03
    • 2018-10-19
    • 2019-08-02
    • 2020-11-12
    • 2021-04-28
    • 2017-03-15
    相关资源
    最近更新 更多