【问题标题】:NestJS - Access user from GuardNestJS - 从 Guard 访问用户
【发布时间】:2021-10-12 20:41:57
【问题描述】:

我一直在关注 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.js express nestjs


    【解决方案1】:

    问题是您没有使用角色保护:

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

    第二种方法也一样。

    【讨论】:

    • 嘿,得到同样的东西,未定义。我之前确实尝试过角色保护,但我在这里复制并粘贴了错误的版本,排除了隧道视觉问题
    • 看来我已经修好了,需要按照我自己的回答锁住警卫:)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2021-10-17
      • 2020-02-10
      • 2022-01-11
      • 1970-01-01
      • 2020-07-06
      • 2019-03-16
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多