Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading