Register An Azure AD Application Programmatically Using C#

Usually, Azure SDK for .NET should provide the APIs to register an Azure AD application programmatically in C#. But as of February 2019, the facility is only available using PowerShell and not using C#. The C# APIs are under consideration or development. Hence, we will follow an approach of running a PowerShell script in the C# application to achieve our goal.

Prerequisites
  • Visual Studio 2017 (I am using the 2017 version; we can also use a lower version).
  • PowerShell v5.0 or higher version.
  • Azure Admin account
We can check the PowerShell version by running the below command on PowerShell.
 
$PSVersionTable.PSVersion
 
There are 3 steps in this solution.
  • Create a C# application
  • Add NuGet packages to our project
  • Code to run PowerShell script in C#
Step 1 - Create a C# Application 
  1.  Open Visual Studio as Administrator.
  2.  Create a console app (.NET Framework).
  3.  Enter AppRegistration in the name section and click OK.
Register An Azure AD Application Programmatically Using C# 
 
Step 2 - Add NuGet packages to our project
 
Add a NuGet package called System.Management.Automation.dll created by the Microsoft Corporation. This package will allow us to run the PowerShell scripts from C# applications. 
 
Register An Azure AD Application Programmatically Using C# 
 
We also need to add the Newtonsoft.Json package created by James Newton-King which will allow us to convert PowerShell Objects into JSON Objects. We can not directly convert a PowerShell Object to C# Object; so we need to first convert it into JSON and then, we can convert it into C# Object.
 
Register An Azure AD Application Programmatically Using C# 
 
Step 3 - C# code to run PowerShell commands
 
Add the reference namespaces in the import section of your Program.cs file.
  1. using System.Management.Automation.Runspaces;  
  2. using System.Management.Automation;  
  3. using Newtonsoft.Json;  
In Main method, write the below code.
  1. string Username = “<User name of Azure account>”;  
  2. string Password = “<Password of Azure account>”;  
  3. string Appname = “<Name using which we want to register an Azure Application>”;  
  4. PowerShell powershell = PowerShell.Create();  
  5. Runspace runspace = RunspaceFactory.CreateRunspace();  
  6. runspace.Open();  
  7. powershell.Runspace = runspace;  
  8. powershell.AddScript("Install-Module -Name AzureADPreview -Force; \n");  
  9. powershell.AddScript("Import-Module -Name AzureADPreview -Verbose \n");  
  10. powershell.AddScript("$username = \""+Username +"\"; \n" +  
  11. "$password = convertTo-securestring '"+ Password + "' -AsPlainText -Force; \n" +  
  12. "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password; \n" +  
  13. "Connect-AzureAD -Credential $cred; \n" +  
  14. "New-AzureADApplication -DisplayName '"+Appname+"'  -ReplyUrls 'https://AppRegisterationDemo.contoso.com'  -PublicClient $true");  
  15. try  
  16. {  
  17.             var result = powershell.Invoke();  
  18.             if (powershell.Streams.Error.Count > 0)  
  19.             {  
  20.                         foreach (var err in powershell.Streams.Error.ToString())  
  21.                         {  
  22.                             Console.WriteLine(err);  
  23.                         }  
  24.                         return "0";  
  25.             }  
  26.         else  
  27.             {  
  28.                         Console.WriteLine(result);  
  29.                         int i = 0;  
  30.                         foreach (var outputItem in result)  
  31.                         {  
  32.                             if (outputItem != null)  
  33.                             {  
  34.                                        
  35.                                  Console.WriteLine(outputItem.BaseObject.GetType());  
  36.                                  var jsonData =   
  37.            JsonConvert.SerializeObject(outputItem.Properties.ToDictionary(k => k.Name, v => v.Value), new JsonSerializerSettings()  
  38.                                  {  
  39.                                               PreserveReferencesHandling =   
  40.                                               PreserveReferencesHandling.Objects,  
  41.                                               Formatting = Formatting.Indented  
  42.                                   });  
  43.                                   if (i == 1)  
  44.                                   {  
  45.                                         var deseialized = JsonConvert.DeserializeObject<MyInfo>(jsonData);  
  46.                                         appID = deseialized.AppId;  
  47.                                         ObjectId = deseialized.ObjectId;  
  48.                                         Console.WriteLine(appID);  
  49.                                    }  
  50.                                i++;  
  51.                           }  
  52.                 }  
  53. }  
  54. runspace.Close();  
  55. Console.WriteLine("App Created Successfully");  
  56. return "1";  
  57. }  
  58. catch (Exception ex)  
  59. {  
  60. return "0";  
  61. }  

