13

I'am a beginner in expressjs and passportjs. I played with authentication via google using passport with GoogleStrategy. Using the code below i have req.user = { id: '123456' } in /users/hello route handler, but i want to get some like this without session support to send it as the answer to authenticated client. In other words i want to send some token to client if authentication is successful without cookie session start. I can't find the way how to forward user object to target route handler when i turn off sessions.

passport.use(new GoogleStrategy({
    returnURL: 'http://localhost/auth/google/return',
    realm: 'http://localhost/'
  },
  function(identifier, profile, done) {
    done(null, {id: '123456'});
  }
));

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

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

app.use(session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/google', passport.authenticate('google');
app.get('/auth/google/return',
    passport.authenticate('google', {
        successRedirect: '/users/hello',
        failureRedirect: '/users/goodbye' 
    }));
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
user3414982
  • 357
  • 1
  • 4
  • 15
  • 1
    I don't think Google OAuth is intended to work without sessions. – Waldo Jeffers Aug 27 '14 at 09:53
  • 3
    I'am not going to call google api, i just need to authentificate the user for working with my own api. I expected that this behaviour doesn't depend on what strategy i use. – user3414982 Aug 27 '14 at 17:42

2 Answers2

5

To turn off sessions try changing this:

app.get('/auth/google/return',
passport.authenticate('google', {
    successRedirect: '/users/hello',
    failureRedirect: '/users/goodbye' 
}));

to:

app.get('/auth/google/return',
passport.authenticate('google', {
    session:false
}));
mfink
  • 1,309
  • 23
  • 32
  • probably have to comment out passport.use(session()) in app.js as well...then I have to login everytime there is a request to the server... – Alexander Mills Dec 25 '15 at 02:34
  • 1
    This throws `OAuth authentication requires session support. Did you forget to use express-session middleware?` (Probably because what @waldo-jeffers said – Mosh Feu Nov 26 '21 at 21:33
1

In 2023 this worked for me:

app.get(
  `/auth/google/return`,
  passport.authenticate("google", { session: false }),
  handleSuccessfulAuth
);

handleSuccessfulAuth should be your function where you handle generating your token and sending it to the browser in the redirect. i.e

const handleSuccessfulAuth = (req: Request, res: Response) => {
  // If you've set up the verify function correctly in the GoogleStrategy,
  // req.user should have the user info from your database.
  // Generate a token and redirect the user accordingly
};
ericgithinji
  • 325
  • 4
  • 11