简体   繁体   English

NestJS 无法解析 JWT_MODULE_OPTIONS 的依赖

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

I'm failed to compile with this error:我无法编译此错误:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Nest 无法解析 JWT_MODULE_OPTIONS (?) 的依赖关系。 Please make sure that the argument at index [0] is available in the JwtModule context.请确保索引 [0] 处的参数在 JwtModule 上下文中可用。 +52ms +52ms

I saw similar dependencies problems with modules & services, but they didn't work for me.我看到了模块和服务的类似依赖问题,但它们对我不起作用。 Using JwtModule in my auth.module.ts :在我的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 { }

I have no idea how to fix this bug... Using jwt 6.1.1我不知道如何修复这个错误......使用jwt 6.1.1

Edit: In my previous project use jwt 6.0.0, so I downgrade it, but problem not fix.编辑:在我之前的项目中使用 jwt 6.0.0,所以我降级了它,但问题没有解决。

First, you are mixing the TypeORMModule configuration with the JWTModule configuration.首先,您将 TypeORMModule 配置与 JWTModule 配置混合在一起。

According to @nestjs/jwt source code (and docs ), secretOrPrivateKey and signOptions .根据@nestjs/jwt 源代码(和文档), secretOrPrivateKeysignOptions All the other parameters seem to be part of the TypeORMModule configuration.所有其他参数似乎都是 TypeORMModule 配置的一部分。

Second, the ConfigService (which is dependency [0] of the JWT module) does not seem to exist anywhere in your code.其次,ConfigService(它是 JWT 模块的依赖项 [0])似乎并不存在于您的代码中的任何地方。 So you are missing an import to a module where the ConfigService exists inside.因此,您缺少对内部存在 ConfigService 的模块的导入。

This is why the dependency load is failing (and that is what the error is throwing means)这就是依赖加载失败的原因(这就是错误抛出的意思)

Note that in your code you are missing an import of a module ( ConfigModule in the following sample), which is the module that holds the ConfigService.请注意,在您的代码中,您缺少一个模块(以下示例中的ConfigModule )的导入,该模块是保存 ConfigService 的模块。 Otherwise there is no way to inject this ConfigService from nowhere!否则就没有办法从任何地方注入这个 ConfigService!

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

I somehow got it to work by adding我以某种方式通过添加使其工作

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

in the app.module.ts and auth.module.tsapp.module.tsauth.module.ts

You can make a separate module for it (SharedModule)你可以为它制作一个单独的模块(SharedModule)

make sure you have the following packages installed确保您安装了以下软件包

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

(optional, if you go with MongoDB/Mongoose) (可选,如果您使用 MongoDB/Mongoose)

  npm i --save @nestjs/mongoose 

shared.module.ts共享模块.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 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;
  }
}

Now where you want to use it, just import in your module SharedModule.现在你想使用它,只需在你的模块 SharedModule 中导入。 In your controllers use the following decorator在您的控制器中使用以下装饰器

@UseGuards(AuthGuard())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM