创建Azure Key Vault C#错误远程服务器返回错误:(403)禁止

时间:2018-07-25 14:53:06

标签: azure azure-keyvault

试图在指定的订阅中创建一个Azure密钥库。  关注了这篇文章

https://docs.microsoft.com/en-us/rest/api/keyvault/keyvaultpreview/vaults/createorupdate#examples

所以我在控制台应用程序中编写代码, 我的代码,

   var URI = "https://management.azure.com/subscriptions/00000000000000000000000000/resourceGroups/0000000/providers/Microsoft.KeyVault/vaults/KeyValutADj?api-version=2018-02-14-preview";
        Uri uri = new Uri(String.Format(URI));
        var token = await AuthHelper.KeyVaultAuthenticationAsync();
        // Create the request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "PUT";
        HttpWebResponse httpResponse = null;
        string body = "{\"location\": \"centralus\",\"properties\": {\"tenantId\": \"00000000.onmicrosoft.com\",\"sku\": {\"family\": \"A\",\"name\": \"standard\"},\"accessPolicies\": [{\"tenantId\": \"0000000000.onmicrosoft.com\",\"objectId\": \"0000000000000000000000000000000\",\"permissions\": {\"keys\": [\"encrypt\",\"decrypt\",\"wrapKey\",\"unwrapKey\",\"sign\",\"verify\",\"get\",\"list\",\"create\",\"update\",\"import\",\"delete\",\"backup\",\"restore\",\"recover\",\"purge\"],\"secrets\": [ \"get\",\"list\",\"set\",\"delete\",\"backup\",\"restore\",\"recover\",\"purge\"],\"certificates\": [\"get\",\"list\",\"delete\",\"create\",\"import\",\"update\",\"managecontacts\",\"getissuers\",\"listissuers\",\"setissuers\",\"deleteissuers\",\"manageissuers\",\"recover\",\"purge\"] }}],\"enabledForDeployment\": true,\"enabledForDiskEncryption\": true,\"enabledForTemplateDeployment\": true}}";


        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
                client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");


                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                using (var stream = new MemoryStream())
                using (var writer = new StreamWriter(stream))
                {

                    writer.Write(body);
                    writer.Flush();
                    stream.Flush();
                    stream.Position = 0;

                    using (var content = new StreamContent(stream))
                    {            

                        content.Headers.Add("Content-Type", "application/json");
                        var response = await client.PutAsJsonAsync(URI, content);
                        if (response.IsSuccessStatusCode)
                        {
                        }
                        else
                        {
                        }
                    }
                }
            }
        }

但是在运行控制台应用程序时,出现错误

“远程服务器返回错误:(403)禁止。”

如何解决此问题?

1 个答案:

答案 0 :(得分:3)

  

“远程服务器返回错误:(403)禁止。”

该错误消息表示您无权向Azure中添加资源。

我在我的网站上测试并重现了您的问题。在Subscriptions中向已在Azure AD中注册的用户或应用程序添加权限后,可以正确创建密钥库。

enter image description here

此外,您可以获得有关如何注册AD App以及为应用程序分配角色的更多详细信息,请参阅document。之后,我们可以从Azure门户获取tenantId, appId, secretKey。然后,我们可以使用Microsoft.IdentityModel.Clients.ActiveDirectory SDK来获取用于api身份验证的令牌。

如何生成Bearer Token的方式可以参考以下代码。

var appId = "0000000000000000000000000000000";
var secretKey = "******************************************";
var tenantId = "0000000000000000000000000000000";
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
ClientCredential clientCredential = new ClientCredential(appId, secretKey);
var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;
var accessToken = tokenResponse.AccessToken;
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    var baseUrl = new Uri($"https://management.azure.com/");
    var requestURl = baseUrl +"subscriptions/b83c1ed3-c5b6-44fb-b5ba-2b83a074c23f/resourceGroups/joeyWebApp/providers/Microsoft.KeyVault/vaults/joeykeyvault5?api-version=2018-02-14-preview";
    string body = "{\"location\": \"centralus\",\"properties\": {\"tenantId\": \"0000000000000000000000000000000\",\"sku\": {\"family\": \"A\",\"name\": \"standard\"},\"accessPolicies\": [{\"tenantId\": \"0000000000000000000000000000000\",\"objectId\": \"0000000000000000000000000000000\",\"permissions\": {\"keys\": [\"encrypt\",\"decrypt\",\"wrapKey\",\"unwrapKey\",\"sign\",\"verify\",\"get\",\"list\",\"create\",\"update\",\"import\",\"delete\",\"backup\",\"restore\",\"recover\",\"purge\"],\"secrets\": [ \"get\",\"list\",\"set\",\"delete\",\"backup\",\"restore\",\"recover\",\"purge\"],\"certificates\": [\"get\",\"list\",\"delete\",\"create\",\"import\",\"update\",\"managecontacts\",\"getissuers\",\"listissuers\",\"setissuers\",\"deleteissuers\",\"manageissuers\",\"recover\",\"purge\"] }}],\"enabledForDeployment\": true,\"enabledForDiskEncryption\": true,\"enabledForTemplateDeployment\": true}}";
    var stringContent = new StringContent(body, Encoding.UTF8, "application/json");
    var response = client.PutAsync(requestURl, stringContent).Result;
}

enter image description here