簡體   English   中英

NestJS 無法解析 JWT_MODULE_OPTIONS 的依賴

[英]NestJS can't resolve dependencies of the JWT_MODULE_OPTIONS

我無法編譯此錯誤:

Nest 無法解析 JWT_MODULE_OPTIONS (?) 的依賴關系。 請確保索引 [0] 處的參數在 JwtModule 上下文中可用。 +52ms

我看到了模塊和服務的類似依賴問題,但它們對我不起作用。 在我的auth.module.ts 中使用JwtModule

import { JwtModule } from '@nestjs/jwt';
@Module({
    imports: [
        TypeOrmModule.forFeature([User, Role]),
        ConfigModule,
        PassportModule.register({ defaultStrategy: 'jwt' }),
        JwtModule.registerAsync({
            inject: [ConfigService],
            useFactory: async (configService: ConfigService) => ({
                secretOrPrivateKey: config.jwtSecret,
                type: configService.dbType as any,
                host: configService.dbHost,
                port: configService.dbPort,
                username: configService.dbUsername,
                password: configService.dbPassword,
                database: configService.dbName,
                entities: ['./src/data/entities/*.ts'],
                signOptions: {
                    expiresIn: config.expiresIn,
                },
            }),
        }),

    ],
    providers: [AuthService, JwtStrategy],
    controllers: [AuthController],
})
export class AuthModule { }

我不知道如何修復這個錯誤......使用jwt 6.1.1

編輯:在我之前的項目中使用 jwt 6.0.0,所以我降級了它,但問題沒有解決。

首先,您將 TypeORMModule 配置與 JWTModule 配置混合在一起。

根據@nestjs/jwt 源代碼(和文檔), secretOrPrivateKeysignOptions 所有其他參數似乎都是 TypeORMModule 配置的一部分。

其次,ConfigService(它是 JWT 模塊的依賴項 [0])似乎並不存在於您的代碼中的任何地方。 因此,您缺少對內部存在 ConfigService 的模塊的導入。

這就是依賴加載失敗的原因(這就是錯誤拋出的意思)

請注意,在您的代碼中,您缺少一個模塊(以下示例中的ConfigModule )的導入,該模塊是保存 ConfigService 的模塊。 否則就沒有辦法從任何地方注入這個 ConfigService!

JwtModule.registerAsync({
  imports: [ConfigModule], // Missing this
  useFactory: async (configService: ConfigService) => ({
    signOptions: {
       expiresIn: config.expiresIn,
    },
    secretOrPrivateKey: config.jwtSecret,
  }),
  inject: [ConfigService], 
}),

我以某種方式通過添加使其工作

JwtModule.registerAsync({
  imports: [ConfigModule], // Missing this
  useFactory: async (configService: ConfigService) => ({
    signOptions: {
       expiresIn: config.expiresIn,
    },
    secretOrPrivateKey: config.jwtSecret,
  }),
  inject: [ConfigService], 
}),

app.module.tsauth.module.ts

你可以為它制作一個單獨的模塊(SharedModule)

確保您安裝了以下軟件包

npm i --save @nestjs/jwt
npm i --save @nestjs/passport

(可選,如果您使用 MongoDB/Mongoose)

  npm i --save @nestjs/mongoose 

共享模塊.ts

@NgModule({
   imports: [
      PassportModule.register({
          defaultStrategy: 'jwt',
        }),
        JwtModule.register({
          secret: process.env.JWT_SECRET_KEY,
          signOptions: {
            expiresIn: '2 days',
          },
        }),
    
   ],
   providers: [JwtStrategy],
   exports: [JwtStrategy, PassportModule]
})

jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(@InjectModel('User') private collection: Model<User>) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET_KEY,
    });
  }

  async validate(payload: JwtPayload): Promise<User> {
    const { username } = payload;
    const user = await this.collection.findOne({ username });

    if (!user) {
      throw new UnauthorizedException('JwtStrategy unauthorized');
    }

    return user;
  }
}

現在你想使用它,只需在你的模塊 SharedModule 中導入。 在您的控制器中使用以下裝飾器

@UseGuards(AuthGuard())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM