Search code examples
azureazure-servicebus-queuesazure-scheduler

send message to Azure service bus by Azure scheduler using post


i want to send message to Azure service bus by Azure scheduler using post like demo in this page http://www.prasadthinks.com/ but i don't know how to set 'authorization' property in Http Header.


Solution

  • As far as I know, the 'authorization' property must contains the service bus's access token.

    You could use your shared access policies's key-name and key to generate the access token by using codes.

    More details, you could refer to below codes.

          string keyName = "keyname";
    
                string key = "key";
    
                var sasToken = createToken("http://yourservicebusname.servicebus.windows.net/queuename", keyName, key);
    

    createToken function:

      private static string createToken(string resourceUri, string keyName, string key)
            {
                TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
                var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 7200); //EXPIRES in 2h 
                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)));
                 //this is the auth token
                var sasToken = String.Format(CultureInfo.InvariantCulture,
                "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                    HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
    
                return sasToken;
            }
    

    The result is like below:

    enter image description here

    This is the 'authorization' property, you could copy it.But this token has two hours limit.

    The azure scheduler job setting like below:

    enter image description here

    Besides, the azure scheduler job have already support send the message to the service bus, you don't need to create the sas token by yourself, you could just add the keyName and key in its authentication settings.

    More details, you could refer to below images:

    enter image description here