Access the http request object from a passport strategy constructor

250 views Asked by At


I need to configure my saml strategy dynamically. Specifically I need to retrieve a parameter from the login URL.

I paste here some of my code to better explain my situation:

// auth.controller.ts
@Controller('api/:id/auth')
@UseGuards(SamlAuthGuard)
export class AuthController {
        @Get('login')
        login(@Param('id') id: string) {}
        
        //...
}
@Injectable()
export class SamlStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      // I need the id param here to recover the correct SAML strategy configuration
    })
  }
        
  async validate(profile: Profile) {
    // I know I can access request object from here but it's too late
    return profile;
  }
}

Thanks in advance for the help.

1

There are 1 answers

0
Nicola On

I found a solution to my problem. I am sharing in case anyone needs it.

SAML supports a multi-provider configuration (see Passport SAML doc). In this case the SAMLStrategy constructor accepts a configuration like this:

{
  getSamlOptions: (req: Request, done: SamlOptionsCallback) => {
    // Here I have access to the request object

    // I can throw an error like this
    // done(new Error('I can throw error i'))

    // or I can dynamically build and return my configuration
    done(null, {
      // Here my configuration
      // issuer: ...
      // cert: ...
      // ...
    })
  }
}

In nestjs I passed this configuration directly to the super method in the constructor of my SamlStrategy.

@Injectable()
export class SamlStrategy extends PassportStrategy(MultiSamlStrategy) {
  constructor(private readonly config: ConfigService) {
    super({
      getSamlOptions: (req: Request, done: SamlOptionsCallback) => {
        // As seen above
      }
    })
  }
}

I hope it helps someone!