You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS Passport认证调用jwtService.sign()报secretOrPrivateKey错误

错误原因

调用jwtService.sign()抛出secretOrPrivateKey must have a value错误,核心是依赖注入作用域冲突,你在UserModule中重复注册了未配置的服务实例,覆盖了AuthModule中已经完成密钥配置的JwtService:

  • 你在UserModule的providers数组中单独声明了AuthService和JwtService,Nest会在当前模块作用域下创建这两个服务的全新实例。其中直接声明的JwtService没有经过JwtModule.register()注入密钥配置,初始化后secret属性为空,调用签名方法就会触发报错。
  • 你没有在UserModule中导入封装好认证逻辑的AuthModule,反而自行重复声明相关服务,违背了Nest模块的导出复用规则。
  • 代码中存在多处路径拼写错误:多处将auth.service错写为auth.servers,会进一步导致依赖注入匹配异常。
修复方案
  1. 调整UserModule配置,删除providers中重复注册的AuthService、JwtService,在imports数组中导入已配置好的AuthModule,修改后代码如下:
import { Module } from "@nestjs/common";
import { UserController } from "./user.controller";
import { UserService } from "./user.service";
import { TypeOrmModule } from "@nestjs/typeorm";
import { User } from "src/modules/user/user.entity";
// 注意修正路径拼写错误,替换掉原来的auth.servers错误路径
import { AuthModule } from '../auth/auth.module';

@Module({
  imports: [TypeOrmModule.forFeature([User]), AuthModule],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}
  1. 全局修正导入路径,把UserController、LocalStrategy等文件中所有指向../auth/auth.servers的错误导入,全部改为正确的../auth/auth.service路径,保证依赖注入能匹配到正确的服务实例。
  2. 清理AuthModule的冗余配置:imports数组中单独声明的User类属于无效配置,实体注册已经通过TypeOrmModule.forFeature([User])完成,可以直接删除,避免不必要的异常。

内容的提问来源于stack exchange,提问作者Rakonjac S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 12:33:12