We also need to add one class named MyInfo in which we will save the Object Id and Application Id.

  1. public class MyInfo  
  2. {  
  3.     public string AppId { get; set; }  
  4.     public string ObjectId { get; set; }  
  5. }  
After all these changes, our file will look like following. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Collections.ObjectModel;  
  6. using Newtonsoft.Json;  
  7. using System.Management.Automation.Runspaces;  
  8.   
  9. namespace AppRegistraion  
  10. {  
  11.     public class MyInfo  
  12.         {  
  13.             public string AppId { getset; }  
  14.             public string ObjectId { getset; }  
  15.         }  
  16.     class Program  
  17.         {  
  18.             public string appID = "";  
  19.             public string ObjectId = "";  
  20.             static void Main(string[] args)  
  21.             {  
  22.                 string Username = “<User name of Azure account>”;    
  23.         string Password = “<Password of Azure account>”;    
  24.         string Appname = “<Name using which we want to register an Azure Application>”;    
  25.         PowerShell powershell = PowerShell.Create();    
  26.         Runspace runspace = RunspaceFactory.CreateRunspace();    
  27.         runspace.Open();    
  28.         powershell.Runspace = runspace;    
  29.         powershell.AddScript("Install-Module -Name AzureADPreview -Force; \n");    
  30.         powershell.AddScript("Import-Module -Name AzureADPreview -Verbose \n");    
  31.         powershell.AddScript("$username = \""+Username +"\"; \n" +    
  32.         "$password = convertTo-securestring '"+ Password + "' -AsPlainText -Force; \n" +    
  33.         "$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password; \n" +    
  34.         "Connect-AzureAD -Credential $cred; \n" +    
  35.         "New-AzureADApplication -DisplayName '"+Appname+"'  -ReplyUrls 'https://AppRegisterationDemo.contoso.com'  -PublicClient $true");    
  36.         try    
  37.         {    
  38.             var result = powershell.Invoke();    
  39.             if (powershell.Streams.Error.Count > 0)    
  40.             {    
  41.                 foreach (var err in powershell.Streams.Error.ToString())    
  42.                 {    
  43.                     Console.WriteLine(err);    
  44.                 }    
  45.                 return "0";    
  46.             }    
  47.             else    
  48.             {    
  49.                 Console.WriteLine(result);    
  50.             int i = 0;    
  51.             foreach (var outputItem in result)    
  52.             {    
  53.                 if (outputItem != null)    
  54.                 {               
  55.                     Console.WriteLine(outputItem.BaseObject.GetType());    
  56.                 var jsonData = JsonConvert.SerializeObject(outputItem.Properties.ToDictionary(k => k.Name, v => v.Value), new JsonSerializerSettings()    
  57.                 {    
  58.                     PreserveReferencesHandling =  PreserveReferencesHandling.Objects,    
  59.                     Formatting = Formatting.Indented    
  60.                 });    
  61.                 if (i == 1)    
  62.                 {    
  63.                     var deseialized = JsonConvert.DeserializeObject<MyInfo>(jsonData);    
  64.                     appID = deseialized.AppId;    
  65.                     ObjectId = deseialized.ObjectId;    
  66.                     Console.WriteLine(appID);    
  67.                 }    
  68.                 i++;    
  69.                 }    
  70.             }    
  71.         }    
  72.         runspace.Close();    
  73.         Console.WriteLine("App Created Successfully");    
  74.         return "1";    
  75.         }    
  76.         catch (Exception ex)    
  77.         {    
  78.             return "0";    
  79.         }  
  80.       }  
  81. }  
Code Explanation
  • In the above code, first, we are creating PowerShell object and a runspace in which the PowerShell script will run.
  • In this runspace, we are adding scripts using the Addscript() method.
  • In PowerShell scripts, we are first installing AzureADPreview module and importing it to our runspace. Then, we are connecting to Azure AD using Connect-AzureAD command. 
  • Using New-AzureADApplication command, we are creating an Azure AD application.
  • Now, we have invoked the commands to run using the Invoke() method of PowerShell object.
  • We need to check for errors if any using powershell.Streams.Error.
  • We want an Object ID and Application ID for the application we have created in Azure AD. To get both of these IDs, we have converted the PowerShell object into a JSON object and JSON object into a C# object using JsonConvert.SerializeObject method and JsonConvert.DeserializeObject() method respectively.
After this code, we can go to the Azure portal and in the Azure Active Directory - App Registrations, we can see the app we have registered using the C# code.
Summary
 
Thus, we can automate the application registration using C# code and PowerShell. In the next blog, we will see how to add and grant permissions programatically.