【问题标题】:Undefined header express when trying to verify token尝试验证令牌时未定义的标头表达
【发布时间】:2021-01-03 08:31:16
【问题描述】:

我已经做了一个快速后端,并想使用 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 预检请求有关,但我无法弄清楚。

【问题讨论】:

    标签: node.js reactjs express axios http-headers


    【解决方案1】:

    首先创建一个中间件文件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());
    

    【讨论】:

    • 谢谢!问题是,如果我这样做,我将不得不对每个请求进行验证,这就是我想要简化的。
    • 您不必为所有请求实现,您可以将其作为中间件。看看我已经更新了我的答案。
    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2020-08-10
    • 2022-01-23
    • 2018-11-18
    相关资源
    最近更新 更多