Search code examples
javascriptnode.jsexpressauthenticationmiddleware

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


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

Solution

  • 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
    });