NestJS - 从 Guard 访问用户

NestJS - Access user from Guard

我一直在关注 NestJS 官方文档。我已成功设置 JWT 护照身份验证。我可以从控制器内的@Req 访问用户详细信息,但我在从自定义防护中访问用户详细信息时遇到问题。

这个很好用

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

这不是(当前正在记录调试)

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

这就是我在控制器中声明每个条目的方式

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

角色元数据的传递工作正常,只是看起来用户没有在正确的步骤附加到上下文。

任何帮助都会很棒,谢谢!

编辑:更新了@UseGuards(RolesGuard),复制并粘贴了错误的版本

问题是您没有使用 rolesGuard :

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

第二种方法相同

看来我已经修复了,必须链接它们

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