Search code examples
javascriptnode.jsexpresspassport.js

passport js google getting original request param in callback


I'm attempting to get a url param /api/sso-login/google?mobile=true in the callback function. However the req returned is for the google auth and not the original request to the server. I have attemped to use req.session, however as stated the callback has a different req. Any advice on how to go about this?

stratergy:

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_OAUTH_CLIENT_ID,
      clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
      callbackURL: process.env.BASE + '/api/sso-callback/google',
      passReqToCallback: true
    },
    function (request, accessToken, refreshToken, profile, done) {
      let parsedUser = {
        firstname: profile.name.givenName,
        lastname: profile.name.familyName,
        provider: 'google',
        email: profile.email
      }
      request.parsedUser = parsedUser
      return done(null, profile)
    }
  )
)

endpoint:

app.get('/api/sso-login/google',(req,res, next) => {
  req.session.isMobile = req.query.mobile
  next()
}, passport.authenticate('google', { scope: ['profile','email']}))

callback:

app.get('/api/sso-callback/google',passport.authenticate('google', { failureRedirect: '/api/sso-failed' }), loginWithSSO)

loginWithSSO:

async function loginWithSSO(req, res)  {
  try {
    let user = req.parsedUser
    .....login user....
    }
//req is from google auth rather than original req, so this is undefined
    if(req.session.isMobile) return res.status(200).redirect(`redirect1://oauth-callback?token=${token`)
    return res.status(200).redirect(process.env.BASE + `?token=${token}`)
  }
}

Solution

  • managed to fix using states which i overlooked

    app.get('/api/sso-login/google',(req, res, next) => {
      passport.authenticate('google', { 
        scope: ['profile','email'], 
        state: req.query.mobile 
      })(req, res, next)
    })
    

    and then in the stratergy

    passport.use(
      new GoogleStrategy(
        {
          clientID: process.env.GOOGLE_OAUTH_CLIENT_ID,
          clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
          callbackURL: process.env.BASE + '/api/sso-callback/google',
          passReqToCallback: true
        },
        function (request, accessToken, refreshToken, profile, done) {
          request.isMobile = request.query.state
          return done(null, profile)
        }
      )
    )