Azure服务总线共享访问签名生成

时间:2019-01-21 14:01:45

标签: azure azure-servicebus-queues azure-servicebus-topics

我正在尝试为Azure服务总线队列生成共享访问签名。这是我用来生成SAS令牌的代码段。

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

namespace SASTokenGeneration
{
    class Program
    {
        static void Main(string[] args)
        {
            string resourceUri = "sb://xxxservicequeue.servicebus.windows.net/;SharedAccessKeyName=xxxservicequeue;SharedAccessKey=xxxxxx";
            string key = "token";
            string keyName = "xxxservicequeue";
            try
            {
                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(resourceUri) + "\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(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

            }
            catch (Exception ex)
            {

            }
        }
    }
}

当我在邮递员中使用此令牌时,有时它会给出

  

MalformedToken:无法解析简单的Web令牌。天蓝色服务巴士

现在我得到

  

401 40103:无效的授权令牌签名

从错误中我知道连接字符串做错了什么,但无法弄清楚是什么。能给我指出正确的方向吗? 谢谢

1 个答案:

答案 0 :(得分:0)

问题可能位于

string resourceUri = "sb://xxxservicequeue.servicebus.windows.net/;SharedAccessKeyName=xxxservicequeue;SharedAccessKey=xxxxxx";
string key = "token";
string keyName = "xxxservicequeue";

resourceUri是要求访问的服务总线资源的完整URI,格式为sb://xxxservicequeue.servicebus.windows.net/或使用特定实体,您需要像sb://xxxservicequeue.servicebus.windows.net/queueName一样进行操作。

密钥应为SharedAccessKeyKey的值,并且keyName是SAS策略名称,如默认的RootManageSharedAccessKey

有关更多详细信息,请查看doc