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

Live Kim 6 Reputation points
2021-11-26T06:43:52.327+00:00

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

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,272 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sander van de Velde | MVP 36,761 Reputation points MVP Volunteer Moderator
    2021-11-26T12:12:15.927+00:00

    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;  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.