如何从IIS上托管的.net代码访问密钥库机密

时间:2018-08-27 17:41:24

标签: c# azure iis azure-keyvault

我有一个场景:

  1. 在Azure中使用机密创建密钥库。
  2. 在代码中访问此机密。

    1. 代码在本地运行(已使用Azure CLI测试)
    2. Azure App服务(启用MSI)中托管的应用程序运行正常。
    3. 我们需要在Azure VM(启用MSI)IIS服务器上托管相同的应用程序-无法正常工作

我想要以上几点(最后一点)的解决方案和建议

访问密钥库机密值的代码

     var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            ConfigurationApp.ClientId = keyVaultClient.GetSecretAsync("https://test.vault.azure.net/", "testid").Result.Value;

关注此文章- substring function documentation

https://kasunkodagoda.com/2018/04/28/allow-application-running-on-an-azure-virtual-machine-to-access-azure-key-vault-using-managed-service-identity/

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题:从Azure VM IIS上托管的.net代码访问密钥库机密

  public async Task getAppconfiguration2()
    {
        string URI = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net";
        Uri uri = new Uri(String.Format(URI));
        HttpClient _client = new HttpClient();
        _client.DefaultRequestHeaders.Add("Metadata", "true");
        HttpRequestMessage request = new HttpRequestMessage
        {
            // Content = new StringContent(body, Encoding.UTF8, "application/json"),
            Method = HttpMethod.Get,
            RequestUri = new Uri(URI)
        };


        var res = await _client.SendAsync(request);
        var content = res.Content.ReadAsStringAsync();
        JObject token = JsonConvert.DeserializeObject<JObject>(content.Result.ToString());
        string token1 = token["access_token"].ToString();
        ConfigurationApp.Encyptionkey = token1.ToString();

        HttpClient _client1 = new HttpClient();
        _client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token1);
        HttpRequestMessage request1 = new HttpRequestMessage
        {

            Method = HttpMethod.Get,
            RequestUri = new Uri("https://test.vault.azure.net/secrets/clientid?api-version=2016-10-01")
        };


        var rs = _client1.SendAsync(request1);
        var rk = rs.Result.Content.ReadAsStringAsync();
        JObject clientjson = JsonConvert.DeserializeObject<JObject>(rk.Result.ToString());
        ConfigurationApp.ClientId = clientjson["value"].ToString();

    }