Streamlining Integration: Using Azure Managed identities in Power Apps and Power Automate to access Microsoft Graph API – Part 1

Using Microsoft Graph in Power Apps and Power Automate offers several advantages for streamlining integration with various Microsoft 365 services and applications. Additionally, securing these integrations with Azure Managed Identities significantly enhances the overall security of the solution. Azure Managed Identities enable applications and services to authenticate with Azure services seamlessly and securely. When it comes to using Microsoft Graph API, you don’t need a client secret anymore. This makes it simpler to manage and keeps everything more secure. This blog series, divided into multiple articles, is dedicated to utilizing managed identities either System Assigned or User Assigned in Power Platform to access MS Graph API endpoints. It leverages Azure API Management service with the support of a custom connector. The focus of this particular article is on configuring the Azure API management service with the necessary Microsoft Graph permissions for the managed identity.

Pre-requisites & permissions:

Here are the resources and permissions required to follow along this blogpost:

Azure Subscription/Entra ID:

You need an Azure subscription to create and manage Azure API Management instances.

  • Azure Managed Identity – User or System Assigned:
    • Create or use an existing Azure Managed Identity. This can be either a user-assigned identity or a system-assigned identity of the APIM resource, depending on your requirements.
  • Global Admin or Privileged Administrator Role:
    • The user should have Global Administrator or Privileged Administrator role in the Microsoft Entra ID to grant Admin consent for the MS graph permissions on the Managed Identity using Microsoft Graph PowerShell SDK.

Power Platform Environment:

Set up a Power Platform Environment where you plan to create and use custom connectors.

  • Role:
    • Ensure that the user/maker has the System Administrator/Customizer/Maker role on the Power Platform Environment. This role is required to create custom connectors.
  • DLP Policy:
    • Make adjustments to allow custom connector endpoints, especially in cases where endpoints are blocked by the tenant scoped DLP policy.
  • License:
    • A Power Apps or Power Automate Premium license is necessary for creating and using custom connectors. Ensure that the user has the required premium license assigned.

Azure API Management Setup with Microsoft Graph Permissions:

Create a Azure API Management resource and turn on System assigned managed identity and if available, add a User Assigned Managed Identity in the Security section of the API Management instance. Execute the following PowerShell script which user Microsoft Graph SDK to add the permission User.Read.All to either the System or User assigned managed identity. Adjust the permissions as needed for your specific requirements. Before executing the script, replace the permission and the display name of the Managed identity depending on the managed identity you have used. If you have used a System Assigned managed identity, ensure that it corresponds to the display name of the API Management instance.

# Install Microsoft Graph PowerShell module if not already installed

$PermissionName = "User.Read.All"
$DisplayNameOfMSI = "replaceherewithactualnameofManagedIdentity"
$GraphAppId = "00000003-0000-0000-c000-000000000000"

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Directory.ReadWrite.All","AppRoleAssignment.ReadWrite.All"

# Get Managed Identity Service Principal

$MSI = (Get-MgServicePrincipal -Filter "displayName eq '$DisplayNameOfMSI'")
# Sleep for a while to allow time for service principal creation if needed

Start-Sleep -Seconds 10
# Get Microsoft Graph Service Principal
$GraphServicePrincipal = Get-MgServicePrincipal -Filter "AppId eq '$GraphAppId'"

# Retrieve the App Role from the Microsoft Graph Service Principal based on the specified Permission Name
$Role = $GraphServicePrincipal.AppRoles | Where-Object {$_.Value -eq $PermissionName}

# Create an App Role Assignment HashTable for assigning the role to the Managed Identity
$AppRoleAssignment = @{

principalId = $MSI.Id

resourceId = $GraphServicePrincipal.Id

appRoleId = $Role.Id }

# Assign the Graph permission
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $MSI.Id -BodyParameter $AppRoleAssignment

You can download the above script from this link. If you prefer using the Azure AD PowerShell module, keep in mind that it is planned for deprecation. In such a case, you can get the script from this link.

Note: You’ll discover equivalent commands for Microsoft Graph PowerShell as opposed to the Azure AD PowerShell cmdlets on the following link

https://learn.microsoft.com/en-us/powershell/microsoftgraph/azuread-msoline-cmdlet-map?view=graph-powershell-1.0

Upon successful execution of the script, the following message will be displayed

The permission granted to the Managed identity can be validated from the Entra ID portal as shown below

