NestJS无法解析JWT_MODULE_OPTIONS的依赖项

时间:2019-08-12 14:53:31

标签: typescript module nestjs

我无法通过此错误进行编译:

嵌套不能解析JWT_MODULE_OPTIONS(?)的依赖项。请确保在JwtModule上下文中索引[0]处的参数可用。 + 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,因此我对其进行了降级,但问题未解决。

3 个答案:

答案 0 :(得分:1)

首先,您将TypeORMModule配置与JWTModule配置混合在一起。

根据@nestjs/jwt source code(和docs),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], 
}),

答案 1 :(得分:0)

我通过添加

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

app.module.ts auth.module.ts

答案 2 :(得分:0)

你可以为它制作一个单独的模块(SharedModule)

确保您安装了以下软件包

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

(可选,如果你使用 MongoDB/Mongoose)

  npm i --save @nestjs/mongoose 
<块引用>

shared.module.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())