3
votes

I was tried to create azure key vault through in the specified subscription. Followed this article,

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

So I write the code in a console application and my code,

   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
                        {
                        }
                    }
                }
            }
        }

But when run the console application , get the error

"The remote server returned an error: (403) Forbidden."

How to solve this issue?

1
Have you given the proper permissions to the application that you are getting the access token with? The API returns a 403 when authorization fails, so maybe you haven't assigned a role for the application in the Access Control (IAM) area at the subscription/resource group level?juunas
how to assigned a role for the application in the subscription/resource group level?Jinesh
You would go to e.g. your subscription -> Access Control (IAM) -> Add. Then find the application you registered in Azure AD by its name. It'll need at least Contributor role to create resources.juunas
You can also give the role to a single resource group so it can only do things there.juunas
Done, but get same error. is need to use any user informations in api call ?Jinesh

1 Answers

2
votes

"The remote server returned an error: (403) Forbidden."

The error message means you have not permission to add resource to azure.

I test and reproduce your problem in my site. After I Add permission in Subscriptions to user or the application which I has registered in Azure AD, I could create key vault correctly.

enter image description here

Also, you could get more details about how to registry AD App and assign role to application, please refer to document. After that we can get tenantId, appId, secretKey from the Azure Portal. Then we can use Microsoft.IdentityModel.Clients.ActiveDirectory SDK to get token for api authentication.

The way how to generate Bearer Token you could refer to the following code.

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