Share via

Web application w/ AD authentication accessing IoT Hub API: working example?

Markus Tacker 1 Reputation point
2019-12-05T13:40:12.91+00:00

I am trying to build a web application that allows users to

  1. Log-in with an AD account
  2. Interact with the IoT Hub API in order e.g. to list all devices

I ran into multiple problems:

I am looking for a working web application sample and would greatly appreciate any pointers.

Microsoft Security | Microsoft Entra | Microsoft Entra ID
0 comments No comments

2 answers

Sort by: Most helpful
  1. Sander van de Velde | MVP 37,066 Reputation points MVP
    2020-07-19T22:32:54.45+00:00

    If you make use of the IoT Hub Rest API, take a look at https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#security-tokens where the creation of a security token is shown.

    There is an example shown in javascript.

    With that token, you could do something like:

       using var client = new HttpClient();  
          
       client.DefaultRequestHeaders.Add("Authorization", token);  
          
       var body = "[some json structure]";  
         
       var stringContent = new StringContent(body, Encoding.UTF8, "application/json");  
          
       var restUriPost = $"https://{iotHubName}/[some method]";  
          
       using var resultPost = client.PostAsync(restUriPost, [stringContent of body]).Result;  
          
       return resultPost.StatusCode.ToString();  
    

    This works in any programming language which is capable to some basic security stuff and HTTPS calls.

    Due to the usage of an IoT hub connection string, please do not distribute that connection string to devices, just use it in cloud resources using a key vault.

    Was this answer helpful?

    0 comments No comments

  2. Marilee Turscak-MSFT 37,396 Reputation points Microsoft Employee Moderator
    2019-12-11T01:25:06.857+00:00

    There seem to be some C# examples here. https://github.com/Azure/azure-iot-sdk-csharp

    I don't think the authentication piece would be drastically different from authentication on any other web app in Azure but I am looking into this to confirm.

    For a regular web app you would use a sample like this one. https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect

    Was this answer helpful?

    0 comments No comments

Your answer

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