我正在使用 NestJS 框架编写 webAPI。我无法使用放置在方法或控制器级别的保护来覆盖全局范围的保护。除了用于登录系统的端点之外,我的所有端点都将使用 JWT 验证保护。是否可以在根级别创建一个防护并仅@UseGuard()在单个方法级别使用装饰器覆盖此全局防护?
我尝试在listen函数调用之前使用 guard并使用APP_GUARD提供程序,但在这两种情况下我都无法覆盖此行为。
只是为了增加我的 2 美分。
我没有像 OP 那样定义 2 个守卫(reject和accept),而是定义了一个自定义装饰器:
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)
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |