【问题标题】:Authentication to Azure Key Vault from an app service fails从应用服务到 Azure Key Vault 的身份验证失败
【发布时间】:2023-04-10 15:05:02
【问题描述】:

我正在尝试使用应用服务的系统分配标识从应用服务(Web API)向 Azure Key Vault 进行身份验证。在 Azure Key Vault 中,我创建了一个访问策略,允许应用服务访问密钥、机密和证书(稍后将限制这一点!)。

在应用服务中,我尝试获取身份验证令牌(请参阅代码 sn-p),但 GetAccessTokenAsync 给了我来自 Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider 的异常,消息如下所示。

搜索,我发现了很多关于这个错误的描述,但没有关于原因或解决方案的有用提示。

请注意,我使用服务主体对同一个密钥保管库进行身份验证没有问题,但使用托管身份的想法当然是避免将客户端 ID 和机密等凭据存储在任何地方

        var azureServiceTokenProvider = new AzureServiceTokenProvider();
        string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(VaultUrl);

        Client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

异常信息:

Parameters: Connection String: [No connection string specified], Resource: https://efipsexternals.vault.azure.net/, Authority: . Exception Message: Tried the following 4 methods to get an access token, but none of them worked.\r\nParameters: Connection String: [No connection string specified], Resource: https://<VAULTNAME>.vault.azure.net/, Authority: . Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {\"ExceptionMessage\":\"AADSTS500011: The resource principal named https://<VAULTNAME>.vault.azure.net/ was not found in the tenant named <TENANTID>. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\\r\\nTrace ID: 52674a60-5e9c-432c-b999-e13e326f2000\\r\\nCorrelation ID: b335c7b2-2f38-4cc0-9ec3-6662c7ee5546\\r\\nTimestamp: 2019-10-27 10:58:52Z\",\"ErrorCode\":\"invalid_resource\",\"ServiceErrorCodes\":[\"500011\"],\"StatusCode\":400,\"Message\":null,\"CorrelationId\":\"102c92f1-525a-44ee-a383-d7e40ccd2ed4\"}\r\nParameters: Connection String: [No connection string specified], Resource: https://<VAULTNAME>.vault.azure.net/, Authority: . Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at \"D:\\local\\LocalAppData\\.IdentityService\\AzureServiceAuth\\tokenprovider.json\"\r\nParameters: Connection String: [No connection string specified], Resource: https://<VAULTNAME>.vault.azure.net/, Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n\r\nParameters: Connection String: [No connection string specified], Resource: https://<VAULTNAME>.vault.azure.net/, Authority: https://login.microsoftonline.com/common. Exception Message: Tried to get token using Active Directory Integrated Authentication. Access token could not be acquired. Failed to get user name from the operating system.Inner Exception : The format of the specified domain name is invalid\r\n

【问题讨论】:

  • 根据我的测试,您可以删除string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(VaultUrl); is
  • @JackJia,你是绝对正确的。我可以建议您在答案中重复一遍,以便我接受吗?
  • 谢谢。添加了我的答案。

标签: azure-web-app-service azure-keyvault azure-managed-identity


【解决方案1】:

要为 azure key vault 获取具有托管标识的访问令牌,您只需:

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(VaultUrl); 代码在这里不是必需的,它应该是您问题的根本原因。您可能会将您的 keyvault url 作为参数传递给它,这在此处不合适。访问 keyvault API 的正确方法是:https://vault.azure.com/。如果你想使用这段代码,你可以这样做:

public static async Task<string> AuthenticationCallback(string authority, string resource, string scope)
{
    Console.WriteLine($"authority:{authority}, resource:{resource}, scope:{scope}");
    return new AzureServiceTokenProvider().GetAccessTokenAsync(resource).Result;
}

static void Main(string[] args)
{
    Console.ReadLine();

    string baseUrl = "your keyvault url, for example: https://jackkv.vault.azure.net/";
    KeyVaultClient kvc = new KeyVaultClient(AuthenticationCallback);
    SecretBundle secret = kvc.GetSecretAsync(baseUrl, "testSecret").Result;
    Console.WriteLine(secret.Value);

    Console.ReadLine();
}

【讨论】:

  • RE: "访问 keyvault API 的正确方法是:https://vault.azure.com";这个网址对我不起作用,但是,https://vault.azure.net 确实有效。
【解决方案2】:

GetAccessTokenAsync 方法需要像这里 https://vault.azure.com/ 这样的资源标识符。

// Instantiate a new KeyVaultClient object, with an access token to Key Vault
var azureServiceTokenProvider1 = new AzureServiceTokenProvider();
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider1.KeyVaultTokenCallback));

// Optional: Request an access token to Key Vault
var azureServiceTokenProvider2 = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider2.GetAccessTokenAsync("https://vault.azure.com/").ConfigureAwait(false);

当您收到Connection String: [No connection string specified] 错误时,请尝试以下方法进行故障排除。

1.在AzureServiceTokenProvider的connectionString参数中传递RunAs=App;。这样它就不会尝试不同的模式来获取token,而且异常稍微好一点。

2.安装/更新最新版Microsoft.Azure.Services.AppAuthentication

更多详情可以参考这个article

【讨论】:

  • GetAccessTokenAsync 有一个字符串资源标识符 VaultUrl。我有最新版本的 Microsoft.Azure.Services.AppAuthentication。重点在这里,token不是必须的,请看Jack Jia的评论。
  • 是的,如果您只想获取 keyvault 密码,您可以使用我提供的第一个代码。如果您想获取密钥保管库的访问令牌,您可以使用可选代码。
猜你喜欢
  • 2020-10-21
  • 2020-09-11
  • 1970-01-01
  • 2019-03-13
  • 2019-06-22
  • 1970-01-01
  • 2018-04-06
  • 2017-08-28
  • 1970-01-01
相关资源
最近更新 更多