jaredhanson / passport

Simple, unobtrusive authentication for Node.js.
https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about
MIT License
22.92k stars 1.24k forks source link

Session is not retained (or req.isAuthenticated() returns false) once authentication is completed?? #525

Open Sid21m opened 7 years ago

Sid21m commented 7 years ago

I am using express-session and middleware passport.session(). For serialization i use user object in session because I dont want to hit database every time I deserialize.

My front end : localhost app at port 80. Back end : node app at port 8080

Also I am using custom callbacks because I need to redirect to dynamic url (consisting of accesstoken and refreshtoken)created from user object

Here is my code (index.html):

<a href="http://localhost:8080/auth/google" class="btn btn-danger"><span class="fa fa-google-plus"></span> Google</a>

(initial setup):

var express  = require('express');
var session  = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app      = express();
var port     = process.env.PORT || 8080;

var passport = require('passport');
var cors = require('cors');
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
// required for passport
app.use(session({
    secret: 'sid',
    resave: true,
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        maxAge: 60*60*1000
    }
 } )); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(cors());

(passport code):

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        console.log("User serialised");
        done(null, user);
    });

    // used to deserialize the user
    passport.deserializeUser(function(user, done) {
         console.log("User de-serialised");
            done(null, user);
    });
  passport.use(new GoogleStrategy({

        clientID        : configAuth.googleAuth.clientID,
        clientSecret    : configAuth.googleAuth.clientSecret,
        callbackURL     : configAuth.googleAuth.callbackURL,
        passReqToCallback : true

    },
    function(req,token, refreshToken, params, profile, done) {

        // make the code asynchronous
        process.nextTick(function() {

                connection.query("SELECT * FROM user WHERE Email = ?",[profile.emails[0].value], function(err, rows){               
                    if (err)
                        return done(err);
                    if (rows.length) {
                        rows[0].accessToken = token;
                        rows[0].refreshToken = refreshToken;    
                        rows[0].expires_in = params.expires_in;                                                  
                        return done(null, rows[0]);
                    }
               });

            //});

        });

    }));

routes:

 app.get('/auth/google', passport.authenticate('google', { scope : configAuth.googleAuth.scopes, accessType: configAuth.googleAuth.access_type, prompt: 'consent'}));

     app.get('/auth/google/callback',function(req,res,next){
         passport.authenticate('google',function(err,user,info){
            console.log(req.user)
            if(err){
                res.redirect("http://localhost/app/index.html?error=Error");
            }else{
                if(user){               
                     req.logIn(user, function(err) {
                          if (err) {
                           return next(err); 
                          }
                         res.redirect("http://localhost/app/index.html?refreshToken=" + user.refreshToken + "&accessToken=" + user.accessToken + "&expires_in=" + user.expires_in);
                    });
                }
                else{
                    res.redirect("http://localhost/app/index.html?error=Error");
                }
            }
         })(req,res,next);
     });
//this will be called inside my app once authentication is completed
     app.post('/userProfile', isLoggedIn,function(req, res) {
        res.status(200).send({success : true, data : req.user});
    });
function isLoggedIn(req, res, next) {
 console.log(req.user)
    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    res.status(400).send({success: false, message : "Session Expired"});
}

I am able to see req.user inside the route handler for auth/google/callback.

But when authentication is completed, I call POST /userProfile, req.isAuthenticated() returns false.

I think I am missing something here.??

Strandedpirate commented 7 years ago

Your secret must match between cookie-parser and express-session. Also you may want to use the expires option as shown below.

app.use(cookieParser('asdf33g4w4hghjkuil8saef345')); // cookie parser must use the same secret as express-session.

const cookieExpirationDate = new Date();
const cookieExpirationDays = 365;
cookieExpirationDate.setDate(cookieExpirationDate.getDate() + cookieExpirationDays);

app.use(session({
    secret: 'asdf33g4w4hghjkuil8saef345', // must match with the secret for cookie-parser
    resave: true,
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        expires: cookieExpirationDate // use expires instead of maxAge
    }
 } ));
tleunen commented 7 years ago

I'm having the same issue. For some reasons, I don't see the cookie in my browser so the next time I refresh the page, my session is lost.

jeffwilcox commented 7 years ago

If the cookie isn't lost, think about other situations that might impact:

Independent of Passport make sure you can establish and maintain a session.

tleunen commented 7 years ago

I made a few more tests, and it seems it was because cors wasn't properly set. Thanks!

NikhilNanjappa-zz commented 4 years ago

@tleunen - Could you please elaborate on how you fixed the issue by properly setting cors ?

tleunen commented 4 years ago

This was so long ago. Sorry, can't remember at all.

NikhilNanjappa-zz commented 4 years ago

hehe .. Just realised!

No worries. Thanks for the quick reply.