Configure the Microsoft Graph API endpoint in API Management and configure policy:

SettingValue
Display namemsgraph
Web service URLhttps://graph.microsoft.com/v1.0
API URL suffixmsgraph

In the API Management instance, on the left menu select APIs > + Add API. Select HTTP and enter the following settings. Then select Create.

System Assigned Managed Identity:

Navigate to the newly created API and select Add Operation. Enter the following settings for accessing the API through System Assigned Managed Identity (SAMI) and select Save.

SettingValue
Display namegetUsrProfileSAMI
URL for GET/users/{User (UPN)}

Select the Operation getUserProfile. In the Inbound processing section, select the (</>) (code editor) icon to use the authentication-managed-identity policy to authenticate with the Microsoft Graph API endpoint using the Managed Identity. This policy uses the managed identity to obtain an access token from Microsoft Entra ID for accessing the specified graph resource.

Replace with the following code in the inbound node:

<inbound>
<base />
<authentication-managed-identity resource="https://graph.microsoft.com" />
</inbound>

User Assigned Managed Identity:

If you prefer to utilize a user-assigned managed identity, click on Add Operation, input the specified settings for accessing the API via User Assigned Managed Identity (SAMI), and then click Save

SettingValue
Display namegetUsrManagerUAMI
URL for GET/users/{User (UPN)}/manager

The Inbound processing section should have the following code

<inbound>

<base />
<authentication-managed-identity resource="https://graph.microsoft.com" client-id="ReplaceitwiththeAppcationIdoftheUAMI" />
</inbound>

You would now be able to test the Graph API endpoint for both the identities from the Test tab.

Add CORS Policy to API in API Management:

CORS settings allow or restrict web applications or services hosted on different domains from making requests to your API. If you want to enable cross-origin requests to the configured Graph API’s from Power Platform Custom connector, you need to configure CORS settings in the API Management service. In the left menu, select APIs and select the API that you will export as a custom connector. If you want to, select only an API operation to apply the policy to.

In the Policies section, in the Inbound processing section, select + Add policy. Select Allow cross-origin resource sharing (CORS).

Add the following Allowed origin: *

Select Save.

I have added * which allows all URL’s but you can be specific by adding the only the relevant URL’s such as https://make.powerapps.com, https://make.powerautomate.com etc

Reference: https://learn.microsoft.com/en-us/azure/api-management/enable-cors-power-platform#add-cors-policy-to-api-in-api-management

Summary:

Up to this point, we have set up the API Management instance with Graph API endpoints for both System Assigned and User Assigned identities. In the upcoming article, we will delve into exporting the API to the Power Platform as a custom connector, implementing security through API key authentication. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Streamlining Integration: Using Service Principal authentication on Custom connectors with Microsoft Graph Application Permissions

Microsoft recently announced a long awaited feature: support for Service Principals in Custom connectors which is currently in Public Preview. This empowers you to authenticate as a service principal instead of relying on user accounts. It’s a game-changer that paves the way for a multitude of scenarios, especially those requiring seamless, uninterrupted access for automated processes, free from the constraints of user involvement.

In one of my earlier posts, I discussed how to harness the power of Microsoft GRAPH API within custom connectors through delegated permission. In this article, I’ll delve into the step-by-step process of configuring service principal authentication in a custom connector for the Graph API with Application permissions to send emails. While I’ve chosen to focus on email communication, remember that you have the flexibility to opt for any of the supported Graph application permissions.

Setting up the Service Principal:

Let’s headover to the Microsoft Entra Admin center to register an AD App and grant the application permissions to send emails using the Graph API. Register an AD application with the following Application permission

Mail.Send: Send Mail as any user

Retrieve the Client ID & Tenant ID from the Overview section of the Azure AD app, and then proceed to generate a secret within the Certificates & secrets section under the Manage blade. Once the secret is generated, copy its value for use within the custom connector configuration. Add a Web Redirect URI https://global.consent.azure-apim.net/redirect as shown below

The Redirect URI is common and will be created while creating the custom connector.

Create Custom Connector:

With the service principal now created, let’s proceed to create the custom connector from the Power Apps maker portal. Choose the environment where you intend to create the custom connector. Navigate to Custom connectors on the left navigation menu, then click on + New custom connector and select Create from blank.

Once you’ve provided the connector name, you’ll be presented with the following screen. Enter graph.microsoft.com in the Host field and provide a brief description of the connector. Additionally, you have the option to customize the connector’s logo to your preference.

