gpt4 book ai didi

node.js - NestJS JWT 策略需要一个 secret 或 key

转载 作者:行者123 更新时间:2023-12-03 12:16:07 24 4
gpt4 key购买 nike

在我的 NestJS Node 应用程序中,我使用 Passport 设置了 JWT 身份验证(根据 https://docs.nestjs.com/techniques/authentication),但是我试图将 JWT key 保留在使用内置 ConfigService 检索的环境文件中。

export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_KEY'),
signOptions: { expiresIn: '60s' }
});
}
模块注册如下:
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_KEY')
};
},
inject: [ConfigService]
})
启动应用程序时出现以下错误:
api: [Nest] 16244   - 03/27/2020, 10:52:00   [ExceptionHandler] JwtStrategy requires a secret or key +1ms
似乎 JWTStrategy 类在 ConfigService 准备好提供 JWT key 之前进行实例化,并且在调用 configService.get<string>('JWT_KEY') 时在策略中返回 undefined .
我在这里做错了什么?在尝试检索任何环境变量之前,如何确保 ConfigService 已准备就绪?
更新:
整个 AuthModule 如下:
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
import { SharedModule } from '../shared/shared.module';
import { UsersModule } from '../users/users.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';

const passportModule = PassportModule.register({ defaultStrategy: 'jwt' });
@Module({
imports: [
UsersModule,
passportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_KEY')
};
},
inject: [ConfigService]
})
],
providers: [ConfigService, AuthService, LocalStrategy, JwtStrategy],
controllers: [AuthController],
exports: [passportModule]
})
export class AuthModule {}

最佳答案

我敢打赌,问题在于你不是 import使用 ConfigModuleAuthModule相反,您正在添加 ConfigServiceproviders直接排列。这意味着如果 ConfigModule是否在 ConfigService 上进行任何类型的设置,不会再发生了。你应该拥有的是这样的:

@Module({
imports: [
PassportModule.register({defaultStrategy: 'jwt' }),
UserModule,
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_KEY')
};
},
inject: [ConfigService]
}),
ConfigModule,
],
providers: [LocalStrategy, JwtStrategy, AuthService],
controllers: [AuthController],
exports: [PassportStrategy],
})
export class AuthModule {}

现在只要一个 ConfigModule exports ConfigService , AuthModule应该开火就好了。

关于node.js - NestJS JWT 策略需要一个 secret 或 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60884932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com