Paul Slm
Paul Slm

Reputation: 483

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'],
    });
  }
}

Upvotes: 9

Views: 2475

Answers (2)

evilive
evilive

Reputation: 1879

@Injectable()
export class GoogleAuthGuard extends AuthGuard('google') {
  getAuthenticateOptions(context: ExecutionContext) {
    // you can get access to the request object.
    // const request = this.getRequest(context);

    return {
      state: `my-custom-state_${Date.now()}`,
    };
  }
}

and in your auth.controller you can get access to this state param though query values.

@UseGuards(GoogleAuthGuard)
@Get('google/callback')
async googleCallback(@Query('state') state: string): Promise<string> {
  console.log({ state });

  return state;
}

Upvotes: 6

Jacob Murphy
Jacob Murphy

Reputation: 1492

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.

Upvotes: 6

Related Questions