【发布时间】:2019-03-22 14:11:32
【问题描述】:
我有 KeysModule,可用于添加或删除 API 密钥。我需要这些密钥来保护某些路由免受未经授权的访问。 为了保护这些路由,我创建了 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;
}
}
然后我在路由中使用它:
@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。 这个解决方案有效,但很愚蠢。我必须在任何我想使用这个守卫的地方复制和粘贴一些代码行(我的意思是路线中的行)。
我尝试将所有逻辑移至 ApiGuard,但出现错误,无法将 KeyService 注入 ApiGuard 类。说明一下,我在 KeysModule 的 provider 中有 KeyService,但是 ApiGuard 是全局使用的。
你知道怎么做吗?
【问题讨论】: