question

LiveKim-9206 avatar image
0 Votes"
LiveKim-9206 asked SandervandeVelde42 edited

[iOS/Swift] generate sas token for Http Authorization to Azure IoT Hub

Please share Swift sample code to generate sas token for Http Authorization to Azure IoT Hub.

azure-iot-hub
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I hope you don't mind me suggesting this, but could you check out this page and add some more details to your question. What have you tried to resolve your issue? Thanks!


0 Votes 0 ·

1 Answer

SandervandeVelde42 avatar image
0 Votes"
SandervandeVelde42 answered SandervandeVelde42 edited

Hello @LiveKim-9206 ,

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;
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.