NestJS - Access user from Guard

Viewed 2288

I've been following the official NestJS documentation. I have successfully setup JWT passport authentication. I can access the user details from the @Req within controllers but I'm having issues accessing the user details from within the custom guard.

This works fine

@UseGuards(RolesGuard)
@Get('me')
  getProfile(@Request() req) {
    return req.user;
  }

This does not (curently logging for debug)

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      console.log('No Roles');
      return true;
    }
    const request = context.switchToHttp().getRequest();
    
    // Returns Undefined 
    console.log(request.user);
    return true;
  }
}

This is how I'm declaring each entry in the controller

  @Get()
  @UseGuards(RolesGuard)
  @Roles('admin')
  findAll() {
    return this.usersService.findAll();
  }

The pass through of roles metadata is working fine, just looks like the user isn't being appended to the context at the correct step.

Any help would be great, thanks!

EDIT: updated @UseGuards(RolesGuard), copied and pasted wrong version

2 Answers

The issue is you are not using the rolesGuard :

@UseGuards(JwtAuthGuard) // <= replace JwtAuthGuard with your guard: RolesGuard 
@Get('me')
getProfile(@Request() req) {
return req.user;
 }

the same for the second method.

Looks like i've fixed it, have to chain them

@Get()
  @Roles('admin')
  @UseGuards(JwtAuthGuard, RolesGuard)
  findAll() {
    return this.usersService.findAll();
  }
Related