I would like to register my AuthenticationGuard, which checks for Authentication, globally on my application, so that by default all routes require authentication.
const authGuard = app
.select(AuthModule)
.get(AuthGuard);
app.useGlobalGuards(authGuard);
What is the best/nest.js way to add route exceptions, so that anonymous routes can also be implemented?
Authorization guard The AuthGuard that we'll build now assumes an authenticated user (and that, therefore, a token is attached to the request headers). It will extract and validate the token, and use the extracted information to determine whether the request can proceed or not.
You can choose npm or Yarn, as per your preference. After the NestJS app is installed successfully, we need to change directories. Now, we can install the passport package and its utility module for nestjs. We'll also install the package for passport-local and it's types.
You can actually set metadata for the global AuthGuard
so it can determine if it should allow an unauthorized request.
e.g.
Set Global Auth Guard
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';
@Module({
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard,
},
],
})
export class AppModule {}
Use SetMetadata
to pass in data to the AuthGuard
import { SetMetadata } from '@nestjs/common';
// Convienience Function
const AllowUnauthorizedRequest = () => SetMetadata('allowUnauthorizedRequest', true);
@Controller()
export class AppController {
@Get('my-unauthorized-path')
@AllowUnauthorizedRequest()
myHandler () {
return { unauthorized: true };
}
}
Use data passed in from SetMetadata
to determine if unauthorized request is allowed.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { validateRequest } from './validateRequest' // your custom implementation
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const allowUnauthorizedRequest = this.reflector.get<boolean>('allowUnauthorizedRequest', context.getHandler());
return allowUnauthorizedRequest || validateRequest(request);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With