[英]Why do I get a 401 using a Shared Access Signature with the Service Bus REST API
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.我正在尝试验证我是否可以使用 Azure 共享访问策略主键手动滚动 SAS 并发布到服务总线主题。 But I always get a 401. Searching around, the below code looks correct and common place to achieve this.
但我总是得到 401。四处搜索,下面的代码看起来是正确和常见的地方来实现这一点。 Have I missed something fundamental?
我错过了一些基本的东西吗? Am I using the wrong key (ie Shared Access Policy Primary Key from the portal admin)?
我是否使用了错误的密钥(即来自门户管理员的共享访问策略主密钥)? (note I'm intentionally using RootManageSharedAccessKey to test this out)
(注意我故意使用 RootManageSharedAccessKey 来测试这个)
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);
I strongly suspect that you're seeing the failure because of the trailing slash in your baseUrl
.我强烈怀疑您看到失败是因为
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.表单应为:
<< NAMESPACE >>.servicebus.windows.net
并且我不认为它在服务验证时被视为规范化的 URL - 所以斜杠是有意义的。 ( 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.对于您的实际应用程序使用,我建议您处理
HMACSHA256
实例并确保您将HttpClient
视为单例。
In case it helps, the source for how the Service Bus SDK forms the SAS can be found here .如果有帮助,可以在此处找到有关服务总线 SDK 如何形成 SAS 的来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.