Search code examples
azure-iot-central

I am trying to create a C# application to access Device IDs from IOTCentral. How can I authenticate the user of the application?


I am currently looking at these examples here but can't get the Example to work as it complains about some invalid format.

The Preview example works find but requires me to have logged in via the azure CLI. I need the users of the application to be able to log in to the application wherever it is to authenticate to IOTCentral.

What API is used to do that - the Azure examples seem to either not work or rely on the az CLI to handle the log in.

Error from Example System.ArgumentException: ''authority' should be in URI format. Arg_ParamName_Name'

PreviewExample

namespace PreviewExamples {
    internal class Program
    {        
        private static void Main(string[] args)
        {
            // Using 'az login' first, and using 'az account set -s subscription'
            var credential = new DefaultAzureCredential();

            var subdomain = "app-name";

            // Users example
            // UserRoleOrgsExample.Run(subdomain, credential);

            DeviceExample.Run(subdomain, credential);
        }
    }
}

Solution

  • Quick C# sample where you have the user log in through a browser popup:

    using var httpClient = new HttpClient();
    var cred = new InteractiveBrowserCredential();
    var token = await cred.GetTokenAsync(new TokenRequestContext(new[] {"https://apps.azureiotcentral.com/.default"}), CancellationToken.None);
    
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
    
    using var centralClient = new AzureIoTCentral(httpClient, true);
    centralClient.Subdomain = Constants.AppName;
    centralClient.ApiVersion = Constants.ApiVersion;
    
    var devices = await centralClient.Devices.ListAsync();
    

    Or if you want to use an API key, like Roman suggested:

    using var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("Authorization", $"SharedAccessSignature sr=stuffnotfortheinternet");
    
    using var centralClient = new AzureIoTCentral(httpClient, true);
    centralClient.Subdomain = Constants.AppName;
    centralClient.ApiVersion = Constants.ApiVersion;
    
    var devices = await centralClient.Devices.ListAsync();