简体   繁体   中英

PassportJS Facebook login isAuthenticated returns false even though authentication succeeds

For some reason on my NodeJS Express app, when authenticating via the PassportJS library with Facebook, regardless of the fact that the authentication succeeds and returns profile data, calls to request.isAuthenticated() always return false .

I've declared my authentication callback to redirect on success to the /profile route, which it does successfully:

app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/profile', failureRedirect: '/' }));

This route is declared with a function that verifies authentication before deciding whether to continue processing the request:

app.get('/profile', ensureAuthenticated, user.list);

The definition of this function is as follows:

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    return res.redirect('/')
}

As you can see everything's fairly simple. I'm not doing anything particularly special here.

Stepping through PassportJS's code revealed that it does not store user data in the request unless you specify the assignProperty in the options dict when declaring the authenticate middleware. It's this same property it attempts to access when calling isAuthenticated() , so because it never stores this data, it's always claiming I'm not authenticated.

Unfortunately, specifying this key screws up Express's route matching, which results in a 404 error handling the callback URL, as the code that checks assignProperty immediately moves onto processing the next available route.

I've added the code in its entirety to pastie . I'd appreciate any help anyone can provide on this.

Try moving the cookieParser and session middleware to before the Passport middleware:

app.use(express.cookieParser());
app.use(express.session({ secret: '--- OMMITTED ---' }));
app.use(passport.initialize());
app.use(passport.session());

The reason for this is that Express executes middleware in order of declaration. In your current situation, a request hits the Passport middleware before the cookie/session middleware (on which the Passport middleware relies).

(the same goes for the bodyParser() middleware by the way, although your routes don't currently rely on it)

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