Reputation: 1120
I'm trying to verify that I can hand-roll a SAS using the an Azure Shared Access Policy Primary Key and post to a Service Bus topic. But I always get a 401. Searching around, the below code looks correct and common place to achieve this. Have I missed something fundamental? Am I using the wrong key (i.e. Shared Access Policy Primary Key from the portal admin)? (note I'm intentionally using RootManageSharedAccessKey to test this out)
var baseUrl = "https://<< NAMESPACE >>.servicebus.windows.net/";
var key = "<< SHARED ACCESS KEY >>";
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var week = 60 * 60 * 24 * 7;
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
string stringToSign = HttpUtility.UrlEncode(baseUrl) + "\n" + expiry;
HMACSHA256 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(baseUrl), HttpUtility.UrlEncode(signature), expiry, "RootManageSharedAccessKey");
var msg = new HttpRequestMessage()
{
RequestUri = new Uri(baseUrl + "things"),
Method = HttpMethod.Post
};
msg.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
msg.Headers.Add("Authorization", $"SharedAccessSignature sr={HttpUtility.UrlEncode(baseUrl)}&sig={sasToken}&se={expiry}&skn=things");
var client = new HttpClient();
var r = client.Send(msg);
Console.WriteLine(r.StatusCode);
Upvotes: 0
Views: 1049
Reputation: 7860
I strongly suspect that you're seeing the failure because of the trailing slash in your baseUrl
. The form is expected as: << NAMESPACE >>.servicebus.windows.net
and I don't believe that it is treated as a normalized URL when validated by the service - so the slash is meaningful. (ref)
The formatting of your signature looks correct, and seems to be using the snippet from the docs almost verbatim. For your actual application use, I'd recommend disposing the HMACSHA256
instance and ensuring that you treat the HttpClient
as a singleton.
In case it helps, the source for how the Service Bus SDK forms the SAS can be found here.
Upvotes: 1