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

如何配置NestJS验证Azure AD令牌?解决签名无效问题

解决Azure AD令牌验证签名无效问题

1. 检查令牌受众匹配性

用jwt.io解析前端获取的access_token,确认aud字段值和NestJS配置中的clientID完全一致。Azure AD仅会验证受众为当前后端应用ID的令牌。

2. 修正BearerStrategy配置

Azure AD v2端点默认使用非对称签名,无需配置clientSecret,通过JWKS自动验证签名。调整后的配置如下:

@Injectable()
export class AzureADStrategy extends PassportStrategy(
  BearerStrategy,
  'azure-ad',
) {
  constructor() {
    super({
      identityMetadata: `https://login.microsoftonline.com/${tenantID}/v2.0/.well-known/openid-configuration`,
      clientID, // 必须与令牌aud字段值一致
      validateIssuer: true,
      loggingLevel: 'debug',
      loggingNoPII: false,
    });
  }

  async validate(payload: any) {
    // 可根据payload做自定义校验,如角色、权限检查
    return { userId: payload.oid, email: payload.email };
  }
}

export const AzureGuard = AuthGuard('azure-ad');

3. 确认前端令牌请求范围

前端登录Azure AD时,需请求后端应用的API权限范围(例如api://<backend-client-id>/access_as_user)。若范围错误,令牌的aud字段会指向其他资源,导致验证失败。

4. 验证令牌颁发者一致性

检查令牌的iss字段是否为https://login.microsoftonline.com/<tenantID>/v2.0,确保配置中的tenantID与Azure AD租户ID完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:30:57