Passport.js: how to access user object after authentication?

Issue

I’m using Passport.js to login a user with username and password. I’m essentially using the sample code from the Passport site. Here are the relevant parts (I think) of my code:

app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(obj, done) {
    done(null, obj);
});

passport.use(new LocalStrategy(function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false, { message: 'Incorrect username.' });
        }
        if (!user.validPassword(password)) {
            return done(null, false, { message: 'Incorrect password.' });
        }
        return done(null, user);
        });
    }
));

app.post('/login',
    passport.authenticate('local', { failureRedirect: '/login/fail', failureFlash: false }),
    function(req, res) {
        // Successful login
        //console.log("Login successful.");
        // I CAN ACCESS req.user here
});

This seems to login correctly. However, I would like to be able to access the login user’s information in other parts of the code, such as:

app.get('/test', function(req, res){
    // How can I get the user's login info here?
    console.log(req.user);  // <------ this outputs undefined
});

I have checked other questions on SO, but I’m not sure what I’m doing wrong here. Thank you!

Solution

You’ll need to make sure that you register a middleware that populates req.session before registering the passport middlewares.

For example the following uses express cookieSession middleware

app.configure(function() {

  // some code ...

  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.cookieSession()); // Express cookie session middleware 
  app.use(passport.initialize());   // passport initialize middleware
  app.use(passport.session());      // passport session middleware 

  // more code ...

});

Answered By – 250R

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published