Skip to content

Instantly share code, notes, and snippets.

@gadgetmies
Last active December 27, 2023 19:33
Show Gist options
  • Save gadgetmies/19725db79baaa49c2cf97ee6e1d5b570 to your computer and use it in GitHub Desktop.
Save gadgetmies/19725db79baaa49c2cf97ee6e1d5b570 to your computer and use it in GitHub Desktop.
Redirect to original url with passport-openidconnect

The library stores the state property passed to it in the options for passport.authenticate. The state is available for the return handler in the req.authInfo.state property.

E.g. for:

http://localhost:3000/login/google?state=/foo

with

router.get('/login/google', (req, res, next) => {
  return passport.authenticate('openidconnect', { state: req.query.state })(req, res, next)
})

and

  passport.use(
    new OpenIDStrategy(
      {
        issuer: 'accounts.google.com',
        clientID: config.googleClientId,
        clientSecret: config.googleClientSecret,
        authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
        tokenURL: 'https://www.googleapis.com/oauth2/v3/token',
        callbackURL: `http://localhost:3000/auth/login/google/return`
      },
      async (issuer, profile, done) => {
      ...

the following would redirect to: http://localhost:3000/foo

router.get(
  '/login/google/return',
  passport.authenticate('openidconnect', { failureRedirect: 'http://localhost:3000/login' }),
  function(req, res) {
    res.redirect(`http://localhost:3000${req.authInfo.state}`)
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment