NestJS - 从 Guard 访问用户

Tob*_*ton 5 node.js express nestjs

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

这很好用

@UseGuards(RolesGuard)
@Get('me')
  getProfile(@Request() req) {
    return req.user;
  }
Run Code Online (Sandbox Code Playgroud)

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

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  @Get()
  @UseGuards(RolesGuard)
  @Roles('admin')
  findAll() {
    return this.usersService.findAll();
  }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Tob*_*ton 3

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

@Get()
  @Roles('admin')
  @UseGuards(JwtAuthGuard, RolesGuard)
  findAll() {
    return this.usersService.findAll();
  }
Run Code Online (Sandbox Code Playgroud)