Skip to content

Instantly share code, notes, and snippets.

@ridomin
Created April 5, 2022 02:28
Show Gist options
  • Save ridomin/03311a7bfa38c7ef4acfbe274a822b41 to your computer and use it in GitHub Desktop.
Save ridomin/03311a7bfa38c7ef4acfbe274a822b41 to your computer and use it in GitHub Desktop.
SasAuth.cs
namespace Rido.MqttCore
{
public class SasAuth
{
private const string apiversion_2020_09_30 = "2020-09-30";
public static string GetUserName(string hostName, string deviceId, string modelId = "") =>
$"{hostName}/{deviceId}/?api-version={apiversion_2020_09_30}&model-id={modelId}";
private static string Sign(string requestString, string key)
{
using (var algorithm = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(key)))
{
return Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(requestString)));
}
}
public static string CreateSasToken(string resource, string sasKey, int minutes)
{
var expiry = DateTimeOffset.UtcNow.AddMinutes(minutes).ToUnixTimeMilliseconds().ToString();
var sig = System.Net.WebUtility.UrlEncode(Sign($"{resource}\n{expiry}", sasKey));
return $"SharedAccessSignature sr={resource}&sig={sig}&se={expiry}";
}
public static (string username, string password) GenerateHubSasCredentials(string hostName, string deviceId, string sasKey, string modelId, int minutes = 60) =>
(GetUserName(hostName, deviceId, modelId), CreateSasToken($"{hostName}/devices/{deviceId}", sasKey, minutes));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment