Search code examples
oauthpassport.jsnestjs

How to pass state during Nest.js Authentication flow


while performing a Google OAuth flow, it is possible to pass an encrypted state (base64) that will be passed as parameter to the final callback. This was useful when you want to redirect your user to a specific page for example. (https://developers.google.com/identity/protocols/oauth2/web-server)

Is it possible to use the OAuth state with the Nest.js authentication library? It seems that the state parameter is ignored and I can't find anything on the documentation.

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(readonly configService: ConfigService) {
    super({
      clientID: configService.get('google.clientId'),
      clientSecret: configService.get('google.clientSecret'),
      callbackURL: `${configService.get('apiUri')}${configService.get('google.callbackUrl')}`,
      passReqToCallback: true,
      scope: ['profile', 'email'],
    });
  }
}

Solution

  • To solve this, I added an authenticate function to the class that sets the state value.

    authenticate(req, options) {
      options.state = 'your state value here'
      super.authenticate(req, options)
    }
    

    disclaimer: I was trying to achieve something similar to what you described and this approach worked for me, but I'm not sure if it's the "correct" way to handle this.