hxmn
hxmn

Reputation: 81

Passport auth works locally but not on remote server

I'm going crazy about this problem. I've just setup Passport js together with Google oAuth 2.0 strategy and it works perfect on my local Express 4 server.

But when I try to run it on my Amazon server the call req.isAuthenticated() returns false every time and req.user is undefined. I can't figure out what's wrong.

passport.serializeUser(function(user, done) {
   console.log("serializeUser " + user.id);
   done(null, user.id);
});

passport.deserializeUser(function(id, done) {
   console.log("deserializeUser: " + id);
   User.find({_id: id}, function (error, user) {
       if (error || !user) {
           done(error, null);
       } else {
           done(null, user);
       }
   });
});

passport.use(new GoogleStrategy({
    clientID: config.google.clientID,
    clientSecret: config.google.clientSecret,
    callbackURL: config.google.callbackURL
},
function(accessToken, refreshToken, profile, done) {

    process.nextTick(function () {

        if(profile._json.domain === 'xxx'){

            var query = {googleId: profile.id};
            var options = {upsert: true, new: true, setDefaultsOnInsert: true };

            // Find the document
            User.findOneAndUpdate(query, query , options, function (error, user) {
                if (error) {
                    return done(error);
                }
                return done(null, user);
            });
        }else{
            return done(new Error("Invalid host domain"));
        }
    });

}
));

router.get('/auth/google',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email'] }));

router.get('/auth/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) {
        res.redirect('/');
});

router.get('/login', ensureAuthenticated, function(req, res){
     console.log("User is Authenticated");
});

function ensureAuthenticated(req, res, next) {

   console.log("USER " + req.user);

   if (req.isAuthenticated()) {
      console.log("Authorized");
      return next();
   } else {
      console.log("Not authorized");
      res.sendStatus(401);
   }

}

And this is the Express server conf.

/ Express
var app = express();
app.use(cookieParser('xxx'));

app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({limit: '100mb', extended: true}));

// Used for production build
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    store: sessionStore, //var sessionStore = new MemoryStore();
    secret: 'xxx',
    resave: true,
    saveUninitialized: true,
    cookie: {
        secure: false,
        path: '/',
        httpOnly: true,
        maxAge: new Date(Date.now() + 3600000),
    }
}));

// Compress responses
app.use(compression());

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

routes(app);

Similar problem

Please help!

Upvotes: 0

Views: 1027

Answers (2)

hxmn
hxmn

Reputation: 81

I think my problem was fixed by switching the Session Store to MongoStore instead of MemoryStore. I hope that saves some time for some of you in the future.

 // Express
var app = express();
app.use(cookieParser('xxx'));

app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({limit: '100mb', extended: true}));

// Used for production build
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    cookieName: 'session',
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000,
    store: new MongoStore({
        mongooseConnection: mongoose.connection,
        touchAfter: 24 * 3600 // time period in seconds
    }),
    secret: 'xxx',
    saveUninitialized: false, // don't create session until something stored
    resave: false, //don't save session if unmodified
    cookie: {
        secure: false,
        path: '/',
        httpOnly: true,
        maxAge: new Date(Date.now() + 3600000),
    }
}));

Upvotes: 1

peterhogg
peterhogg

Reputation: 11

Have you added the amazon server to the list of authorized redirect URIs? See the following : https://developers.google.com/adwords/api/docs/guides/authentication#oauth2_playground

Make sure to add your Amazon redirect URI to google's console in order to authenticate

Upvotes: 0

Related Questions