NestJs 重用使用多个服务的防护会产生"传递给 @UseGuards() 的无效防护"错误



我试图在守卫中检索当前用户以授予他访问权限。我有一个守卫现在没有做任何事情


@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor (
private readonly studentService: StudentService,
private readonly agencyService: AgencyService
) {
super()
}
}

当我像这样将它添加到两个控制器中时

@UseGuards(JwtAuthGuard /* CrudAbilitiesGuard */)
@ApiBearerAuth('access-token')
@ApiBody({ type: CreateStudentDto })
@Post()
async create (
@Body() newStudentDto: CreateStudentDto
): Promise<StudentDocument> {
const student = await this.service.create(newStudentDto)
if (student == null) throw new InternalServerErrorException()
return student
}

抛出Error: Invalid guard passed to @UseGuards() decorator

如果我只在一个控制器中使用guard,它可以正常工作,如果我在构造函数中注释两个服务并在两个控制器中使用它,它也可以正常工作。似乎这是一个偶然的隐藏循环依赖,但我真的无法理解它

编辑:

与直接扩展CanActivate的Guard结果相同

@Injectable()
export class CrudAbilitiesGuard implements CanActivate {
constructor (
private readonly agencyService: AgencyService,
private readonly studentService: StudentService,
private readonly reflector: Reflector,
private readonly caslAbilityFactory: CaslAbilityFactory
) {}
async canActivate (context: ExecutionContext): Promise<boolean> {
return true
}
}

From docs:

Guard是一个带有@Injectable()装饰器的类,它实现了CanActivate接口。

尝试在守卫内部为CanActivate提供一些实现

好吧,这是个大错误。为了避免300多个文件,我在同一个文件中放置了小模块(服务+控制器+模式等),当然会导致数十亿的相互依赖和各种循环问题。注:Module指的是Module

将保护修饰符放在方法前面(在API描述符之后)

顺便说一句,在NestJS中已经有JwtAuthGuard(https://docs.nestjs.com/fundamentals/testing#overriding-globally-registered-enhancers)

providers: [
{
provide: APP_GUARD,
useExisting: JwtAuthGuard,
// ^^^^^^^^ notice the use of 'useExisting' instead of 'useClass'
},
JwtAuthGuard,
],

最新更新