0
votes

I am trying to generate Shared Access signature for the Azure service bus queue. Here is the code snippnet through which I am generating SAS token.

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)
            {

            }
        }
    }
}

When I use this token in postman then sometime it gives

MalformedToken: Failed to parse simple web token. azure sevice Bus

and Now I am getting

401 40103: Invalid authorization token signature

From error, I know that I am doing something wrong with connection string but cannot figure out what. Can you please point me in right direction. Thanks

1
Instead of sharing the screenshot of the code, please paste the actual code.Gaurav Mantri

1 Answers

0
votes

Problems may locate at

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

The resourceUri is the full URI of the Service Bus resource to which access is claimed, in the format of sb://xxxservicequeue.servicebus.windows.net/ or with specific entity you need to operate like sb://xxxservicequeue.servicebus.windows.net/queueName.

The key should be the value of SharedAccessKeyKey and keyName is SAS policy name like the default RootManageSharedAccessKey.

Have a look at doc for more details.