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

Nest.js集成Azure B2C端点JWT守卫报错:Unknown authentication strategy 'jwt'求助

解决Nest.js Passport JWT "Unknown authentication strategy 'jwt'" 错误

核心问题

你的EndpointStrategy未在模块的providers中注册,Nest无法识别这个自定义JWT策略,导致报错。同时针对Azure B2C场景,还有专属配置需要调整。

步骤1:注册策略到模块

修改app.module.ts,将EndpointStrategy添加到providers数组,同时完善JwtModule的基础配置:

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { EndpointStrategy } from './endpoint.strategy'; // 确保文件路径正确

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: 'INSERT WEIRD KEY HERE', // 和策略中的配置保持一致
      signOptions: { expiresIn: '60s' },
    }),
  ],
  providers: [EndpointStrategy], // 关键:注册自定义JWT策略
})
export class AppModule {}

步骤2:检查依赖是否安装

确保已安装所有必要依赖包:

npm install @nestjs/passport @nestjs/jwt passport-jwt

步骤3:适配Azure B2C的特殊配置

Azure B2C的JWT令牌使用公钥签名,不能直接用固定的secretOrKey,需通过JWKS端点动态获取公钥验证。

首先安装jwks-rsa依赖:

npm install jwks-rsa

然后更新endpoint.strategy.ts代码:

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { passportJwtSecret } from 'jwks-rsa';

@Injectable()
export class EndpointStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      // 替换为你的Azure B2C JWKS端点
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: 'https://你的租户.b2clogin.com/你的租户.onmicrosoft.com/你的策略/discovery/v2.0/keys',
      }),
      // 替换为你的Azure B2C应用信息
      audience: '你的应用客户端ID',
      issuer: 'https://你的租户.b2clogin.com/你的租户ID/v2.0/',
      algorithms: ['RS256'],
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, email: payload.email, idp: payload.idp };
  }
}

验证

修改完成后重启应用,使用Azure B2C颁发的Bearer令牌访问受保护端点,即可正常完成验证。

内容的提问来源于stack exchange,提问作者V. Benavides

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:30:22