passport's req.isAuthenticated always returning false, even when I hardcode done(null, true)

前端 未结 14 1387
小鲜肉
小鲜肉 2020-11-29 02:06

I\'m trying to get my Passport local strategy working.

I\'ve got this middleware set up:

passport.use(new LocalStrategy(function(username, password,         


        
14条回答
  •  [愿得一人]
    2020-11-29 02:33

    There's a kink in passport.js that nobody really mentions but I found out. This is why you can create an account or sign in and it authenticates fine at first but later on you find out req.user is undefined or req.isAuthenticated() is false throughout the app.

    After authenticating, passport.js requires you to reroute/redirect. That's how passport initializes the actual session.

      signIn(req, res, next) {
        passport.authenticate("local")(req, res, function() {
          if (!req.user) {
            console.log("User not found!");
          } else {
            res.redirect("/")
            console.log("signed in")
          }
        })
      }
    
    

    If you don't reroute after authenticating, it won't even start your session as a req.user and req.isAuthenticated() will be false.

    My app is a React and Node app but this is true for both Node apps and React/Node apps.

提交回复
热议问题