NestJs Public endpoit with Global Auth
Hi everyone, my name is Rodrigo Alcorta and this is my first post on Medium! I’m a freelancer web developer and student of Informatics engineering from Argentina.
Many times we need to implement authentication on the entire site. One way to do this is applying an Auth Guard on the App Provider array. The problem is that perhaps we don’t know how exclude this authentication on certain endpoints, like Login.
This take me some time until I got the answer. In this post we will discuss how to do it and implement it.
This article assumes that authentication is already implemented. If is not, you can see how do it from the official NestJs documentation: https://docs.nestjs.com/techniques/authentication
Index of the article:
- Part 1: Create Public Decorator
- Part 2: Create a custom AuthGuard
- Part 3: Make this AuthGuard Global
- Part 4: Check in AuthGuard if the method is public or not
Part 1: Create Public Decorator
First, we’ll create a decorator that will help us later to know if this endpoint is public or not:
Part 2: Create a custom AuthGuard
Create a new Guard named AuthGuard (You can name this guard as you want, in this case AuthGuard) and let’s make it extends from the Auth guard that you are using (In this case I use JwtAuthGuard):
Part 3: Make this AuthGuard Global
Now you need to put this new Guard in the app provider:
@Module({... providers: [
... { provide: APP_GUARD, useClass: AuthGuard, }, ... ],
....})export class AppModule { }
Part 4: Check in AuthGuard if the method is public or not
Now, the authentication is required for all the routes, excluding for a specific route or class that can be made by adding the @Public()
decorator. For example:
@Public()
@Get()
public getHello(): string {
return this.appService.getHello();
}
Summary:
This give us a view of how we can implement guards with decorators and metadata to give us a great flexibility and multiple ways to combine them.
I hope it works for you and you have learned something new.
Greetings Rodrigo!
Personal WebSite: https://rodrigoalcorta.com