401 unauthorized Azure management api

戏子无情 提交于 2021-02-08 10:21:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!