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

NestJS链式使用多个JWT策略报未知sec认证策略如何解决

问题根因

报错Unknown authentication strategy "sec"是因为自定义的第二个JWT策略没有显式指定策略名称。
NestJS的PassportStrategy封装默认规则:继承策略类时如果不传入第二个自定义名称参数,会使用当前passport策略的默认名称。你两个策略都基于passport-jwt的Strategy实现,默认名称都是jwt,所以框架根本没有注册名为sec的认证策略,守卫调用时自然找不到。
另外你的jwt.strategy.ts中secretOrKey使用了中文全角单引号‘test’,会导致密钥解析错误,也需要一并修正。

修复方法
  • 修改sec.strategy.ts的策略继承声明,显式指定策略名为sec,和守卫中传入的名称对应:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
// 第二个参数传入自定义策略名,与守卫配置对齐
export class JwtStrategysec extends PassportStrategy(Strategy, 'sec') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: '1test',
    });
  }
  async validate(payload: any) {
    return {
      userId: payload.sub,
      username: payload.username,
    };
  }
}
  • 修正jwt.strategy.ts中的全角引号问题,将secretOrKey: ‘test’改为secretOrKey: 'test'(使用英文半角单引号)。
  • 你当前AuthModule中两个策略的provider注册配置是正确的,修改完成后重启项目,AuthGuard(['jwt', 'sec'])就会按顺序尝试两个策略,任意一个校验通过即可完成认证。

内容的提问来源于stack exchange,提问作者Erika

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 06:06:40