1

I am having a NestJS backend application.

my-controller.ts

import { Roles } from 'private-npm';

export class myController {
    constructor(private readonly service: MyService) { }

---> @ClientRoles({ roles: ['test-role'] })
    @Get()
    @ApiOperation({ title: 'List users' })
    async listUsers(): IUser[] {
      return this.service.listUsers(); 
    }
}

@ClientRoles throws Permission not fulfilled, 403 (FORBIDDEN) error, If a user does not have required roles (e.g. test-role).

The problem is, I can see the error message (ERROR: Permission not fulfilled) in the terminal but I do not get the same error message in my Swagger UI response body.

Instead of an error message, I get the following error message in Swagger UI.

{
  "statusCode": 500,
  "message": "Internal server error"
}

It's pretty hard to debug also.

Any help is appreciated.

The Rock
  • 323
  • 1
  • 8
  • 18

1 Answers1

0

Your guard should NOT throw an error. It should implement the CanActivate interface and have a canActivate method, which returns boolean | Promise<boolean> | Observable<boolean> being false if access is denied. And you should pass it to the @UseGuards decorator. Read more about Guards: https://docs.nestjs.com/guards

Usually best practice is to have one Guard which reads metadata written by another decorator.. eg:

@Roles(['roleA', 'roleB'])
@UseGuards(new RoleGuard())

Although you could combine those by making a factory function for which you pass the roles and it returns the guard instance.

funkizer
  • 4,626
  • 1
  • 18
  • 20