I am using Azure REST API for fetching Billing Usage and Ratecard details. To acquire Token using AcquireToken() Method, initially I used only Client Id which then asks for User Credentials in login window.
However, I am looking for Non-Interactive Approach, so I used Client Credentials in which I passed Client Id and Client Secret Key.
But it gives "Remote Server returns an error 401 Unauthorized"
When I look into error deeply, I found that it gives error "The access token is from wrong audience or resource"
Please give me any solution using which I can access the API without any user interaction.
Thanks in Advance.
Here is my code:
{
string token = GetOAuthTokenFromAAD();
string requestURL = String.Format("{0}/{1}/{2}/{3}",
ConfigurationManager.AppSettings["ARMBillingServiceURL"],
"subscriptions",
ConfigurationManager.AppSettings["SubscriptionID"],
"providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq 'MS-AZR-*****' and Currency eq 'INR' and Locale eq 'en-IN' and RegionInfo eq 'IN'");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(String.Format("RateCard service response status: {0}", response.StatusDescription));
}
public static string GetOAuthTokenFromAAD()
{
AuthenticationContext authenticationContext = new AuthenticationContext(string.Format("{0}/{1}",ConfigurationManager.AppSettings["ADALServiceURL"], ConfigurationManager.AppSettings["TenantDomain"]));
AuthenticationResult result = null;
ClientCredential uc = new ClientCredential(Client_Id, Secret_Key);
try
{
result = authenticationContext.AcquireToken("https://management.core.windows.net/", uc);
}
return result.AccessToken;
}
//App Config File
<add key="ADALServiceURL" value="https://login.microsoftonline.com" />
<add key="ADALRedirectURL" value="http://*****-authentication.cloudapp.net" />
<add key="ARMBillingServiceURL" value="https://management.core.windows.net" />
<add key="TenantDomain" value="********.onmicrosoft.com" />
<add key="SubscriptionID" value="*******-****-****-****-********" />
<add key="ClientId" value="*******-****-****-****-********" />
System.IdentityModel.Tokens.JwtSecurityToken securityToken = new System.IdentityModel.Tokens.JwtSecurityToken(token);
and then check theAudiences
property in the securityToken. Please see the screenshot: i.stack.imgur.com/j4RWS.png – Gaurav Mantri