/// <summary> /// Generate the SAS token /// </summary> /// <param name="resourceUri">Contains [hubname].azure-device.net/devices/[deviceid]</param> /// <param name="signingKey">Signing key from connection string</param> /// <param name="expiresInMinutes">Number of minutes before the generated SAS token expires</param> /// <returns></returns> private string GeneratePassword(string resourceUri, string signingKey, int expiresInMinutes) { resourceUri = WebUtility.UrlEncode(resourceUri); ExpiresAt = DateTime.UtcNow.AddMinutes(expiresInMinutes); TimeSpan secondsFromBaseTime = ExpiresAt.Subtract(EPOCH); string toSign = string.Format("{0}\n{1}", resourceUri, Math.Ceiling(secondsFromBaseTime.TotalSeconds)); string signed = ""; string result = ""; using (HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(signingKey))) { signed = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(toSign))); } signed = WebUtility.UrlEncode(signed); result = string.Format("sr={0}&sig={1}&se={2}", resourceUri, signed, Math.Ceiling(secondsFromBaseTime.TotalSeconds)); return(result); }
/// <summary> /// Returns true if the token is within 10 minutes of expiring. /// </summary> /// <returns></returns> public bool IsCloseToExpiry() { return(ExpiresAt.Subtract(DateTime.UtcNow).TotalMinutes < 10); }