401未经授权的Azure管理API [英] 401 unauthorized Azure management api

查看:84
本文介绍了401未经授权的Azure管理API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用azure管理api以获取Cloud Service中的实例列表.

I'm calling azure management api to get the list of instances in a Cloud Service.

以下代码在提琴手处于活动状态时起作用,并在未通过提琴手时不断返回未经授权的401.

The following code works when fiddler is active and constantly returns 401 unauthorized when it's not going through fiddler.

我无法确定原因.没有Fiddler,令牌将正确返回,因此,我不明白为什么会遭到未经授权的攻击.<​​/p>

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

推荐答案

简短的答案,但我觉得解决方案是将载体大写.服务通常期望"Bearer",所以这可能是问题所在.

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

这篇关于401未经授权的Azure管理API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