Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
NestJS - Access user from Guard

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

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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

@Get()
  @Roles('admin')
  @UseGuards(JwtAuthGuard, RolesGuard)
  findAll() {
    return this.usersService.findAll();
  }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda