【问题标题】:Guard says user is undefined in NestJSGuard 说用户在 NestJS 中未定义
【发布时间】:2021-10-17 17:22:58
【问题描述】:
@UseGuards(JwtAccessTokenAuthGuard)
@ApiBearerAuth()
@SetMetadata('roles', Role.ADMIN)
@UseGuards(RolesGuard)
@Post('/add/card')
addCard(@Body() addCardDto: AddCardDto) {
  return this.storeService.addCard(addCardDto);
}

这是角色卫士

canActivate(context: ExecutionContext): boolean {
  const roles = this.reflector.get<string[]>('roles', context.getHandler());
  if (!roles) {
    return true;
  }
  const user = context.switchToHttp().getRequest().user;
  return this.matchRoles(roles, user.user_type);
}

在此,请求对象在主体或函数addCard 中有用户,但在RoleGuard 中没有。他们说未定义。为什么这样?在JwtAccessTokenGuard我返回了用户属性。

我想在 Guard 内部而不是在功能中检查它。我做错了什么。

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    为了通过这种方法让用户进入守卫:

    const user = context.switchToHttp().getRequest().user;
    

    您应该在本地策略中返回用户对象。这会将user 对象附加到request 对象。正文与user 对象无关。所以,你的 local.strategy.ts 应该是这样的:

    @Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
      constructor(private authService: AuthService) {
        super({ usernameField: 'email' });
      }
    
      async validate(email: string, password: string): Promise<any> {
        const user = await this.authService.validateUser(email, password);
    
        if (!user) {
          throw new UnauthorizedException();
        }
        return user;
      }
    }
    

    有关详细信息,请参阅here

    【讨论】:

    • 我在我的 JwtAuthGuard 中做了这个
    【解决方案2】:

    当使用两个相同的装饰器时,如果我记得的话,顺序是代码中最低的装饰器,然后是最高的装饰器。在这种情况下,为什么不直接将两个 @UseGuards() 合并为像 @UseGuards(JwtAccessTokenAuthGuard, RolesGuard) 这样的单个装饰器,这样您就可以确定在 as described in the docs 中运行守卫的顺序是什么

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 2021-07-30
      • 2016-03-11
      • 2021-10-28
      • 2021-07-10
      • 2017-09-24
      • 2022-01-17
      • 2020-03-26
      • 2019-03-16
      相关资源
      最近更新 更多