【问题标题】:function auth middleware node功能认证中间件节点
【发布时间】:2020-08-24 22:15:46
【问题描述】:

嘿嘿,我对 js 和 node js 很陌生,我真的需要一些帮助。我有这个文件,我在其中导出处理令牌的中间件


const jwt = require("jsonwebtoken");
const config = require("../config/config");

module.exports = (req, res, next) => {
  try {
    let token = req.headers.authorization.split(" ")[1];
    let decodeToken = jwt.verify(token, config.secrets.jwt);
    let id = decodeToken.id;
    let userType = decodeToken.userType;
    if (req.body.id && req.body.id !== id) {
      throw "Invalid user Id";
    } else {
      next();
    }
  } catch {
    res.status(401).json({
      error: new Error("Invalid request!"),
      message: "Unauthorized"
    });
  }
};

我想要的是将它包装到一个函数中,该函数将有效负载(用户 ID 和用户类型)作为参数,这样我就可以从任何其他文件访问用户 ID 和用户类型。或者,如果有其他方法可以从这里导出用户 ID 和用户类型,以使其可见,以便我可以在控制器文件中使用它们,例如。谢谢你:)

【问题讨论】:

    标签: node.js authentication jwt


    【解决方案1】:

    您将无法访问使用过的“从任何其他文件”。因为user 是动态的,并且仅根据 HTTP 请求(您的快速中间件)的 上下文 进行解析。

    所以你需要做的就是将user添加到请求上下文并扩展请求对象(请求对象是上下文)。

    module.exports = (req, res, next) => {
      try {
        let token = req.headers.authorization.split(" ")[1];
        let decodeToken = jwt.verify(token, config.secrets.jwt);
        let id = decodeToken.id;
        let userType = decodeToken.userType;
        if (req.body.id && req.body.id !== id) {
          throw "Invalid user Id";
        } else {
          req.user = decodeToken; // or any object that describe the user
          next();
        }
      } catch {
        ....
      }
    };
    

    现在您可以在控制器中访问请求context,并根据需要使用user

    app.get('....', function(req, res){
       console.log(req.user);  // output { "id": XXX, userType: XXXX, ... }
    
       const userId = req.user.id;
       someService.someAction(userId, arg1, ....);
    });
    

    【讨论】:

    • 谢谢!!!我试过了,但我没有正确地将用户添加到请求中。你帮了我,你!
    猜你喜欢
    • 2014-12-12
    • 2017-02-14
    • 1970-01-01
    • 2018-07-11
    • 2021-01-09
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多