Skip to content

Instantly share code, notes, and snippets.

@sedouard
Created July 10, 2015 02:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sedouard/79d9813bfae0ed1e56cf to your computer and use it in GitHub Desktop.
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)
/// <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;
}
@trzye
Copy link

trzye commented Apr 11, 2018

Thank you! Based on your code I've made similar function for Kotlin language.

https://gist.github.com/trzye/27cff4f6a785618f32e10ab6737bbd02

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment