Search code examples
authenticationnestjspassport.js

Implementing Mixed Authentication Strategies in NestJS with Passport


I am working on a NestJS project and having trouble implementing authentication using Passport. My goal is to set up a controller where all routes are protected by JWT authentication, but some specific routes should additionally allow API-key authentication.

I'm aware that the AuthGuard in @nestjs/passport allows an array of strategies like AuthGuard(['jwt', 'headerapikey']). However, when I use this at the controller level, it applies both authentication methods to all the routes within the controller.

The alternative I've considered is applying the guard individually to each method, like so:

@UseGuards(AuthGuard('jwt'))
@Get('route1')
someMethod1() { /*...*/ }

@UseGuards(AuthGuard(['jwt', 'headerapikey']))
@Get('route2')
someMethod2() { /*...*/ }

This approach works, but it feels like I'm duplicating code and not adhering to best practices.

Is there a more elegant or recommended way to achieve this mixed authentication setup?

Thank you!


Solution

  • You could create a second controller class for the module that has the multiple allowed methods, so that they are separated by auth type but still use the same path and you can inject the service into both of them. Otherwise, I'd keep doing what you're doing here, specifying the @UseGuards() with the necessary passport strategies