Now click Security at the lower-right corner of the above screen, which allows you to input the Azure AD application information for the service principal/App registration created earlier in the Entra Admin portal.

Here’s the step-by-step configuration:

  • Choose Authentication type as OAuth 2.0.
  • Change the Identity provider to Azure Active Directory.
  • Check the box Enable Service Principal support
  • Enter the Client ID and Client Secret from the Azure AD application.
  • Keep the Authorization URL as https://login.microsoftonline.com and Tenant ID as common.
  • Enter the Resource URL as https://graph.microsoft.com
  • For the Scope, specify Mail.Send based on the permissions you have added to the Azure AD app. If you have multiple permissions, separate them with spaces.

Once you’ve filled in this information, click Create connector. This action will automatically generate the Redirect URL as https://global.consent.azure-apim.net/redirect This URL should match the Redirect Web URI you previously added in the Azure AD application. With this configuration, your connector is now ready for the adding the actions based on the Graph API endpoints for sending emails.

Create Action to Send email:

With the connector successfully created, it’s time to create the action for sending emails. This action can be utilized in both Power Apps and Power Automate. The Graph API endpoint for sending emails is:

Http Request Mode: POST

Request URI: https://graph.microsoft.com/v1.0/users/{fromEmailAddress}/sendMail

The request parameter fromEmailAddress is to collect the information from the user while using the action

Request Body:

{
  "message": {
    "subject": "Mail sent using Custom Connector",
    "body": {
      "contentType": "Text",
      "content": "This is a sample email sent using Custom Connector which uses Service prinicipal"
    },
    "toRecipients": [
      {
        "emailAddress": {
          "address": "mailboxaddress@domain.com"
        }
      }
    ]
}
}

Proceed to the Definition tab of the Custom Connector. Here, select + New action, which will generate the following screen for you to enter information about the action.

After the Summary, Description and Operation ID is entered. Click + Import from sample under the Request section to the enter the Graph API endpoint request details as shown below

Click Import on the screen above. You can optionally provide a sample response by entering details in the default response section in the Add Action interface which will help you identify objects in Power Apps if the request has a response. For more information, please refer to my earlier blog post, which I have referenced in the introduction section. Don’t forget to update the connector.

Create Connection:

Once the connector with the Send Email action is set up, you can now proceed to test the action for sending emails. The first step is to create the connection, navigate to the below interface and click on + New connection under the section Test and then on the following popup select the Authentication Type as Service Principal Connection.

Enter the Client ID, Secret, and the Tenant ID you copied earlier to create the connection. You would now be able to test the action.

To use this in the Power Apps, after adding the connector, you would be able to call the action using the below code:

ServicePrinicpalSupport.SendEmail("fromEmailAddress@domain.com", {
        'message': {
            'subject': "Mail sent using Custom Connector from Power Apps",
            'body': {
                'contentType': "Text",
                'content': "Sample email sent from Custom Connector leveraging Service Principal"
            },
            'toRecipients': [
                {
                    'emailAddress': {
                        'address': "toUseraddrees@domain.com"
                    }
                }
            ]
        }
    });

The connections created uses the Authentication Type Explicit Authentication.

https://learn.microsoft.com/en-us/power-platform/admin/security/connect-data-sources#authenticating-to-data-sources

Sharing Connector:

When the app is shared with the user, the user will not be prompted to create a connection; instead, the consent window below will appear to allow the connection. You can use the PowerShell command Set-AdminPowerAppsApiToBypassConsent if you want to bypass consent for the app users. The connection is shareable, allowing you to share it for editing, using, sharing, etc., with other users.

Authentication Flow:

The authentication flow for custom connectors enabled with Service Principal uses the OAuth 2.0 client credentials flow, while for the custom connectors without Service Principal authentication, the OAuth 2.0 Authorization code flow is used. Below, you’ll find the Swagger details for the custom connector, showing both scenarios for connecting to Microsoft Graph using OAuth2 with Azure Active Directory

