问题
I'm calling azure management api to get the list of instances in a Cloud Service.
The following code works when fiddler is active and constantly returns 401 unauthorized when it's not going through fiddler.
I'm unable to determine the reason. Without Fiddler, the token is correctly returned, therefore, I don't understand why I'm getting an unauthorized.
private HostedService GetCloudServiceProperties(string serviceName)
{
if (_client == null)
{
GetClient();
}
string serviceProperties = string.Format("https://management.core.windows.net/{0}/services/hostedservices/{1}?embed-detail=true", AzureSettings.SubscriptionId, serviceName);
var result = _client.GetStringAsync(serviceProperties).Result;
var serializer = new XmlSerializer(typeof(HostedService), "http://schemas.microsoft.com/windowsazure");
var returnValue = (HostedService)serializer.Deserialize(new StringReader(result));
return returnValue;
}
private void GetClient()
{
string authority = "https://login.microsoftonline.com/" + AzureSettings.TenantName;
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(AzureSettings.ClientId)
.WithClientSecret(AzureSettings.ClientSecret)
.WithAuthority(new Uri(authority))
.Build();
List<string> scopes = new List<string>()
{
"https://management.core.windows.net/.default"
};
var token = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
_client = new HttpClient();
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
_client.DefaultRequestHeaders.Add("x-ms-version", "2009-10-01");
}
回答1:
Short answer, but I feel like the solution is capitalizing bearer. Services usually expect 'Bearer ', so this might be the issue.
来源:https://stackoverflow.com/questions/60952124/401-unauthorized-azure-management-api