joy
joy

Reputation: 3707

How to pass HTTP response object part of node js passport module based authentication callback function?

I am using passport module to write local authentication. Recently I started setting userid after successful authentication as header using response object. Surprisingly I realized that my passport code is not taking HTTP "response" object. Following are details.

Code which doesn't work (callback function is only expecting four parameter):

passport.use('local-login', new LocalStrategy({
        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },
    function (req, res, username, password, done) {
        log.debug("passport authenticateUser >> req >>"+req+", res >>"+res+", username "+username+", password "+password);
        userService.authenticateUser(req, res, username, password, done);
    }));

Code which works

passport.use('local-login', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, username, password, done) {
    log.debug("passport authenticateUser >> req >>"+req+", res >>"+res+", username "+username+", password "+password);
    userService.authenticateUser(req, username, password, done);
}));

I need HTTP "response" object as well. Please help

Upvotes: 0

Views: 1689

Answers (2)

Manjula
Manjula

Reputation: 21

Change the parameter(res) of the following function to (req.res)

Your code->

    function (req, ***res***, username, password, done) { 
       log.debug("passport authenticateUser >> req >>"+req+", res >>"+res+",
       username "+username+", password "+password);  
       userService.authenticateUser(req, res, username, password, done); 
    }));

After modifying the parameter ->

    function (req, ***req.res***, username, password, done) { 
       log.debug("passport authenticateUser >> req >>"+req+", res >>"+res+",
       username "+username+", password "+password);  
       userService.authenticateUser(req, res, username, password, done); 
    }));

Upvotes: 2

robertklep
robertklep

Reputation: 203251

You can access the response object through req as req.res.

However, I don't think it's what you want, because your local strategy will only be called for your "login" route; any other routes that a logged-in user will access will not call it, and hence your header won't be set.

Instead, you can use a custom middleware to set the header for each request that a logged-in user makes:

app.use(function(req, res, next) {
  if (req.user) {
    // Set the X-User-Id header to contain the user id. Obviously
    // you should change this example to fit your situation.
    res.set('X-User-Id', req.user.id);
  }
  next();
});

Make sure to add this route after app.use(passport.session()) but before any regular routes.

Upvotes: 3

Related Questions