Ale*_*yne 4 javascript typescript nestjs
我的应用程序有两个基于 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。
我发现的另一个选择是让一个策略继承另一个策略。但这是一种丑陋的语义混乱,因为它们是并行的,并且根本不依赖于彼此。
| 归档时间: |
|
| 查看次数: |
5704 次 |
| 最近记录: |