【问题标题】:In NestJS, how to get execution context or request instance in custom method decorator?在 NestJS 中,如何在自定义方法装饰器中获取执行上下文或请求实例?
【发布时间】:2020-08-19 23:42:00
【问题描述】:

我有一个像这样的自定义方法装饰器。

export function CustomDecorator() {

    return applyDecorators(
        UseGuards(JwtAuthGuard)
    );
}

在自定义装饰器中,我想获取请求头,但不知道如何获取请求实例?

【问题讨论】:

  • 可以添加更多关于你想做什么的信息吗?我知道您想访问标头但出于什么目的?
  • 我们有一个共享的身份验证模块,我们可以在其中拥有 JWT 或 GoogleAuth。我想实现一个自定义装饰器,它根据请求标头应用不同的保护。

标签: decorator nestjs


【解决方案1】:

您将无法在类或方法装饰器中获取ExectuionContext 对象或Request 对象,因为这些装饰器在导入时立即运行。相反,应该做的是创建一个SuperGuard,它确实可以使用ExecutionContext。这个SuperGuard 应该通过constructor 将所有其他守卫注入其中,并且根据标题,您应该调用/返回被调用守卫的结果。像这样的:

@Injectable()
export class SuperGuard implements CanActivate {
  constructor(
    private readonly jwtAuthGuard: JwtAuthGuard,
    private readonly googleAuthGuard: GoogleAuthGuard,
  ) {}

  canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest();
    if (req.headers['whatever'] === 'google') {
      return this.googleAuthGuard.canActivate(context);
    } else {
      return this.jwtAuthGuard.canActivate(context);
    }
  }
}

【讨论】:

  • 嗨,Jay,我收到此错误。错误:Nest 无法解析 RomeGuard (?) 的依赖关系。请确保索引 [0] 处的参数 JwtAuthGuard 在 AuthModule 上下文中可用。潜在的解决方案: - 如果 JwtAuthGuard 是提供者,它是当前 AuthModule 的一部分吗? - 如果 JwtAuthGuard 是从一个单独的 @Module 导出的,那么该模块是在 AuthModule 中导入的吗? @Module({ imports: [ /* the Module contains JwtAuthGuard */ ] }) at Injector.lookupComponentInParentModules
  • 您需要确保无论在何处使用SuperGuard,您都将JwtAuthGuardGoogleAuthGuard 添加为providers。如果您愿意,可以通过GuardModule 完成此操作
  • 嗨,Jay,我像这样添加了它providers: [SharedDataAuthService, JwtStrategy, JwtAuthGuard],,但它显示了该错误。
  • 一切都好,杰伊。我还需要将其添加到导出中。感谢您的帮助。
  • 嗨 Jay,我有一个问题......如果 Guard 装饰器在导入时立即运行,它如何在 executionContext 中捕获请求? ^^
猜你喜欢
  • 2021-10-17
  • 2021-09-30
  • 2019-03-30
  • 1970-01-01
  • 2021-04-11
  • 2021-08-08
  • 1970-01-01
  • 2023-02-16
  • 2019-08-09
相关资源
最近更新 更多