【问题标题】:NestJS Dependency Injection in Websocket AdapterWebsocket 适配器中的 NestJS 依赖注入
【发布时间】:2021-11-05 03:31:33
【问题描述】:

我正在尝试在 NestJS 应用程序中建立 websocket 连接时验证和检查用户的权限。

我找到了推荐使用NestJS Websocket adapterthis discussion。您可以在options.allowRequest 回调中执行令牌验证,如下所示。

export class AuthenticatedSocketIoAdapter extends IoAdapter {

  private readonly authService: AuthService;
  constructor(private app: INestApplicationContext) {
    super(app);
    this.authService = app.get(AuthService);
  }

  createIOServer(port: number, options?: SocketIO.ServerOptions): any {
    options.allowRequest = async (request, allowFunction) => {

      const token = request.headers.authorization.replace('Bearer ', '');

      const verified = this.authService.verifyToken(token);
      if (verified) {
        return allowFunction(null, true);
      }
      
      return allowFunction('Unauthorized', false);
    };

    return super.createIOServer(port, options);
  }
}

但是,我在 websocket 适配器中的依赖注入存在问题。 IoAdapter 的构造函数有一个 INestApplicationContext 参数,我正在尝试使用 app.get(AuthService) 取回 AuthService,如上所示。

AuthService 注入另外两个服务,UserServiceJwtService 来检查 JWT 令牌。我的问题是这些服务仍未在该上下文中定义。

@Injectable()
export class AuthService {
  constructor(private usersService: UsersService, private jwtService: JwtService) {}

  verifyToken(token: string): boolean {
    // Problem: this.jwtService is undefined
    const user = this.jwtService.verify(token, { publicKey });
    // ... check user has permissions and return result
  }

对于信息,AuthService 位于另一个模块中,而不是定义 Websocket 的模块。我还尝试在当前模块中导入 AuthService(及其依赖项),但这没有帮助。

是否可以使用app.get() 方法使用服务?

【问题讨论】:

    标签: websocket dependency-injection service nestjs adapter


    【解决方案1】:

    我可以通过使用app.resolve() 而不是app.get() 来解决DI 问题

    export class AuthenticatedSocketIoAdapter extends IoAdapter {
      private authService: AuthService;
    
      constructor(private app: INestApplicationContext) {
        super(app);
        app.resolve<AuthService>(AuthService).then((authService) => {
          this.authService = authService;
        });
      }
    }
    

    这解决了AuthService 中注入的jwtService 未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 2021-04-06
      • 2020-09-09
      • 2021-04-23
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多