是否可以使用控制器/方法范围一覆盖全局范围保护

Mac*_*ski 4 nestjs

我正在使用 NestJS 框架编写 webAPI。我无法使用放置在方法或控制器级别的保护来覆盖全局范围的保护。除了用于登录系统的端点之外,我的所有端点都将使用 JWT 验证保护。是否可以在根级别创建一个防护并仅@UseGuard()在单个方法级别使用装饰器覆盖此全局防护?

我尝试在listen函数调用之前使用 guard并使用APP_GUARD提供程序,但在这两种情况下我都无法覆盖此行为。

代码示例:https : //codesandbox.io/embed/nest-yymkf

Mac*_*ski 7

发布问题后,我找到了问题的解决方案。我应该将一些自定义元数据添加到我的控制器中,并在警卫内部放置一个逻辑来读取该元数据。我已经更新了代码示例。


Joh*_*nny 6

只是为了增加我的 2 美分。

我没有像 OP 那样定义 2 个守卫(rejectaccept),而是定义了一个自定义装饰器:

import { SetMetadata } from '@nestjs/common'

export const NoAuth = () => SetMetadata('no-auth', true)
Run Code Online (Sandbox Code Playgroud)

拒绝守卫 ( AuthGuard) 用于Reflector能够访问装饰器的元数据并根据它决定是否激活。

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Observable } from 'rxjs'

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {

    const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler())

    if(noAuth) return true

    // else your logic here
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我reject在某个模块中全局绑定守卫:

@Module({
  providers: [{
    provide: APP_GUARD,
    useClass: AuthGuard
  }]
})
Run Code Online (Sandbox Code Playgroud)

并在需要时继续使用装饰器:

@NoAuth()
@Get() // anyone can access this
getHello(): string {
  return 'Hello Stranger!'
}

@Get('secret') // protected by the global guard
getSecret(): string {
  return 'ssshhh!' 
}
Run Code Online (Sandbox Code Playgroud)