Swagger definition for Service Principal AuthenticationSwagger definition for Non Service Principal Authentication
securityDefinitions:   oauth2-auth:     type: oauth2     flow: accessCode     tokenUrl: https://login.windows.net/common/oauth2/authorize     scopes:       Mail.Send: Mail.Send     authorizationUrl: https://login.microsoftonline.com/common/oauth2/authorize   oAuthClientCredentials:     type: oauth2     flow: application     tokenUrl: https://login.windows.net/common/oauth2/authorize     scopes:       Mail.Send: Mail.Send security:   – oauth2-auth:       – Mail.Send   – oAuthClientCredentials:       – Mail.SendsecurityDefinitions:   oauth2-auth:     type: oauth2     flow: accessCode     tokenUrl: https://login.windows.net/common/oauth2/authorize     scopes:       Mail.Send: Mail.Send     authorizationUrl: https://login.microsoftonline.com/common/oauth2/authorize security:   – oauth2-auth:       – Mail.Send

Summary:

In this blog post, I have shown you how to use Service principal authentication in custom connector with application permissions to send an email through the Graph API. You can apply this feature for any supported Microsoft Graph Application permission such as SharePoint, Exchange, Teams, Azure AD, and more. It’s a game-changer, making automated processes smooth and user-free. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Automate the provision of On-Premise AD Account – Part 2

This post is in continuation to my previous post Automate the provision of Azure AD Account & License assignment – Part 1 for creating account in Azure active directory using Power Automate. On this post I will highlight the feature available in Azure Automation account which can be leveraged to create an On-premise AD account. Refer to this post for the usage of Azure automation account to interact with SharePoint online in Microsoft 365 using Power Automate.

Azure Automation is so easy to setup for automating tasks that interacts with

  • Azure (Azure AD, SQL etc)
  • M365 services (SharePoint etc). 

Automation runbooks in Azure might not have access to resources in other clouds or in your on-premises environment because they run on the Azure cloud platform. To access local resources like On-premise Active Directory which lives behind the firewall, there is a feature within Azure Automation called as Hybrid runbook worker. Azure Automation Hybrid Workers extends Azure Automation into your private networks and allows running runbooks that interacts with resources such as on-premises Active Directory, SharePoint etc.

Hybrid Runbook Worker feature to run runbooks directly on the

  • Computer in On-premise network
  • Any secured network like a virtual machine in Azure behind the firewall
  • Cloud services like AWS etc

that’s hosting the role and against resources in the environment to manage local resources. Refer to this documentation about Hybrid runbook worker for more information.

The following image from Microsoft documentation illustrates this functionality:

Pre-requisite:

  1. Azure Subscription to create
    • Automation Account
    • Log Analytics Workspace
  2. Server (Windows or Linux based)
    • Internet access
    • Port: Only TCP 443 required for outbound internet access

The deployment instructions from Microsoft for

I’ve found a really interesting video on Youtube from Travis Robert regarding this topic to set this up on Windows workstation.

Once the Hybrid runbook worker is setup, you can write PowerShell script to create account in On premise Active directory. Find the link to the script to add a user to Active directory in Onpremise. The parameters for the AD account (attributes like name, location, jobtitle, manager etc) to the runbook can be passed from a SharePoint List in Office 365 which could then be triggered using a Flow.

Summary: I was not able to give you a complete walkthrough but I hope had given some pointers to connect on-premise AD. Forgive my ignorance if I have made some mistakes since I don’t have much experience with IT infrastructure. Hope you find this post useful & informational. Let me know if there is any comments or feedback below.

Access Active Directory user profile attributes using Graph API

Using graph API you can access all the Active directory attributes. The me endpoint gives your profile information https://graph.microsoft.com/v1.0/me. To get a specific user’s information the endpoint should be https://graph.microsoft.com/v1.0/users/useremailaddress

For getting any specific AD attribute you can pass the required attribute as a query string https://graph.microsoft.com/v1.0/me?$select=jobTitle,department,displayName

In bigger active directory implementation, there will also be information stored on the Extension attributes, to get the information you will have to pass the name of the attribute “OnPremisesExtensionattributes” as a query string in the format as

 https://graph.microsoft.com/v1.0/me?$select=jobTitle,department,displayName, OnPremisesExtensionattributes

Graph explorer is a nice tool to test the Graph endpoints. Refer the documentation from Microsoft on the different available AD endpoints

Graph Explorer

The beta ME endpoint https://graph.microsoft.com/beta/me gives more information of the user

The User profile service Rest API endpoint in SharePoint http://siteurl/_api/SP.UserProfiles.PeopleManager/GetMyProperties does not provide all the active directory information. For e.g Location, OnPremisesextensionAttributes etc information is not available. SharePoint UPS synchronizes the AD data of all users in schedule basis. So the other option is to use the Graph Endpoint if you need those information for your application customization.

