尝试验证令牌时未定义 header 表示

Undefined header express when trying to verify token

我做了一个快速后端,想使用 JsonWebToken npm 库增加一些安全性。

我在 React 应用程序中使用拦截器为每个请求设置身份验证令牌:

Axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem("api_token") || "auth_pending";
  config.headers.Authorization =  token;
  console.log("Injected header token",token);
  return config;
});

在我的节点后端,我使用 express 库为除登录之外的所有请求设置了一个中间件。

app.use(/\/((?!login).)*/, (req, res, next)=>{
   const {authorization} = req.headers;
   // console.log(authorization); next(); #If end function here the token is shown in the console.                     
   jwt.verify(authorization, '53CR37C0D3', function(err, decoded) {
      if(err){
         console.error(err);
         return res.status(403).send("Token is not valid.");
        }
    req.duser = decoded.user;
    res.status(200).send("Access granted.");
    next();
  });

});

如代码所示,如​​果我只使用中间件来记录令牌,它就可以正常工作。但是如果我想使用 JWT 对其进行解码,授权将变为 undefined。 我认为它与 cors 预检请求有关,但我无法弄清楚。

首先创建一个中间件文件isAuth.js然后你可以这样实现它:

const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const token = req.get("Authorization"); //get header from req by name 'Autherization'
 if (!token || token === "") {
    req.isAuth = false;
    return next();
  }

  try {
    let decoded = jwt.verify(token, "thisissecret");
    req.duser = decoded.user;
    res.status(200).send("Access granted.");
  } catch (error) {
    return res.status(403).send("Token is not valid.");
  }
  req.isAuth = true;
  return next();
};

最后,您可以像这样将其导入并用作中间件:

const isAuth = require('/middleware/isAuth');
...
app.use(isAuth());