ASP.NET Core 9 AKS应用调用Azure Entra下游API令牌获取失败
AKS上ASP.NET Core 9 Web API调用Entra保护下游API的令牌获取问题
在Azure Kubernetes Service(AKS)运行的ASP.NET Core 9 Web API应用中,使用Microsoft.Identity.Web包的AddDownstreamApi结合托管身份调用Azure Entra保护的下游API时,无法获取令牌,托管身份端点返回“HttpStatusCode: NotFound”错误。
错误信息
ExceptionHandlerOptions上配置的异常处理程序返回了404状态响应。抛出包含原始异常的InvalidOperationException,这通常是由于ExceptionHandlingPath配置错误导致的。如果预期异常处理程序返回404状态响应,请将AllowStatusCode404Response设置为true。IDW10109: 无法加载凭据。当传递给配置的证书过期或无法加载,且代码未在Azure环境中运行以使用托管身份、Pod Identity等时,可能会发生这种情况。详细信息:(Parameter 'clientCredentials')
现有代码与配置
Program.cs
builder .AddConfiguration(applicationName); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() .AddDownstreamApi("SecureApi", builder.Configuration.GetSection("SecureApi")) .AddInMemoryTokenCaches(); var app = builder.Build(); app.UseServices(); await app.Initialize(); app.Run();
appsettings.json
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "ClientId": "调用方应用的托管身份Client Id", "TenantId": "我的租户Id", "ClientCredentials": [ { "SourceType": "SignedAssertionFromManagedIdentity", "ManagedIdentityClientId": "调用方应用的托管身份Client Id" } ] }, "SecureApi": { "BaseUrl": "基础地址", "Scopes": [ "api://受保护API的Client Id/.default" ] } }
控制器代码
[HttpGet] [Route("CallSecureAPI")] public async Task<IActionResult> CallSecureAPI() { var response = await _downstreamApi.CallApiForAppAsync("SecureApi", options => { options.RelativePath = "Controller/Get"; options.HttpMethod = HttpMethod.Get.ToString(); }); return Ok(response); }
环境信息
- 使用的Microsoft.Identity.Web版本:4.72.1
- 场景:受保护的Web API调用下游Web API
验证结果
使用以下代码直接调用DefaultAzureCredential可以正常生成令牌并成功调用API,说明Azure Entra和托管身份配置本身无问题:
var _httpClient = new HttpClient(); var _apiScope = "api://受保护API的Client Id/.default"; var _apiUrl = "API地址"; var credential = new DefaultAzureCredential(); var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { _apiScope })); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); var response = await _httpClient.GetAsync(_apiUrl);
内容的提问来源于stack exchange,提问作者farid salehi
相关产品推荐
相关产品推荐

