How can I get a user bearer token for the list of users I have in my IoT Central App?

Augusto Piva 15 Reputation points
2023-08-07T13:01:53.8+00:00

Hi,

I'm new on IoT Central and I'm digging into "Authenticate and authorize IoT Central REST API calls" (https://learn.microsoft.com/en-us/azure/iot-central/core/howto-authorize-rest-api)

To give you more context, this is what I'm working on:

I'm going to use IoT Central from a completely customized mobile app, by making usage of the REST API that Central IoT exposes.

This app would have users, which I'm thinking to use those users you have in the Azure IoT Central Permissions / User section. The purpose of using these users, is because I want to use all the built-in permissions it have for the device access control and so on...

Those users would have to log in by using the mobile app login screen.

Having said all that, what I'd do when user logs in is to authenticate that user with Azure IoT Central app, and so the subsequent REST API calls would be made by using that user's token.

The key here is that I'm not understanding how you authenticate those users programatically, so that getting that token which I think it's the so called Azure Active Directory Bearer token (AAD Bearer Token)

I've already read about tokens (https://learn.microsoft.com/en-us/azure/iot-central/core/howto-authorize-rest-api#token-types), but I didn't understand how can I get it outside the Azure CLI as it shows there, as I won't be using the CLI.

The REST API documentation and sample only shows how to get an API TOKEN via the HTTP endpoint (PUT https://{your app subdomain}.azureiotcentral.com/api/apiToken/operator-token?api-version=2022-07-31), but that token doesn't tell you to which user it belong. Is only Role related.

Just in the answers bear in mind that I need to take this token from a logic app flow (after the user enters the credentials in the mobile app login screen, this would hit a logic app endpoint).

FYI at this time, I'll following this tutorial which I found while I was creating the question (https://www.mikaelsand.se/2023/01/getting-a-bearer-token-from-aad-using-logic-apps/)

Any thought on this approach and how can I get that token would be really appreciated.

Thank you all,

Augusto

Azure IoT Central
Azure IoT Central
An Azure hosted internet of things (IoT) application platform.
344 questions
{count} votes

2 answers

Sort by: Most helpful
  1. LeelaRajeshSayana-MSFT 13,466 Reputation points
    2023-08-07T22:59:35.9266667+00:00

    Hi @Augusto Piva Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.

    There are different ways you can get the token through the code. Please find the below few options through which you can achieve them

    Approach 1: Through C# code invoking Azure CLI command.

    using System.Diagnostics;
    using System;
    
    namespace AccessToken // Note: actual namespace depends on the project name.
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
                string resource = "https://apps.azureiotcentral.com";
                string command = $"az account get-access-token --resource {resource}";
    
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {command}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false
                };
    
                Process process = new Process
                {
                    StartInfo = startInfo
                };
    
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
    
                string token = output.TrimEnd();
    
                Console.WriteLine(token);
    
           }
       }
    }
    

    The above code needs the Azure CLI to be installed on the machine where your application is hosted, and it will utilize the user credentials logged into the Azure CLI command line to fetch the credentials.

    Approach 2: Use Azure Active Directory Client ID and Client Secret authentication to get the bearer token.

    For this approach to work, you would need to do the following to get the client ID and clinet secret details for the code Create an Azure AD Application:

    • Go to the Azure portal.
    • Navigate to your Azure Active Directory.
    • Click on "App registrations" in the left-hand menu.
    • Click on the "+ New registration" button.
    • Fill in the necessary information for your application.

    Generate a Client Secret:

    • After creating the application, go to the "Certificates & secrets" section.
    • Under the "Client secrets" section, click on "+ New client secret."
    • Enter a description for the secret and choose an expiration period.
    • Click the "Add" button.

    Copy the Client Secret:

    • After you've added the client secret, a new secret value will be generated. Copy this value immediately, as you won't be able to see it again.
    • Replace the placeholder in your code with the actual client secret you generated.

    Copy the Client ID:

    • After creating the application, you will see a page with your application's details.
    • The "Application (client) ID" listed on this page is the Client ID you need for your code.
    • Copy the Client ID and use it in your code.

    Please find the code below to use this approach.

    using System;
    using Microsoft.Azure.Management.ResourceManager.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
    using Microsoft.Identity.Client;
    
    namespace AccessToken // Note: actual namespace depends on the project name.
    {
        internal class Program
        {
            static async Task Main(string[] args)
            {
                string clientId = "<ClientID>";
                string clientSecret = "<ClinetSecret>";
                string tenantId = "<TenantID>";
                string subscriptionId = "<Subscription>";
                
    
                // Get an access token
                resource = "https://apps.azureiotcentral.com/.default";
                var app = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                    .Build();
    
                var result = await app.AcquireTokenForClient(new[] { resource }).ExecuteAsync();
    
                Console.WriteLine("Second approach result is "+result.AccessToken);
    
            }
        }
    }
    
    

    Please also make sure to provide Tenant ID which can be obtained from Azure Active Directory and your Subscription ID details.

    Approach 3: Getting Access token through Python code

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.resource import ResourceManagementClient
    
    credential = DefaultAzureCredential()
    subscription_id = "<SubscriptionID>"
    
    resource_client = ResourceManagementClient(credential, subscription_id)
    
    access_token = credential.get_token("https://apps.azureiotcentral.com").token
    
    print('Access token is '+access_token)
    
    

    The Python code would just need the subscription ID. You can look into the .Net SDK and perhaps find a similar implementation in C#.

    Hope this helps. Please let me us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    0 comments No comments

  2. Bruce (SqlWork.com) 56,526 Reputation points
    2023-08-11T20:31:33.5966667+00:00

    To authenticate azure ad users with mobile apps you use the msal library. There is a library for android, iOS and web apps.

    https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-overview

    0 comments No comments