我有 KeysModule,可用于添加或删除 API key 。我需要这些 key 来保护某些路由免遭未经授权的访问。 为了保护这些路由,我创建了 ApiGuard:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class ApiGuard implements CanActivate {
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest();
return request.headers.api_key;
}
}
然后我在 route 使用它:
@Get('/protected')
@UseGuards(ApiGuard)
async protected(@Headers() headers: Api) {
const key = await this.ks.findKey({ key: headers.api_key });
if (!key || !key.active) return 'Invalid Key';
return 'Your API key works';
}
其中ks是KeyService,用于检查 key 是否正确。 这个解决方案有效,但很愚蠢。我必须在想要使用此防护的任何地方复制并粘贴一些代码行(我的意思是 route 的行)。
我尝试将所有逻辑移至 ApiGuard,但出现错误,KeyService 无法注入(inject)到 ApiGuard 类。解释一下,我在 KeysModule 的提供者中有 KeyService,但 ApiGuard 是全局使用的。
你知道该怎么做吗?
最佳答案
从 NestJS v8 开始,注入(inject) zsoca 在接受的答案中回答的服务似乎不再起作用。
NestJS 8 的工作解决方案是提供类引用而不是字符串:
constructor(@Inject(KeyService) private keyService: KeyService) {}
关于node.js - 在 Nest.JS 中将服务注入(inject)到守卫中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52862644/