passport's req.isAuthenticated always returnin

2019-01-08 20:07发布

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

I've got this middleware set up:

passport.use(new LocalStrategy(function(username, password, done) {
    //return done(null, user);
    if (username=='ben' && password=='benny'){
        console.log("Password correct");
        return done(null, true);
    }
    else
        return done(null, false, {message: "Incorrect Login"});
}));

but then in here

app.use('/admin', adminIsLoggedIn, admin);

function adminIsLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

it always fails and redirects to the home page.

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

In my console I can see that's Password Correct is printing. Why won't it work?

9条回答
劫难
2楼-- · 2019-01-08 20:56

I had the same issue by forgetting to add

request.login()

on

app.post('/login', 
    function(request, response, next) {
        console.log(request.session)
        passport.authenticate('login', 
        function(err, user, info) {
            if(!user){ response.send(info.message);}
            else{

                request.login(user, function(error) {
                    if (error) return next(error);
                    console.log("Request Login supossedly successful.");
                    return response.send('Login successful');
                });
                //response.send('Login successful');
            }

        })(request, response, next);
    }
);

Hopefully that might help for others that ended up here same reason as I did.

查看更多
贼婆χ
3楼-- · 2019-01-08 20:57

I had a similar issue. Could be due to the express-session middleware needed for passport. Fixed it by using middlewares in the following order: (Express 4)

var session = require('express-session');

// required for passport session
app.use(session({
  secret: 'secrettexthere',
  saveUninitialized: true,
  resave: true,
  // using store session on MongoDB using express-session + connect
  store: new MongoStore({
    url: config.urlMongo,
    collection: 'sessions'
  })
}));

// Init passport authentication 
app.use(passport.initialize());
// persistent login sessions 
app.use(passport.session());
查看更多
姐就是有狂的资本
4楼-- · 2019-01-08 20:57

If you wrap your routes like so:

module.exports = function(){

router.get('/',(req,res)=>{
 res.send('stuff');
  }

}

You have to pass "app and passport" to your routes like so:

module.exports = function(app,passport){

//routes n stuff

}
查看更多
登录 后发表回答