代码之家  ›  专栏  ›  技术社区  ›  Greggy

在门卫中注入服务巢.JS

  •  0
  • Greggy  · 技术社区  · 8 年前

    我有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的providers中有KeyService,但ApiGuard是全局使用的。

    你知道怎么做吗?

    2 回复  |  直到 8 年前
        1
  •  7
  •   Jinni    7 年前

    将服务注入守卫。你可以创建全局模块。

    // ApiModule
    import {Module,Global} from '@nestjs/common';
    import {KeyService} from '../';
    
    @Global()
    @Module({
        providers: [ KeyService ],
        exports: [KeyService]
    })
    export class ApiModule {}
    

    然后像这样给守卫注入服务

    // guard
    export class ApiGuard implements CanActivate {
    constructor(@Inject('KeyService') private readonly KeyService) {}
    }
     async canActivate(context: ExecutionContext) {
        // your code
        throw new ForbiddenException();
      }
    

    现在问题是解决了。但是我有另一个问题。我想向服务中注入一些内容,但遇到以下错误:

    我的解决方案是:

    在KeyService中注入其他依赖项,比如 nestjs docs 说吧。

    从任何模块外部注册的全局保护(在上面的示例中使用useGlobalGuards())无法注入依赖项,因为这是在任何模块的上下文之外完成的。

    这是他们的样品

    // app.module.js
    import { Module } from '@nestjs/common';
    import { APP_GUARD } from '@nestjs/core';
    
    @Module({
      providers: [
        {
          provide: APP_GUARD,
          useClass: RolesGuard,
        },
      ],
    })
    export class ApplicationModule {}
    

    它成功了。现在我可以使用guard global而不会出现依赖错误。

        2
  •  4
  •   Zsoca    7 年前

    也许已经太迟了,但我也遇到了同样的问题并找到了解决办法。也许还有更好的方法,但它对我来说很正常:

    将KeysModule定义为全局模块,可以在nestjs docs中查看如何实现: https://docs.nestjs.com/modules

    完成此操作后:

    import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
    
    @Injectable()
    export class ApiGuard implements CanActivate {
    
    constructor(
    @Inject('KeyService')
    private readonly ks
    ) {}
    
    const key = await this.ks.findKey();
    
    "YOUR_CODE_HERE..."
    
    }
    

    希望这对你或者将来会坚持这个的人有所帮助。

        3
  •  0
  •   quen2404    8 年前

    您可以像在任何用 Injectable . 如果您的ApiGuard需要KeyService,您有两个选择:

    • 在导入KeysModule的模块中添加ApiGuard。然后导入创建的模块以全局使用ApiGuard
    • 在KeysModule中添加ApiGuard并将其导出。