如何在路由之前使用身份验证中间件获取令牌。

huangapple go评论70阅读模式
英文:

how to use middleware of the auth before route to get token

问题

我该如何解决这个问题?我想在路由中获取令牌,然后路由发送响应。但在这个中间件中,我的代码在路由被调用后获取令牌。我如何访问中间件令牌以验证用户?

var express = require("express");
var request = require("request");
var router = express.Router();
var supertoken;
tokenmiddleware = function(req, res, next) {
  console.log("这是身份验证中间件");
  try {
    var options = {
        method: "POST",
        url: "这里是我的身份验证服务器URL",
        headers: {
          json: true,
          Authorization: "", //
          "Content-Type": "application/x-www-form-urlencoded"
        }
      },
      form: {
        grant_type: "password",
        username: "用户名",
        password: "密码"
      };
    request(options, function(error, response, body1) {
      if (error) {
        throw new Error(error);
      } else {
        let info = JSON.parse(body1);
        //将body1解析为JSON,以便我们可以使用body1的属性。
        supertoken = info.access_token; //它提供了超级管理员的令牌。
        // console.log(supertoken)
        // console.log(process.env.ACCESS_TOKEN);
        //返回supertoken
      }
    });
    console.log("超级令牌");
    console.log(supertoken);
    next();
  } catch (error) {
    return res.status(401).json({ message: "身份验证失败。" });
  }
}; //此中间件给了我一个令牌。

router.post("/verifyUser", tokenmiddleware, (req, res) => {
  //这里我想要我的中间件令牌(但它在路由之后调用)
  //在这里我应用了验证用户的逻辑,但令牌不起作用(它说是未定义的)
});

请注意,这是您提供的代码的中文翻译部分。

英文:

How can I solve this?
i want get token in router and then router send response.but in this middle ware my code get token after routes called.and how can i access middleware token for verify user

var express = require("express");
var request = require("request");
var router = express.Router();
var supertoken;
tokenmiddleware = function(req, res, next) {
  console.log("this is auth middleware");
  try {
    var options = {
        method: "POST",
        url: "here is my auth server url",
        headers: {
          json: true,
          Authorization: "", //
          "Content-Type": "application/x-www-form-urlencoded"
        }
      },
      form: {
        grant_type: "password",
        username: "usrename",
        password: "password"
      };
    request(options, function(error, response, body1) {
      if (error) {
        throw new Error(error);
      } else {
        let info = JSON.parse(body1);
        //it parse the body1 into json so we can use property of body1.
        supertoken = info.access_token; //it gives the token of the super admin.
        // console.log(supertoken)
        // console.log(process.env.ACCESS_TOKEN);
        //return supertoken
      }
    });
    console.log("superrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
    console.log(supertoken);
    next();
  } catch (error) {
    return res.status(401).json({ message: "Auth Failed." });
  }
}; //this middleware gave me a token.



router.post("/verifyUser", tokenmiddleware, (req, res) => {
  //here i want my middleware token (but it calls after the route)
  //here i applied logic of verify user but token is not working.(it say's undefined)
});

答案1

得分: 0

你的中间件包括一个异步操作的请求,并且你在请求回调之外调用了 next()。在你的中间件调用后,你在请求完成之前触发了 next(),只需将 next() 移动到请求回调内部。

tokenmiddleware = function (req, res, next) {
  console.log('这是身份验证中间件');
  try {
    var options = {
      method: 'POST',
      url: '这里是我的身份验证服务器URL',
      headers: {
        json: true,
        Authorization: '', //
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      form: {
        grant_type: 'password',
        username: '用户名',
        password: '密码',
      },
    };
    request(options, function(error, response, body1) {
      if (error) {
        throw new Error(error);
      } else {
        let info = JSON.parse(body1);
        // 解析body1为JSON,以便我们可以使用body1的属性。
        supertoken = info.access_token; // 它提供了超级管理员的令牌。
        // console.log(supertoken)
        console.log('超级令牌');
        console.log(supertoken);
        req.userToken = info.access_token;
        next();
      }
    });
  } catch (error) {
    return res.status(401).json({ message: '身份验证失败。' });
  }
};

router.post("/verifyUser", tokenmiddleware, (req, res) => {
  console.log(req.userToken); // 应该是您的令牌
});
英文:

Your middleware includes request which is an asynchronous operation. And you call next() outside of request callback. After your middleware called you fire next() before request is finished, just move next inside request callback

    tokenmiddleware = function (req, res, next) {
console.log('this is auth middleware');
try {
var options = {
method: 'POST',
url: 'here is my auth server url',
headers: {
json: true,
Authorization: '', //
'Content-Type': 'application/x-www-form-urlencoded',
},
form: {
grant_type: 'password',
username: 'usrename',
password: 'password',
},
};
request(options, function(error, response, body1) {
if (error) {
throw new Error(error);
} else {
let info = JSON.parse(body1);
//it parse the body1 into json so we can use property of body1.
supertoken = info.access_token; //it gives the token of the super admin.
// console.log(supertoken)
console.log('superrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr');
console.log(supertoken);
req.userToken = info.access_token;
next();
}
});
} catch (error) {
return res.status(401).json({ message: 'Auth Failed.' });
}
};
router.post("/verifyUser", tokenmiddleware, (req, res) => {
console.log(req.userToken); // should be your token
});

huangapple
  • 本文由 发表于 2020年1月3日 16:58:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定