Invoke Power Automate on Creation of New Users in Azure AD

Vikrant SarodeDyn365CE4 years ago16 Views

As we know, Power Automate contains around 350+ inbuilt connectors with their actions and triggers. But in some scenarios we need custom triggers, which are not directly available in Power Automate. To achieve those scenarios, we can create custom Connectors.

In my previous article, I have shown how to create a custom connector to automate Microsoft Teams Meeting.

https://vikrantsdynamicsblogs.wordpress.com/2020/05/10/automate-microsofts-teams-meetings-using-custom-connector-in-power-automate/

In this blog, I will show you how to invoke power automate on creation of new user in azure active Directory.

We can achieve this by doing below simple steps,

  1. Application registration and add permissions on the Azure portal.
  2. Create Subscription.
  3. Create Power Automate.

Let’s start step by step,

  • Register an Application and add permissions at the Azure portal.

To use Microsoft Graph API (connects you to Azure AD), you need a registered application with an identity provider. Bunch of reasons behind this (read original thoughts here: https://www.oauth.com/oauth2-servers/background/), but as a summary: it makes life more secure and provides an extra layer to control permissions.

In Azure AD, you can register your application either as a web or a native app. Go with a web application, as that allows the service-to-service scenario.

Please follow below link for more info to register application: https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Once the app is registered, save Client ID and Client secret, we require this in future steps. 

Now, hit the “API permissions” tab, and add Microsoft Graph with at least the “User read and write” permission.

Don’t forget to grant admin consent to newly added permission. (Azure global admin will help you in this case).

  • Create Subscription:

We need to subscribe graph’s API to receive notifications when the requested type of changes occur to the specified resource.

We have multiple resources which support subscription mechanism, Depending on resource and permission type (Delegate or Application) we have below listed resource.

In our scenario we are subscribing to “User” resource, so whenever new User gets created in Azure active directory it will notify us.     

To subscribe resource we need to create new Postman Collection,

Download postman app for windows https://www.postman.com/downloads/

Click New to create Collection, provide collection name and navigate to Authentication tab,

Select Type as OAuth2.0 and click on get new access token.

Once you click on “Get New Access Token”, Provide below properties.

Token Name: provide token name.

Grand type: Authorization code

Callback URL: https://www.getpostman.com/oauth2/callback (you need to add this URL in azure Application as well).

Auth URL: https://login.microsoftonline.com/{{Tenant ID}}/v2.0/authorize

Access Token URL: https://login.microsoftonline.com/{{Tenant ID}} /oauth2/v2.0/token

Client ID: Azure app client ID

Client Secret: Azure App Secret ID

Scope: https://graph.microsoft.com/.default

State: 1234

It will look like as below, click on request token and use it in you collection.

 Now create one more request in Postman as below,

baseUrl: https://graph.microsoft.com/v1.0/subscriptions

Authorization : “Inherit auth from parent”

Body: 

{
"changeType": "updated",
  "notificationUrl": "https://webhooknotification.azurewebsites.net/api/getTrigger?code=aQbafLOMVVC3oT/aVTFO ==",
  "resource": "/Users",
  "expirationDateTime": "2020-05-22T11:00:00.0000000Z",
  "clientState": "SecretClientState"
}

Below is description of body

changeType : Required. Indicates the type of change in the subscribed resource that will raise a notification. The supported values are: created, updated, deleted. Multiple values can be combined using a comma-separated list.

notificationUrl: Required. The URL of the endpoint that will receive the notifications. This URL must make use of the HTTPS protocol.

Resource: Required. Specifies the resource that will be monitored for changes. Do not include the base URL (https://graph.microsoft.com/v1.0/). See the possible resource path values for each supported resource.

expirationDateTime: Required. Specifies the date and time when the webhook subscription expires. The time is in UTC, and can be an amount of time from subscription creation that varies for the resource subscribed to.

clientState: Optional. Specifies the value of the clientState property sent by the service in each notification. The maximum length is 128 characters. The client can check that the notification came from the service by comparing the value of the clientState property sent with the subscription with the value of the clientState property received with each notification.

It will look like as below,

notificationUrl: you need to create one azure function, it will work as Webhook, whenever users get created in Azure AD, this subscription will notify to our Azure function.

Create one Azure function and include the below code in it and publish it at your azure portal. 

public static class getTrigger
    {
        [FunctionName("getTrigger")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"C# HTTP trigger function begun");
            string response = string.Empty;

            string requestContent = await req.Content.ReadAsStringAsync();
            log.Info($"Received events: {requestContent}");

            if (requestContent == string.Empty || requestContent == "")
            {
                string validationToken = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "validationToken", true) == 0)
                .Value;

                if (validationToken != null)
                {
                    //Send success responce for subscription 
                    var token = validationToken;
                    log.Info($"GetQueryNameValuePairs: {validationToken}");
                    return req.CreateResponse(HttpStatusCode.OK, validationToken);                   
                }
            }
            else
            {
                //invoke power automate 
                TriggerPowerAutomate(requestContent,log);
            }
            return req.CreateResponse(HttpStatusCode.OK, response);
        }
}

After successfully publish you can call postman requests to subscribe to the event.

In response, it will show you the subscription is successful as below.

  • Create Power Automate:

Navigate to https://make.powerapps.com/ and login with your credentials.

Once you log in, create new Flow as “Automated – from blank”

Then select Trigger as “When a HTTP request is received” and provide below properties,

HTTP Post URL: Once you saved the Flow, HTTP post URL will Auto-generate, copy it, and call it from your newly created Azure function.ally create once the flow is saved.

Request body JSON schema: you can provide the expected JSON format.

Method: POST

Add one more component to parse JSON as below, in this JSON we will get GUID of newly created user.

Now select action “Get User” from Azure AD connector, and provide user GUID as a unique identifier, you will get it in parse JSON action.

Once you saved the Flow, HTTP post URL will Auto-generate, copy it, and call it from your newly created Azure function.

In the Azure Function you have to incorporate this URL as below, so whenever this Azure function gets trigger it will also call this HTTP URL with JSON.

Write a function to call Flow as below.

public static void TriggerPowerAutomate(string requestContent, TraceWriter log)
        {
            //call power automate 
            string PowerAutomateURL = "{{Powe Automate URL}}";
            log.Info($"Function call TriggerPowerAutomate");
            HttpResponseMessage servicerequest = null;
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(PowerAutomateURL);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var content = new StringContent(requestContent.ToString(), System.Text.Encoding.UTF8, "application/json");
                servicerequest = httpClient.PostAsync(new Uri(PowerAutomateURL), content).Result;
                string response = servicerequest.Content.ReadAsStringAsync().Result;
                log.Info($"TriggerPowerAutomate response: "+ response.ToString());
            }
        }

Download Azure function’s solution file from here: https://drive.google.com/file/d/1_3G5NhuHoajzzzbGpVSBsW10QNaE2pYu/view?usp=sharing

Now, we will test our flow, create a new user in your azure.

As soon as you click on Create, MS Flow will get a trigger and it will provide you details of newly created User.

As once we get this trigger and user’s information you can perform your actions as per your requirements.

Same things we can do when any user gets added/removed in a specific group.

Happy Coding 🙂

Original Post https://vikrantsdynamicsblogs.wordpress.com/2020/05/24/invoke-power-automate-on-creation-of-new-user-in-azure-ad/

Leave a reply

Join Us
  • X Network2.1K
  • LinkedIn3.8k
  • Bluesky0.5K
Support The Site
Events
March 2025
MTWTFSS
      1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31       
« Feb   Apr »
Follow
Sign In/Sign Up Sidebar Search
Popular Now
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...