问题
We try to use Azure Resources Management API to create a Hybrid Connection. (https://docs.microsoft.com/en-us/rest/api/relay/hybridconnections.)
The problem we have is that every time we submit HTTP request it returns us 401 error with message:
{ "error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication failed. The 'Authorization' header is provided in an invalid format."}}
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;
}
}
}
回答1:
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;
}
So if you replace GetSASToken in sample above with this method, then it works.
来源:https://stackoverflow.com/questions/48121847/azure-resources-management-api-authorization-issue-when-creating-service-bus-hy