简体   繁体   中英

How to generate Shared Access Signature Token in C#

For Create Registration on azure notification hub We want authorization token for below rest api

https://{namespace}.servicebus.windows.net/{NotificationHub}/registrations/?api-version=2015-01

please see follwing link
https://msdn.microsoft.com/en-us/library/azure/dn223265.aspx

// Add Nuget package

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;
        }

Trying to follow Direct Send ( https://msdn.microsoft.com/en-us/library/mt608572.aspx ) I faced the same problem.

I was able to use @Sama's solution just changing the "Registrations" to "messages". The Solution provided is working in .Net Core.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM