How can I access OAuth’s state parameter using Passport.js?

The reason this doesn’t work is because you’re passing state as an object instead of a string. Seems like passport doesn’t stringify that value for you. If you want to pass an object through the state param, you could do something like this:

passport.authenticate("google", {
  scope: [
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/userinfo.email'
  ],
  state: base64url(JSON.stringify(blah: 'test'))
})(request, response);

As Rob DiMarco noted in his answer, you can access the state param in the callback req.query object.

I’m not sure encoding application state and passing it in the state param is a great idea though. The OAuth 2.0 RFC Section 4.1.1 defines state as “an opaque value”. It’s intended to be used for CSRF protection. A better way to preserve application state in between the authorization request and the callback might be to:

  1. generate some state parameter value (hash of cookie, for example)
  2. persist the application state with state as an identifier before initiating the authorization request
  3. retrieve the application state in the callback request handler using the state param passed back from Google

Leave a Comment