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

Azure客户端凭证流令牌签名无效问题排查求助

解决Azure客户端凭证流调用API返回401(签名无效)问题

问题背景

已在Azure中注册MyApi和MyClient两个应用,通过客户端凭证流获取令牌后调用REST API,始终返回401 Unauthorized - Bearer error="invalid_token" error_description="The signature is invalid"。

当前配置信息

MyApi应用

  • Client ID:client_id_MyApi
  • Tenant ID:tenant_id
  • Application ID URI:api://MyApi
  • API权限:Microsoft.Graph -> User.Read
  • 公开API:范围api://MyApi/accessAsUser;应用角色accessAsApplication

MyClient应用

  • Client ID:client_id_MyClient
  • Tenant ID:tenant_id
  • API权限:Microsoft.Graph -> User.Read,MyApi -> accessAsApplication

REST API服务器配置

Program.cs片段:

builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
    o.Audience = client id of MyClient;
    o.Authority = "https://login.microsoftonline.com/tenenat_id/";
    o.IncludeErrorDetails = true;
});

FooController.cs片段:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("Foo")]
[HttpPost]
public async Task Foo()
{
    await Task.Delay(1000);
    Console.WriteLine("!!!!!!!!!!!!!!!");
}

令牌获取请求

请求地址:https://login.microsoftonline.com/tenant_id/oauth2/v2.0/token
POST请求体:grant_type=client_credentials&client_id=client_id_MyClient&client_secret=mysecret&scope=https://graph.microsoft.com/.default

错误原因分析

  1. 令牌受众不匹配:获取令牌时使用了Microsoft Graph的scope,导致令牌的aud(受众)字段为Graph API的标识,而非目标MyApi的标识,API验证时会判定令牌无效。
  2. API验证配置错误:JwtBearer的Audience设置为MyClient的Client ID,而非MyApi的Application ID URI;同时Authority中的租户ID拼写错误(tenenat_id应为tenant_id)。
  3. 权限验证(潜在):若MyClient的MyApi应用权限未完成管理员同意,也可能导致令牌权限不足,但当前报错为签名无效,优先解决前两点。

修正步骤

  1. 修正令牌获取的scope参数
    将POST请求体中的scope改为api://MyApi/.default,确保返回的令牌受众匹配MyApi:

    grant_type=client_credentials&client_id=client_id_MyClient&client_secret=mysecret&scope=api://MyApi/.default
    
  2. 修正API的JwtBearer配置
    更新Program.cs中的验证配置,指定正确的受众和权限颁发机构:

    builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Audience = "api://MyApi"; // 替换为MyApi的Application ID URI
        o.Authority = "https://login.microsoftonline.com/tenant_id/"; // 修正租户ID拼写
        o.IncludeErrorDetails = true;
    });
    
  3. 确认权限的管理员同意
    登录Azure门户,进入MyClient应用的API权限页面,确保accessAsApplication权限已点击授予管理员同意(客户端凭证流需要应用权限的管理员同意才能生效)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:43:15