简体   繁体   中英

Why isAuthenticated return false in passport.js local strategy after successful login the user

I have the following code to authenticate through the passport-local strategy:

    
routes.post("/login", passport.authenticate("local"), (req, res) => {
  res.json(req.user);
});

function ensureAuth(req, res, next) {
  console.log(req.isAuthenticated());
  if (req.isAuthenticated()) {
    next();
  } else {
    req.flash("info", "You must be logged in to see this page");
    res.redirect("/login");
  }
}

routes.get("/edit", ensureAuth, (req, res) => {
  res.sendStatus(200);
});

routes.post("/edit", ensureAuth, (req, res, next) => {
  req.user.username = req.body.username;
  req.user.bio = req.body.bio;
  req.user.email = req.body.email;

  req.user.save((err) => {
    if (err) {
      return next(err);
    } else {
      res.send({
        success: "true",
        info: "Profile updated",
      });
    }
  });
});

I can't figure out why this is happening? Why won't it authenticate?

I can't see your passport local configuration and I send a sample for local Authentication by passport local I hope help you:) login route:

router.post('/login', loginController.process);

controller loginController.process :

async process(req, res, next) {
        try {
            passport.authenticate('local.login', async (err, user) => {
                // User not Exist
                if (!user) return this.back(req, res);
                req.logIn(user, (err) => {
                    if (req.body.remember) {
                        user.setRememberToken(res);
                    }
                    return res.redirect('/');
                });
            })(req, res, next);
        } catch (e) {
            next(e);
        }
    }

}

passport configuration:

passport.use('local.login', new localStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true,
}, async (req, email: string, password: string, done) => {
    // Select User Where email
    const user = await userService.findOne({email});
    // Check user Exist or Incorrect Password
    if (!user || !user.comparePassword(password)) return done(req.flash('global_error', req.__('typeScript.app.passport.passport-local.wrong')), null);
    done(null, user);
}));

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