NestJS集成Passport与JWT时出现Unknown authentication strategy "jwt"错误
NestJS Passport-JWT认证报错:Unknown authentication strategy "jwt"
错误信息
ERROR [ExceptionsHandler] Unknown authentication strategy "jwt" Error: Unknown authentication strategy "jwt" at attempt (/path/to/node_modules/passport/lib/middleware/authenticate.js:193:39) at authenticate (/path/to/node_modules/passport/lib/middleware/authenticate.js:379:7) ...
问题背景
此前应用运行正常,近期未修改任何代码,但使用JWT令牌认证时突然出现上述错误,导致认证失败。
相关代码片段
Auth模块
import { Module } from '@nestjs/common'; import { AuthService } from './auth.service'; import { AuthController } from './auth.controller'; import { CommonModule } from '../common/common.module'; import { PassportModule } from '@nestjs/passport'; import { JwtModule } from '@nestjs/jwt'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { JwtStrategy } from './strategies/jwt.strategy'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './entities/user.entity'; @Module({ imports: [ ConfigModule, CommonModule, PassportModule.register({ defaultStrategy: 'jwt' }), JwtModule.registerAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => ({ secret: configService.get('SECRET_KEY'), signOptions: { expiresIn: '1d', }, }), }), TypeOrmModule.forFeature([User]), ], controllers: [AuthController], providers: [AuthService, UsersService, JwtStrategy], exports: [PassportModule, JwtStrategy, JwtModule, AuthService], }) export class AuthModule {}
JWT策略
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { CommonService } from '@/common/common.service'; import { ErrorCodes } from '@/common/interfaces/error-codes.interface'; import { User } from '../entities/user.entity'; import { JwtPayload } from '../interfaces/jwt-payload.interface'; import { UsersService } from '../users.service'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private readonly userService: UsersService, private readonly configService: ConfigService, private readonly commonService: CommonService, ) { super({ secretOrKey: configService.get('SECRET_KEY'), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, }); } async validate(payload: JwtPayload): Promise<User> { const { email } = payload; const user = await this.userService.findOneByEmail(email); if (!user) this.commonService.handleErrors(ErrorCodes.TokenNotValid); delete user.password, user.name, user.email; return user; } }
当前依赖版本
"@nestjs/passport": "10.0.3" "@nestjs/jwt": "^10.2.0" "passport": "^0.7.0" "passport-jwt": "^4.0.1"
已尝试的解决步骤
- 执行
npm install重装所有依赖 - 确认环境变量
SECRET_KEY配置正确 - 校验
@nestjs/passport、@nestjs/jwt和passport-jwt版本兼容性
排查与解决方案
1. 检查模块导入完整性
确保使用@UseGuards(AuthGuard('jwt'))的模块已正确导入AuthModule,或直接导入PassportModule与JwtStrategy。模块间依赖缺失会导致Passport无法识别jwt策略。
2. 验证JwtStrategy的注册与注入
- 确认
JwtStrategy类上的@Injectable()装饰器未被误删 - 检查
AuthModule的providers数组是否包含JwtStrategy,且导出配置正确(若其他模块需使用)
3. 清理缓存与重新构建
- 删除
node_modules和package-lock.json,重新执行npm install - 删除
dist编译目录,执行npm run build重新编译项目
4. 检查Passport初始化顺序
确保PassportModule在JwtModule之前导入,避免策略注册延迟。可尝试在PassportModule.register时显式指定策略名称,确保与AuthGuard中使用的名称一致。
5. 验证环境变量加载时机
在JwtStrategy构造函数中打印configService.get('SECRET_KEY'),确认变量已正确加载。若ConfigModule未全局注册,需确保JwtStrategy所在模块已导入ConfigModule。
6. 锁定依赖版本到历史正常版本
若版本兼容问题导致策略注册失败,可尝试锁定到之前运行正常的依赖版本,例如:
"@nestjs/passport": "10.0.3", "@nestjs/jwt": "10.1.1", "passport": "0.6.0", "passport-jwt": "4.0.1"
内容的提问来源于stack exchange,提问作者JDorozco
相关产品推荐
相关产品推荐

