如何在C#中生成共享访问签名令牌

时间:2017-05-17 12:34:21

标签: c# azure azure-notificationhub azure-servicebus-queues

用于在azure通知中心上创建注册 我们想要下面的休息api的授权令牌

的https:// {}命名空间.servicebus.windows.net / {NotificationHub} /注册/ API-版本= 2015-01

请参阅以下链接
https://msdn.microsoft.com/en-us/library/azure/dn223265.aspx

2 个答案:

答案 0 :(得分:1)

//添加Nuget包

Install-Package Microsoft.Azure.NotificationHubs

using Microsoft.Azure.NotificationHubs;//Add namespace


string accessTokenstring = GetAccessToken();

 private string GetAccessToken()
        {
            var hubName = "<Notification Hub>";
            string connectionString = "Endpoint=sb://<Notification Hub Namespace>.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=<Key>";
            var apiVersion = "?api-version=2015-01";
            string endpoint = null;
            string sasKeyValue = null;
            string sasKeyName = null;
            string targetUri = null;
            var parts = connectionString.Split(';');
            foreach (var part in parts)
            {
                if (part.IndexOf("Endpoint") == 0)
                {
                    endpoint = "https" + part.Substring(11);
                }
                else if (part.IndexOf("SharedAccessKeyName") == 0)
                {
                    sasKeyName = part.Substring(20);
                }
                else if (part.IndexOf("SharedAccessKey") == 0)
                {
                    sasKeyValue = part.Substring(16);
                }
            }
            targetUri = endpoint + hubName;
            var registrationPath = targetUri + "/Registrations/";
            var resourceUri = registrationPath + apiVersion;
            TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
            string accessTokenstring = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(sasKeyName, sasKeyValue, resourceUri, sinceEpoch);
            return accessTokenstring;
        }

答案 1 :(得分:0)

尝试关注直接发送(https://msdn.microsoft.com/en-us/library/mt608572.aspx)我遇到了同样的问题。

我能够使用@ Sama的解决方案,只需将“注册”更改为“消息”即可。提供的解决方案正在.Net Core中工作。