Azure Key Vault抛出CredentialUnavailableException的原因及解决咨询
.NET 6应用部署到客户Azure环境时Azure Key Vault认证失败问题
问题描述
我在Azure上部署了.NET 6应用并使用Azure Key Vault,该应用在个人Azure环境中运行正常,但部署到安全策略更严格的客户Azure环境时,启动阶段在事件日志中抛出如下错误:
Application: w3wp.exe CoreCLR Version: 6.0.922.41905 .NET Version: 6.0.9 Description: The process was terminated due to an unhandled exception. Exception Info: Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot - EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot - ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint. - Visual Studio Token provider cant be accessed at D:\DWASFiles\Sites\<APP SERVICE NAME\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json - Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot - Azure CLI not installed - Az.Account module >= 2.2.0 is not installed.
Program.cs中Azure Key Vault的配置代码:
if (String.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "Release")) { builder.Configuration.AddAzureKeyVault( new Uri("https://<KEY VAULT URI>/"), new DefaultAzureCredential()); // Auth can be added here, look at link above } else { builder.Configuration .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false, true) .AddEnvironmentVariables(); }
已在Azure应用服务的「配置|应用程序设置」中配置了ASPNETCORE_ENVIRONMENT变量。注释掉环境检查改用appsettings时应用运行正常,但无客户环境完整访问权限,无法自行排查配置问题。
解决步骤
1. 确认应用服务托管标识配置
- 要求客户检查应用服务是否启用了系统分配托管标识(个人环境可能默认启用,客户严格环境可能禁用)
- 确保该托管标识在Key Vault的「访问策略」中被授予
机密读取(或业务所需的最小权限)
2. 替换DefaultAzureCredential为ManagedIdentityCredential
修改Program.cs中的Key Vault配置,直接使用托管标识凭据,避免尝试其他无关认证方式:
if (String.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "Release")) { builder.Configuration.AddAzureKeyVault( new Uri("https://<KEY VAULT URI>/"), new ManagedIdentityCredential()); } // 其余代码保持不变
3. 排查网络访问限制
- 要求客户确认应用服务是否允许访问Azure实例元数据服务(IMDS)端点(
http://169.254.169.254) - 检查Key Vault的防火墙规则,确认是否允许应用服务所在的VNet/IP范围访问
4. 验证环境变量配置
- 确认
ASPNETCORE_ENVIRONMENT确实被设置为Release(客户环境可能存在配置覆盖问题) - 若使用用户分配托管标识,需添加环境变量
AZURE_CLIENT_ID(值为用户分配标识的客户端ID),并修改代码:
new ManagedIdentityCredential(clientId: Environment.GetEnvironmentVariable("AZURE_CLIENT_ID"))
内容的提问来源于stack exchange,提问作者Dermo909
相关产品推荐
相关产品推荐

