简体   繁体   中英

req.isAuthenticated always returns false (react frontend)

I am using passport js to authenticate and passport isn't putting user object to the req object(req.user returns undefined).

login route:-

Router.post("/login",ensurelog,async (req, res, next) => {
  await passport.authenticate("local", { failWithError: true }, function(err,user,info
  ) {
    if (err) {
      console.log("1", err);
    } 
    else if (info)
     {
      res.json({info}).end();
    } 
    else if (user) {
      res.json({user}).end();
    }
  })(req, res, next);
});  

when the react client recieves the user object,the page is redirected to a different component using this.props.history.push() function,that component is routed using BrowserRouter from react-router-dom
ensurelog function:-

function(req,res,next){
        //console.log("reached ensurelog")
       console.log(req.user) //always returns undefined
       console.log(req.isAuthenticated()) //always returns false
       if(req.isAuthenticated()){

          res.json({
              message:'already loged in'
          }).end();
       }
        next();

    }

I just had a quick look at the API documentation . Looks like you have your post parameters a bit mixed up. Can you try this:

var ensurelog = function(req,res,next) {
  passport.authenticate('local', function(err, user, info) {
    console.log(user);
  })(req, res, next);
};


Router.post("/login", ensurelog)

It's also worth noting that this API seems to be using callback functions (not Promises) to handle the asynchronous requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM