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

NestJS调用JWT守卫接口报错:Unknown authentication strategy 'jwt'

解决NestJS中"Unknown authentication strategy 'jwt'"错误

请求受Jwt策略守卫的/auth/profile接口时,触发以下错误:

ERROR [ExceptionsHandler] Unknown authentication strategy "jwt"
Error: Unknown authentication strategy "jwt"

问题根源

核心错误出在jwt.strategy.ts文件——你错误导入了passport-local的Strategy类,而非passport-jwt的Strategy。Passport需要对应策略的实现类,用local的Strategy无法注册"jwt"策略,导致守卫找不到对应策略。

修正代码

将jwt.strategy.ts中的Strategy导入替换为passport-jwt的对应类,修正后的代码如下:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
// 替换为passport-jwt的Strategy
import { Strategy } from 'passport-jwt';
import { ExtractJwt } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { IUser } from '../../types/types';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretKey: configService.get('JWT_SECRET'),
    });
  }

  async validate(user: IUser) {
    return { id: user.id, email: user.email };
  }
}

额外检查确认

  • 你的AuthModule已正确将JwtStrategy注册到providers数组,无需修改
  • JwtAuthGuard继承AuthGuard('jwt')时的策略名称,与passport-jwt的Strategy默认注册名称一致,无需调整

修正后重启服务,携带有效JWT令牌请求/auth/profile接口,控制台将正常输出"some profile"。

内容的提问来源于stack exchange,提问作者Павел Хорольський

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:52:55