Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js: Global AuthGuard but with exceptions

Tags:

nestjs

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?

like image 904
AyKarsi Avatar asked Mar 22 '18 12:03

AyKarsi


People also ask

What is AuthGuard in NestJS?

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.

How do I use NestJS passport?

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.


1 Answers

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);
  }

}
like image 73
Jonathan002 Avatar answered Nov 05 '22 19:11

Jonathan002