首页 > 解决方案 > NestJS - 组合多个警卫并在一个返回 true 时激活

问题描述

我有一个问题。

是否可以在一条路线上使用多个身份验证守卫(在我的情况下是基本身份验证和 ldap 身份验证)。当一个守卫成功时,应该对路由进行身份验证。

标签: nestjs

解决方案


简短回答:不,如果您在一条路线上添加多个守卫,他们都需要通过才能激活路线。

长答案:但是,通过使您的 LDAP 保护扩展基本保护,您可以尝试完成。如果 LDAP 特定逻辑成功,则返回true,否则返回调用结果到super.canActivate()。然后,在您的控制器中,将基本或 LDAP 保护添加到您的路由中,但不能同时添加两者。

基本的.guard.ts

export BasicGuard implements CanActivate {
  constructor(
      protected readonly reflector: Reflector
  ) {}

  async canActivate(context: ExecutionContext) {
     const request = context.switchToHttp().getRequest();
     if () {
        // Do some logic and return true if access is granted
        return true;
     }

    return false;
  }
}

ldap.guard.ts

export LdapGuard extends BasicGuard implements CanActivate {
  constructor(
      protected readonly reflector: Reflector
  ) {
   super(reflector);
}

  async canActivate(context: ExecutionContext) {
     const request = context.switchToHttp().getRequest();
     if () {
        // Do some logic and return true if access is granted
        return true;
     }
    
    // Basically if this guard is false then try the super.canActivate.  If its true then it would have returned already
    return await super.canActivate(context);
  }
}

有关更多信息,请参阅官方 NestJS 存储库上的这个 GitHub 问题


推荐阅读