通过库共享时 NestJS 自定义 PassportStrategy 未注册

问题描述

我的任务是将我们的 nestJS 身份验证模块隔离到一个单独的共享库中,以便在多个 nestJS 项目之间重用它。每个项目都位于每个自己的存储库中,共享库作为 npm 包导入。我正在使用 nestJS 的通行证模块进行身份验证(使用 jwt 令牌),并且基本上只是遵循了有关如何实现它的官方文档。

我遵循了其他 nestJS 社区包的模式,到目前为止,我已经移动了大部分身份验证代码并确保它可以编译和运行。

现在,我遇到了一个问题。应用程序不再识别自定义 jwt 护照策略,在我将它移到图书馆之后,我不知道为什么。我只是得到了例外:

未知的身份验证策略“jwt”

示例:

这是自定义通行证策略和 AuthModule (真实版本更复杂,但这是一个最小的可复制示例)。 “父”项目和新库项目中的代码完全相同。

import { Injectable,Module } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-custom';

@Injectable()
export class CustomStrategy extends PassportStrategy(Strategy,'custom') {
  async validate(request: Request): Promise<any> {
    console.log('Custom validation',request);

    return true;
  }
}

@Module({})
export class AuthModule {
  static forRoot() {
    return {
      module: AuthModule,providers: [CustomStrategy],exports: [CustomStrategy],};
  }
}

这是我在 nestJS 应用程序中注册它的方式:

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from '@my-org/common';        // Library version
// import { AuthModule } from './auth/AuthModule';  // Local version

@Module({
  imports: [
    AuthModule.forRoot(),PassportModule.register({ defaultStrategy: 'custom' })
  ]
})
export class CommonModule {}

export class CustomAuthGuard extends AuthGuard('custom') {}

当从同一个 nestJS 项目中引用 AuthModule 时,一切都会运行并且我收到 Custom validation 控制台消息。

当从我的 npm 库导入 AuthModule 时,每当我提出请求时,我都会收到来自 Passport 的 UnkNown authentication strategy "custom" 异常。

两边的代码完全一样。无论模块来自哪里,模块的用法都是完全相同的。共享库使用与官方 nestJS 包相同的模式设置,例如 @nestjs/common 和 @nestjs/cqrs。图书馆导出的任何其他注册服务都按预期工作(如果需要,我可以包含另一个最小示例来展示这一点)。

我错过了什么?如何使用单独的 npm 包共享我的自定义 nestJS PassportStrategy?

我花了半个工作日试图解决这个问题,到目前为止,我认为这可能与该策略注册到哪个护照实例有关,但我不知道如何进行测试 - 或者,如果是这样,如何解决

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...