Add Guest Users in Azure Active Directory using Power Automate and C# Code

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.

In brief, If we have to perform any operation in Dynamics 365 either from within the Dynamics CRM Application like forms and views, through JavaScript, Plugin, Workflow, C# code, or through any language, Microsoft has given one Rest API called – Dynamics 365 WEB API (Enhanced version of Organisation Service or OData). And that API is only restricted to perform operations in Dynamics 365 only.

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.

Let\’s get started…

Azure AD Configuration:
1.  Navigate to the Azure Portal.
2.  Search for App Registrations. Click App Registrations as shown below.

3.  Click on New Registration.

4.  Enter the Name and click Register.

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.

6.  In the left navigation, click Certificates & secrets. Click New client secret.

7.  Enter the description and set its Expiry to Never and click Add.

8.  Copy the secret value which will be used in flow for authentication.

9.  In the left navigation, click API Permissions.

10.  Click Add permission. Select Microsoft Graph API as shown below.

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.

12.  Click Grant admin consent.

Once you are done with the Azure AD Configuration, you have two approaches/solutions to create users in Azure AD. What approach you go with it totally depends on your project need, product license, and organization need.

Approach 1 – Low Code – No Code

Using Power Automate:

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 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

Using C# 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 –

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

    <add key="clientId" value="\”/>
    <add key="clientSecretKey" value="\”/>
    <add key="tenantId" value="\”/>
    <add key="userName" value="\”/>
    <add key="Password" value="\”/>

Step 3:  Add the JSON file to keep HTTP Request JSON

Put the following content in JSON file

  \”invitedUserEmailAddress\”: \”\”,
  \”inviteRedirectUrl\”: \”\”,
  \”sendInvitationMessage\”: \”true\” 


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:

using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace CallMicrosoftGraphAPI
    class Program
        static void Main(string[] args)
            Console.WriteLine(\”Generating Token\”);



        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 = \”\”+ 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…\”);

            return token;

        public static void CreateGuestUser()
// Reading the JSON value,
// You can directly paste your JSON as well. Check this article to get the syntax –

            string json = File.ReadAllText(@\”C:\\Users\\Arpit\\Documents\\Code\\CallMicrosoftGraphAPI\\CallMicrosoftGraphAPI\\request.json\”);

// Get the user token
            string token = GenerateToken();
            HttpResponseMessage servicerequest = null;

            using (HttpClient httpClient = new HttpClient())
                httpClient.BaseAddress = new Uri(\”\”);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\”application/json\”));
                httpClient.DefaultRequestHeaders.Add(\”authorization\”, \”Bearer \” + token + \”\”);

                var content = new StringContent(json.ToString(), System.Text.Encoding.UTF8, \”application/json\”);

                servicerequest = httpClient.PostAsync(\”\”, content).Result;

                string response = servicerequest.Content.ReadAsStringAsync().Result;

                Console.WriteLine(\”User has been added as Guest User in Azure AD\”);



Code Explanation

  •  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.

Cheers 👍


Published by arpitpowerguide

My name is Arpit Shrivastava, who is a Microsoft MVP in the Business Applications category. I am a Microsoft Dynamics 365 and Power Platform enthusiast person who is having a passion for researching and learning new things and acquiring immense knowledge. I am providing consistent help, support, and sharing my knowledge through various Social Media Channels along with my Personal Blog, Microsoft Community, conducting online training and attending various 365 Saturday Events worldwide and sharing the best Solutions to the readers helping them achieve their goals and objectives in Customer Relationship Space.

6 thoughts on “Add Guest Users in Azure Active Directory using Power Automate and C# Code

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: