I am trying to get token from using Azure Resource Manager API but getting 401-Unauthorized in response.I have my code as below :
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", client_Id, client_secret))));
var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = client.PostAsync("https://login.windows.net/subscriptionId/oauth2/token", content);
I dont fully understand your code but i know how to construct ARM API calls so i can help you out with the core facts. What jumps out at me is the fact that your POST URL looks wrong:
you should be using https://login.microsoftonline.com/ - check out the following blogpost Simplifying our Azure AD Authentication Flows
There needs to be the tenantID in your POST uri, not the subscriptionID. Access to subscriptions is managed through assigning RBAC Roles to the serivceprincipal created for the AzureAD App
Here is an example call. I use Postman to check if my constructed calls use the correct values and parameters:
Request
response:
According to your code, you could refer to the following code to retrieve your token:
Result:
For more details, you could refer to this blog about using the Azure ARM REST API – Get Access Token.