how NestJs config a custom state into 'passport-azure-ad' OIDCStrategy options

271 Views Asked by At
@Injectable()
   export class AzureADStrategy extends PassportStrategy(OIDCStrategy, 'azuread') {
   constructor() {
   super({
   identityMetadata: 'https://login.microsoftonline.com/xxx/v2.0/.well-known/openid-configuration',
   clientID: 'xxx',
   redirectUrl: 'http://localhost/auth/azure',
   responseType: 'id_token',
   responseMode: 'form_post',
   allowHttpForRedirectUrl: true,
   passReqToCallback: true,
   //customState: 'custom state test' ??
   });

i tried to above code, and check passport-azure-ad docs, however, i can not get a way to pass custom state to azure ad and receive it in nestjs callback controller. please help to resolve, many thanks

1

There are 1 best solutions below

0
JW. On

It's not obvious, but you can use a custom AuthGuard for this, and override the getAuthenticateOptions method. For example, if you wanted to get the state from the initial URL's ?state=<state> param:

import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard, IAuthModuleOptions } from '@nestjs/passport';

@Injectable()
export class AzureAuthGuard extends AuthGuard('azuread-openidconnect') {
  getAuthenticateOptions(context: ExecutionContext): IAuthModuleOptions {
    const request = context.switchToHttp().getRequest();
    return {
      customState: request.query.state,
    };
  }
}

and when the auth redirects, read the state in your controller:

@UseGuards(AzureAuthGuard)
@Post('redirect')
async redirect(@Body('state') state: string): Promise<void> {
  console.log('state', state);
  ...
}