Created
July 10, 2015 02:15
-
-
Save sedouard/79d9813bfae0ed1e56cf to your computer and use it in GitHub Desktop.
Generates a SAS Token for Azure REST Api Calls (Particularly for Service Bus Services like Event Hub & Queues)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Code for generating of SAS token for authorization with Service Bus | |
/// | |
/// This handy function can be found on this helpful blog post: | |
/// http://developers.de/blogs/damir_dobric/archive/2013/10/17/how-to-create-shared-access-signature-for-service-bus.aspx | |
/// </summary> | |
/// <param name="resourceUri"></param> | |
/// <param name="keyName"></param> | |
/// <param name="key"></param> | |
/// <returns></returns> | |
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 + 3600); //EXPIRES in 1h | |
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); | |
return sasToken; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! Based on your code I've made similar function for Kotlin language.
https://gist.github.com/trzye/27cff4f6a785618f32e10ab6737bbd02