Jiew Meng
Jiew Meng

Reputation: 88217

PassportJS (Google OpenID) nothing in req.user

According to the PassportJS docs

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user

However I had this:

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

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

passport.use(new GoogleStrategy({
    returnURL: "http://localhost:3000/auth/google/return",
    realm: "http://localhost:3000/"
}, function(id, profile, done) {
    console.log("Done: ", profile);
    done(null, profile);
}));

app.get('/auth/google', passport.authenticate('google', {session: false}));
app.get('/auth/google/return', passport.authenticate('google', {
    successRedirect: '/success',
    failureRedirect: '/failure',
    session: false
}));

app.get('/success', function(req, res, next) {
    console.log(req.user);
    res.send(JSON.stringify(req.user));
});

app.get('/failure', function(req, res, next) {
    res.send("FAIL");
});

And req.user in the route /success is undefined. The req.user in the GoogleStrategy definition is ok tho. Why is that?

Upvotes: 2

Views: 242

Answers (2)

Evan Siroky
Evan Siroky

Reputation: 9418

req.user will not get set if you specify session: false in the options of your call to passport.authenticate.

You could use the user's profile as you are doing in the callback from the new GoogleStrategy, but be aware that your server might end up making the user authenticate each request instead of reusing the access token.

Upvotes: 0

Will Stern
Will Stern

Reputation: 17579

Is there a reason you're not using sessions?

Try using this without {session: false}

app.use(express.cookieSession());
//passport config here
app.use(passport.initialize());
app.use(passport.session());
//routes here

Upvotes: 1

Related Questions