Skip to content

Instantly share code, notes, and snippets.

@itsff
Forked from sedouard/SAStoken.cs
Created July 12, 2017 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsff/84f8db7d9eeb3cf892f9bcde88a8b4ea to your computer and use it in GitHub Desktop.
Save itsff/84f8db7d9eeb3cf892f9bcde88a8b4ea 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment