简体   繁体   中英

401 unauthorized Azure management api

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");
}

Short answer, but I feel like the solution is capitalizing bearer. Services usually expect 'Bearer ', so this might be the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM