Nest JS Guards - 使用两种策略之一

Ale*_*yne 4 javascript typescript nestjs

我的应用程序有两个基于 JWT 的策略:

  • 我的组织及其成员的单点登录。外部提供商为此案例创建 JWT。
  • 电子邮件/密码经过身份验证的外部用户。我的应用程序为此案例创建了一个 JWT。

在任何给定的路线上,我只需要其中一个即可成功允许访问。问题是,如果声明了多个守卫,那么所有守卫都必须成功。

例如,这需要两名守卫都成功,但只有一名守卫会成功。

@UseGuards(AuthGuard('local-jwt'))
@UseGuards(AuthGuard('azure-ad'))
someRoute(
  @CurrentUser currentUser: User,
) {
  //...
}
Run Code Online (Sandbox Code Playgroud)

关于这个问题,我找到了这个片段:

@Injectable()
export class ComposeGuard implements CanActivate {
  constructor(private allowGuard: AllowGuard, private authGuard: AuthGuard, private roleGuard: RoleGuard) {
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    return await this.allowGuard.canActivate(context) || (await this.authGuard.canActivate(context) &&  await this.roleGuard.canActivate(context));
  }
}
Run Code Online (Sandbox Code Playgroud)

这似乎允许我需要的自定义逻辑,但我不知道如何将守卫作为依赖项导入。守卫似乎不是一个类,因此它对于依赖注入是有效的。而策略是一个类,但没有方法canActivate


我发现的另一个选择是让一个策略继承另一个策略。但这是一种丑陋的语义混乱,因为它们是并行的,并且根本不依赖于彼此。

Jay*_*iel 10

根据这个拉取请求,您可以使用@UseGuards(AuthGuard(['strategy1', 'strategy2']))护照将运行第一个策略,如果失败,它将通过策略2,直到策略N。如果运行该策略时出现错误,那么该策略将很快失败。