How to manage session logins with Passport (Express)? By session logins I mean: an authenticated user should not have to resend credentials at each request.
In the following example, myStrategy.authenticate() keeps being called even if the user previously authenticated.
var express = require( "express" );
var session = require( "express-session" );
var passport = require( "passport" );
var app = express();
var myStrategy = function(){ this.name = "mystrategy"; };
myStrategy.prototype.authenticate = function( req ) {
console.log( "called" );
this.success( "user" );
};
passport.use( new myStrategy() );
passport.serializeUser( function( id, cb ){ cb( null, id ); });
passport.deserializeUser( function( id, cb ){ cb( null, id ); });
app
.use( session({ secret: "hello", resave: true, saveUninitialized: true }) )
.use( passport.initialize() )
.use( passport.session() )
.get( "/", passport.authenticate( "mystrategy" ), function( req, res ) {
res.send( "OK" );
})
.listen( 80 );
It seems passport.session() retrieves req.user from req.session.passport.user, but passport.authenticate() fires even when req.user is defined, which defeats the whole point.
The solution is to dissociate the login action (on the login page) from the authentication checks (on the protected pages):
.get( "/auth", passport.authenticate( "mystrategy" ), function( req, res ) {
res.send( "OK" );
})
.get( "/private", function( req, res ) {
if ( req.isAuthenticated() ) {
res.send( "Private data" );
}
})