node.js - 在 Nest.JS 中将服务注入(inject)到守卫中

标签 node.js express nestjs

我有 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/

相关文章:

node.js - 如何动态更改 Node js中的数据库连接?

node.js - 开 Jest toEqual 不适用于异常匹配

typescript - 如何使用类验证器验证嵌套 js 中的 uuid 数组?

node.js - Node - 如何测试 stub 依赖项的匿名回调

javascript - 无法在 Node js的模块导出中正确返回

node.js - 清除 mongodb、expressjs、nodejs 中的 session

node.js - NodeJS - 主文件未接收函数内的lookupService的返回

azure - Cosmos DB : Retryable writes are not supported. 请通过指定禁用可重试写入

javascript - 编译失败。 ./node_modules/react-dev-utils/formatWebpackMessages.js 找不到模块 : Can't resolve

javascript - Sequelize js orm seeder 用于多个关系表