Azure资源管理API.创建服务总线混合连接时的授权问题 [英] Azure Resources Management API. Authorization issue when creating Service Bus Hybrid Connection

查看:84
本文介绍了Azure资源管理API.创建服务总线混合连接时的授权问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们尝试使用Azure资源管理API创建混合连接.( https://docs.microsoft.com/en-us/rest/api/relay/hybridconnections .)

We try to use Azure Resources Management API to create a Hybrid Connection. (https://docs.microsoft.com/en-us/rest/api/relay/hybridconnections.)

我们遇到的问题是,每次我们提交HTTP请求时,它都会向我们返回401错误并显示以下消息:

The problem we have is that every time we submit HTTP request it returns us 401 error with message:

{错误":{代码":"AuthenticationFailedInvalidHeader",消息":身份验证失败的.在无效的位置提供了授权"标头格式.}}

{ "error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication failed. The 'Authorization' header is provided in an invalid format."}}

我们更喜欢使用REST API,而不是SDK/掘金包

We prefer to use REST API rather than SDK/nugget packages

这是控制台应用程序代码:

Here is console app code:

using System;
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace HybridConnectionManagement
{
    class Program
    {
        public const string RelayAddress = "https://[namespace].servicebus.windows.net/";
        private static string RelaySasKeyName = "RootManageSharedAccessKey";
        private static string RelaySasKey = "[RootManageSharedAccessKey_Primary_Key]";

        static void Main(string[] args)
        {
            var createHybridConnectionEndpoint = "https://management.azure.com" +
                           "/subscriptions/[subscription_id]" +
                           "/resourceGroups/[resourceGroup]" +
                           "/providers/Microsoft.Relay" +
                           "/namespaces/[namespace]" +
                           "/hybridConnections/test-521?api-version=2017-04-1";


            var token = GetSASToken(RelayAddress, RelaySasKeyName, RelaySasKey);

            using (var httpClient = new HttpClient())
            {

                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                var response = httpClient.GetAsync(createHybridConnectionEndpoint).Result;
                var responseText = response.Content.ReadAsStringAsync().Result;

                //responseText is always: 
                //{ "error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication failed. 
                //The 'Authorization' header is provided in an invalid format."}}
                Console.WriteLine(responseText);
            }
        }

        public static string GetSASToken(string resourceUri, string keyName, string key)
        {
            var sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600); //EXPIRES in 1h 
            string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
            var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            var sasToken = String.Format(CultureInfo.InvariantCulture,
                "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

            return sasToken;
        }
    }
}

推荐答案

我对各种身份验证API感到困惑.对于这种情况,我不必使用SAS令牌.我需要使用的是Authorization Bearer令牌.这是获取它的方法:

I was confused with different kinds of Authentication API. For this case I didn't have to use SAS token. What I needed to use is Authorization Bearer token. Here is methods that acquires it:

        private string AcquireToken()
        {
            var credentials = new UserPasswordCredential(UserName, Password);
            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + DirectoryName);
            var result = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", AdClientId, credentials).GetAwaiter().GetResult();
            return result.AccessToken;
        }

因此,如果您使用此方法替换上面示例中的GetSASToken,那么它将起作用.

So if you replace GetSASToken in sample above with this method, then it works.

这篇关于Azure资源管理API.创建服务总线混合连接时的授权问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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