我想创建一个身份验证模块作为单独的节点包,以便我们可以将它重用于多个项目。
作为其中的一部分,我们希望通过 AuthLibModule 从主应用程序提供必要的配置。register() 将此参数作为配置提供。
并且传递的配置将使用注入令牌保存,以通过依赖注入使用它。
我们如何实现它?
AuthLib.module.ts
@Module({})
export class AuthLibModule {
static register(config: AuthLibConfig): DynamicModule {
const authConfigToken = {
provide: AuthLibConstants.JWT_CONFIG_TOKEN,
useValue: config.jwtConfig
};
return {
module: AuthLibModule,
imports: [
ConfigModule.forRoot(
{
isGlobal: true
}
),
MongooseModule.forRoot(config.mongoDbUrl ? config.mongoDbUrl : process.env.MONGO_URI),
AuthModule
],
controllers: [],
exports: [authConfigToken],
providers: [authConfigToken]
}
}
}
APP.MODULE.TS
@Module({
imports: [
AuthLib.register({
authTokenExpiration: 60S,
authTokenSecret: XYZZZZZ,
refreshTokenSecret: YYYYYYYYYYYYYYYYY,
refreshTokenExpiration: 90S
})
],
controllers: [],
providers: [],
})
export class AppModule { }
jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, GuardNames.jwtAuth) {
constructor(
@Inject(AuthLibConstants.JWT_CONFIG) jwtConfig: JWTConfig
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
// jwtConfig.authTokenSecret -> getting as undefined.
secretOrKey: jwtConfig.authTokenSecret
});
}
async validate(payload: TokenParsePayload): Promise<TokenParsePayload> {
return payload;
}
}
错误:
[Nest] 21492 - 28/02/2022, 5:30:03 pm ERROR [ExceptionHandler] JwtStrategy requires a secret or key
TypeError: JwtStrategy requires a secret or key
at new JwtStrategy (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\passport-jwt\lib\strategy.js:45:15)
at new MixinStrategy (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\passport\dist\passport\passport.strategy.js:32:13)
at new JwtStrategy (D:\Freelancing\code-mentor\infra-services\auth-lib\src\auth\strategies\Jwt-auth.strategy.ts:17:9)
at Injector.instantiateClass (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\injector.js:301:19)
at callback (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\injector.js:48:41)
at Injector.resolveConstructorParams (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\injector.js:124:24)
at Injector.loadInstance (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\injector.js:52:9)
at Injector.loadProvider (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\injector.js:74:9)
at async Promise.all (index 6)
at InstanceLoader.createInstancesOfProviders (D:\Freelancing\code-mentor\infra-services\auth-lib\node_modules\@nestjs\core\injector\instance-loader.js:44:9)