使用jwt的区别

difference between using jwt

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

问题 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
});

提前致谢。

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

检查-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
});

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