我正在尝试验证我是否可以使用 Azure 共享访问策略主键手动滚动 SAS 并发布到服务总线主题。但我总是得到一个 401。四处搜索,下面的代码看起来是正确且常见的地方来实现这一点。我错过了一些基本的东西吗?我是否使用了错误的密钥(即来自门户管理员的共享访问策略主密钥)?(注意我故意使用 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);