Nest.js全局JwtService配置异常:守卫中无密钥无法正常工作
全局JwtService在自定义守卫中未配置密钥的问题解决
问题描述
我尝试将JwtService设置为全局服务,但在实现CanActivate的自定义守卫JwtAuthGuard中无法正常工作——JwtService实例存在,但未配置密钥,调用verify方法时验证失败。
相关代码
全局注册服务
forwardRef(() => UsersModule), { ...JwtModule.registerAsync({ useFactory: (configService: ConfigService) => ({ secret: configService.get<string>('PRIVATE_KEY'), signOptions: { expiresIn: '24h', }, }), inject: [ConfigService], }), global: true, },
JwtAuthGuard守卫
@Injectable() export class JwtAuthGuard implements CanActivate { constructor(private jwtService: JwtService) {} canActivate( context: ExecutionContext, ): boolean | Promise<boolean> | Observable<boolean> { const req = context.switchToHttp().getRequest(); try { const authHeader = req.headers.authorization; const [bearer, token] = authHeader.split(' '); if (bearer.toLowerCase() !== 'bearer' || !token) throw new UnauthorizedException({ message: '用户未授权', }); const user = this.jwtService.verify(token); req.user = user; return true; } catch (e) { console.log(e); throw new UnauthorizedException({ message: '用户未授权', }); } } }
Auth模块
@Module({ controllers: [AuthController], providers: [JwtService], imports: [forwardRef(() => UsersModule)], exports: [], }) export class AuthModule {}
问题原因
AuthModule的providers数组中手动声明了JwtService,这会导致Nest创建一个全新的、未经过任何配置的JwtService实例,覆盖了全局JwtModule提供的已配置实例。
解决方法
- 移除AuthModule中手动添加的JwtService
修改后的AuthModule代码如下:@Module({ controllers: [AuthController], providers: [], // 移除JwtService imports: [forwardRef(() => UsersModule)], exports: [], }) export class AuthModule {} - 确认全局JwtModule配置正确
确保ConfigService能正确读取到PRIVATE_KEY,全局注册的JwtModule结构无误。 - 检查其他模块是否重复提供JwtService
如果JwtAuthGuard在其他模块中声明,确保该模块没有在providers中重复添加JwtService,依赖全局JwtModule提供的实例即可。
内容的提问来源于stack exchange,提问作者Артём Копиль
相关产品推荐
相关产品推荐

