首页 > 解决方案 > NestJS - 从 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),复制并粘贴了错误的版本

标签: node.jsexpressnestjs

解决方案


看起来我已经修好了,必须把它们锁起来

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

推荐阅读