Welcome everyone to the Power Guide Mentorship Program.
Today I am going to share a #PowerGuideTip11– which will help you to automate the User creation in Azure Active Directory. There are various business requirements we may come across where we need to automate the user creation in Azure AD. Few very common business requirements are:
- Add Owner in Microsoft Teams – Need to add the user in Azure AD
- Add Members in Microsoft Teams. – User must be Guest User in Azure AD
- Migrate Users from one CRM instance to another instance
- Move users from one security group to another
- Power Automate UI Approvals – In order to allow External Users to approve the request they must be in Azure AD as a guest user
- Send Portal Invitation to Azure AD B2C Users.
- Allow Portal access to invited users only – Remove Sign Up option from Azure AD B2C Login Page and allow portal access to invited users only by creating them from CRM internally.
- ….and many more
Today, I will share two-approaches through which you can easily automate your user creation in Azure AD: However, before discussing that, I would like to give a short explanation about Microsoft Graph API. Though I have already been covered this topic in my previous article.
If you want to know the Basics of Microsoft Graph API, You can go through my this article.
However, you already know that Microsoft Dynamics 365 is tightly coupled with numerous other Microsoft products and services like Microsoft Azure, Microsoft Teams, Office 365. Outlook, OneDrive, OneNote, Microsoft Excel, and many more. And we often need to interact with these products and services to fulfill various business needs.
Hence, in order to interact with all these products and services, Microsoft introduced a new Rest API called Microsoft Graph API, which enables you to access various Microsoft Cloud service resources.
Since we have to create the users in Azure AD, Hence we’ll have to interact with Graph API.
5. In the left panel, click Overview. Copy the Application (client) ID and Directory (tenant) ID values. These values will be used in Flow for authentication.
11. Click Application Permission and Add the following Permissions (Add permission based on your need).
I have added the following Application and Delegate Permission based on my Requirements and the operations I need to perform using Microsoft Graph API.
Approach 1 – Low Code – No Code
Important Note: Make sure you have following privileges in Azure AD, otherwise you may end up facing permission related issues (for Azure AD user creation focus on highlighted one)
Step 1 – Go to https://make.powerapps.com/ and click on Flows
Step 2: Click on + New and Choose + Instant from Blank
Step 3: Provide Flow Name and Add Http Request Step
Step 4 – Configure the Flow as following.
Provide the Client ID, Client Secret Key, and Azure AD Tenant ID
Step 4 – As a best practice, Instead of hard-coding the Azure AD configuration, you can initialize all in the variables and pass the variable as shown below.
Step 5 – You can now Run and Test the Flow
Approach 2 – Custom Code
Important Note: Make sure the User (that you are using to connect yourAD in your code and getting token of it) must have following privileges in Azure AD, otherwise you may end up facing permission related issues (for Azure AD user creation focus on highlighted one)
Check these article as well for permissions – https://stackoverflow.com/questions/46429059/ms-graph-guid-for-permission-user-invite-all
Step 1 – Open Visual Studio and Create a Console Application (CallMicrosoftGraphAPU)
Step 2: Add Application.Config file to keep all the Azure AD related configuration
Put the following content in App.config file
<?xml version=”1.0″ encoding=”utf-8″ ?>
<supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.5″ />
<add key=”clientId” value=”<your azure app client id>”/>
<add key=”clientSecretKey” value=”<your azure app client secret key>“/>
<add key=”tenantId” value=”<your azure active directory id>“/>
<add key=”audienceURL” value=”https://graph.microsoft.com/.default”/>
<add key=”userName” value=”<Azure AD admin username>”/>
<add key=”Password” value=”<Azure AD admin password>“/>
Step 3: Add the JSON file to keep HTTP Request JSON
Put the following content in JSON file
“invitedUserEmailAddress”: “<email id of guest user that you want to add in Azure AD>”,
Step 4 – Download the C# Code from My GIT HUB Repository and paste it inside Program,cs
Step 5 – Add all necessary DLLs and References from Nuget Packagers. I have added the following references. You may need to add other references as well based on your Visual Studio version and framework
Step 6 – After pasting the code. The code will look like this:
static void Main(string args)
public static string GenerateToken()
String clientID = ConfigurationManager.AppSettings[“clientId“];
String clientSecretKey = ConfigurationManager.AppSettings[“clientSecretKey“];
string tenantId = ConfigurationManager.AppSettings[“tenantId“];
string audienceURL = ConfigurationManager.AppSettings[“audienceURL“];
string TokenUrl = “https://login.microsoftonline.com/”+ tenantId + “/oauth2/v2.0/token“;
string userName = ConfigurationManager.AppSettings[“userName“];
string Password = ConfigurationManager.AppSettings[“Password“];
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.CacheControl] = “no-cache“;
webClient.Headers[HttpRequestHeader.ContentType] = “application/x-www-form-urlencoded”;
string para = “grant_type=password&scope=” + audienceURL + “&client_id=” + clientID + “&client_secret=” + clientSecretKey + “&userName=” + userName + “&password=” + Password + “”;
string response = webClient.UploadString(TokenUrl, “POST“, para);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
string token = jsonObj.access_token;
Console.WriteLine(“Token Generated Succesfully…“);
public static void CreateGuestUser()
// Reading the JSON value,
// You can directly paste your JSON as well. Check this article to get the syntax – https://stackoverflow.com/questions/22998177/store-hardcoded-json-string-to-variable
string json = File.ReadAllText(@”C:UsersArpitDocumentsCodeCallMicrosoftGraphAPICallMicrosoftGraphAPIrequest.json“);
// Get the user token
string token = GenerateToken();
HttpResponseMessage servicerequest = null;
using (HttpClient httpClient = new HttpClient())
httpClient.BaseAddress = new Uri(“https://graph.microsoft.com/v1.0/invitations“);
httpClient.DefaultRequestHeaders.Add(“authorization“, “Bearer ” + token + “”);
var content = new StringContent(json.ToString(), System.Text.Encoding.UTF8, “application/json“);
servicerequest = httpClient.PostAsync(“https://graph.microsoft.com/v1.0/invitations“, content).Result;
string response = servicerequest.Content.ReadAsStringAsync().Result;
Console.WriteLine(“User has been added as Guest User in Azure AD“);
- Read all Azure AD configurations from App.config
- Request for Access Token
- Got the Access Token
- Use the Token to call Microsoft Graph API in order to add a guest user in Azure AD
- User added successfully
Step 6 – Run and Test the code
Download the Complete Code:
That’s all for today.
Stay Tuned for more such interesting stuff.