Endpoint point to get a specific attribute is

https://siteURL/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=PictureUrl,AccountName

For more information about different endpoint, refer this documentation from Microsoft.

Automate the provision of Azure AD Account & License assignment – Part 1

A decade back I was part of a team to automate the On & Offboarding process of employees for a customer using .NET framework, it had a module to provision user accounts in an on-premise environment. I still remember having used couple of dll’s for Active directory 2003 & exchange 2007 to create AD & Email account. It was not easy but nowadays with the Office 365 in place its so easy to create account & enable different Office 365 services (Exchange, SharePoint, Yammer etc) for a user in Azure Active directory. This example will be applicable for the Organization which does not have On-premise Active directory. Organizations having On-premise active directory, the user account’s will be synchronized from On-premise AD to Azure AD. On this post I am going show you how to

  1. Create Azure AD account & assign license using Power Automate
  2. Assign License using Graph Endpoint

Create Azure AD account & assign license using Power Automate:

There is a Power Automate action Create user under the connector Azure AD which helps us to create account in Azure AD but there is no action as of now to assign individual license to a user but we can overcome this by adding the user to the AD security group which has a license assigned to it.

There is a flow action Add user to group under the same connector for adding the user to the security group, all the members of the group will get the license assigned on that group. The Azure AD connector does not return custom attributes of Azure AD. For e.g you can’t assign a value to a custom AD attribute with the Create user action, if you want to assign a custom attribute or an attribute which is not exposed in the Create User action then the account has to be created using PowerShell. There are ways to call a PowerShell script from Azure Automation Runbooks with the help of a flow action.

Other Azure AD actions apart from the above screenshot which could be of use are

  • Create group
  • Get group members
  • Get groups of a user
  • Get user
  • Remove Member from Group
  • Update user

There are templates available in Power automate template section which helps you create account based on the information from the SharePoint List, based on HTTP request etc

Prerequisite:

  • Permissions on Azure AD:
    • Group.ReadWrite.All
    • User.ReadWrite.All
    • Directory.ReadWrite.All
  • Security group with license assigned

For assigning a license to Security group, go to Azure AD Admin center. Follow this documentation from Microsoft to assign license to a group.

You can also turn off certain services from the license to the group, for e.g Turning off the Power App service for the user

You can also use dynamic groups for assigning license to a user, if you have dynamic group based license assignment to a user then you could ignore the step on the flow to add user to the security group. Dynamic groups works based on rules to determine group membership, for e.g if a user has an AD attribute set for Department. In this case the AD user created with certain department will get automatically added to the group which will in turn assign a license to the user.

Let’s now create the flow, I have used an Instant flow with trigger Manually Trigger a flow. Add the action Create user from the connector Azure AD

Now add the action Add user to group, the Group Id should be for the Security group which has a license assigned to it. The User Id field should be dynamic value Id from the previous action Create user.

To get the group Id, go to Azure AD

Run the flow. Once the flow runs successful the user account will be provisioned on Azure Ad with a license.

Assign License using Graph Endpoint:

There is a beta graph endpoint to assign license to a user. Find the Microsoft documentation for more information

All types of license (E5, E3, PowerApps, Power etc) has a Service Plan id also called as SKU id. Find the list of SKU id’s on this link if your tenant has procured the license for the service

 To get the available service plan or SKU ID, make a GET call to the endpoint https://graph.microsoft.com/v1.0/subscribedSkus & also from the beta endpoint of the user https://graph.microsoft.com/beta/me

Once the sku id are available based on the type of license to be assigned, you will have to make a POST call to

Endpoint URL: https://graph.microsoft.com/beta /users/testuser10@mydevashiq.onmicrosoft.com/assignLicense

Request Body:

{
  "addLicenses": [
        {
            "disabledPlans": [],
            "skuId": "b05e124f-c7cc-45a0-a6aa-8cf78c946968"
        },
        {
            "disabledPlans": [],
            "skuId": "a403ebcc-fae0-4ca2-8c8c-7a907fd6c235"
        }
  ],
  "removeLicenses": []
}

The first SKU id is for Enterprise Mobility & Power BI (Free)

To remove the license for a user, use the collection removeLicenses. This graph endpoint to assign license can also be called from a Flow.

Summary: You can also use a HTTP request trigger in the Flow for integrating with other applications. On next post I will write about creating account in On-premise Active Directory. Hope you find this post useful & informational. Let me know if there is any comments or feedback below.