Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,272 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Please share Swift sample code to generate sas token for Http Authorization to Azure IoT Hub.
Hello @Live Kim ,
it seems you want to access the Azure IoT Hub Rest API.
This is just based on HTTP calls where the security is done using a SAS key.
I do not have an iOS/Swift example, an example of this call using CURL is shown here.
A C# example looks like this:
using System;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
private static void Main(string[] args)
{
var jsonString = TestGetIdentity("[full iothub connection string]", "[device name]");
Console.WriteLine($"Press a key to exit for {jsonString}");
Console.ReadKey();
}
private static string TestGetIdentity(string cs, string deviceId)
{
var sas = ConstructToken(cs);
var fullIotHubName = cs.Split(';')[0].Substring(9); // "{shortIoTHubName}.azure-devices.net";
string shortIoTHubName = fullIotHubName.Split('.')[0];
var url = $"https://{shortIoTHubName}.azure-devices.net/devices/{deviceId}?api-version=2020-05-31-preview";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", sas);
var req = new HttpRequestMessage(HttpMethod.Get, url);
using var res = client.SendAsync(req).Result;
return res.Content.ReadAsStringAsync().Result;
}
private static string ConstructToken(string connectionStringIoTHub)
{
var fullIotHubName = connectionStringIoTHub.Split(';')[0].Split('=')[1];
var policyName = connectionStringIoTHub.Split(';')[1].Split('=')[1];
var key = connectionStringIoTHub.Split(';')[2].Replace("SharedAccessKey=", string.Empty);
int expiryInSeconds = 3600;
var fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);
var expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + expiryInSeconds);
var stringToSign = $"{WebUtility.UrlEncode(fullIotHubName)}\n{expiry}";
var hmac = new HMACSHA256(Convert.FromBase64String(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var token = $"SharedAccessSignature sr={WebUtility.UrlEncode(fullIotHubName)}&sig={WebUtility.UrlEncode(signature)}&se={expiry}&skn={policyName}";
return token;
}