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

In both Part 1  and Part 2 of the blog series, I’ve covered the utilization of Managed Identities in Power Apps and Power Automate for secure access to Microsoft Graph API. This included a deep dive into setting up and configuring the Azure API Management service with the Microsoft Graph permissions for the managed identity. In Part 2, I’ve explored the process of exporting the API as a connector in Power Platform, securing it with API key authentication.

The Part 3 aims to enhance the security of the connector by implementing Entra ID OAuth authentication.

Entra ID Apps:

To enhance the security of the custom connector published from Azure API Management for Microsoft Graph APIs using Entra ID OAuth authentication instead of Subscription key, it is essential to create two Entra ID applications. One application should represent the API from API Management, while the other should represent the client application to be utilized in the Entra ID OAuth authentication for the custom connector.

Registering an Application in Microsoft Entra ID for API Representation:

In the Entra ID portal, navigate to App registrations and click + New registration. Enter a name, such as APIM PP Resource, and proceed by clicking the Register button, leaving all settings as default. This app represents the APIs added in the Azure API management instance.

  • Under the Manage section in the side menu, select Expose an API. Set the Application ID URI with the default value and remember to copy this value for future use.
  • Click on the Add a scope button to access the Add a scope panel:
    1. Enter a new Scope name as APIM.MSGraphAPI
    2. Set Admin consent display name to APIM MSGraph API
    3. Provide Admin consent description as “Grants access to the API in APIM.”
    4. Ensure the Enabled scope state is selected.
    5. Complete the process by selecting the Add scope button to create the scope.

Registering an Application in Microsoft Entra ID for Client Representation:

Create another Entra ID app to be used in the custom connector for securing with Entra ID OAuth Authentication. In the Entra ID portal, navigate to App registrations and click + New registration. Enter a name, such as APIM PP Client, and proceed by clicking the Register button, leaving all settings as default.

  1. Retrieve the Client ID, Tenant Id from the Overview section of the Entra ID app and generate a secret through the Certificates & secrets under the Manage blade. Once the secret is successfully created, copy its value for use in configuring the custom connector OAuth Authentication.
  2. Go to the Entra ID app APIM PP Resource created earlier. In the Manage section, click on Expose an API and then Add a client application by selecting + Add a client application in the popout panel. Enter the Client ID of the APIM PP Client app registered now. Select the authorized scope created in the previous section, then proceed by clicking Add Application. This ensures the application APIM PP Resource trusts the client application APIM PP Client and users should not be asked to consent when the client calls the APIs published API Management instance.

Note: If you prefer users/admins to provide consent for the permission while creating a connection for the custom connector, add the APIM.MSGraphAPI Scope to the APIM PP Client app, as shown below. In this scenario, the step mentioned in bullet no 2 becomes unnecessary.

Configuring Custom Connector Authentication to Entra ID OAuth:

Following the export of the API from the Azure API Management as a custom connector in Power Platform in Part 2 of this blog series, proceed to the Power Apps or Power Automate maker portal to edit the connector.

  1. Access the custom connectors, locate the exported connector in the Power Platform Environment where the connector was exported from API Management
  2. Within the Authentication type settings, originally set to API Key, click Edit, and modify it to OAuth 2.0.
  3. Choose the Identity provider as Azure Active Directory. Enter the Client ID and Client secret obtained from the APIM PP Client app copied earlier. Set the resource URL to the Application ID URI generated from the APIM PP Resource app.
  4. Click Update connector to generate a Redirect URL on the same screen—ensure to copy this URL.
  1. Navigate to the APIM PP Client app in the Entra ID portal and add a Web Redirect URI, paste the copied Redirect URL.

Azure API Management: Configure JWT validation policy to Authorize requests from Custom connector:

The JWT validation policy pre-authorizes requests from the Power Platform Custom connector as it adds the layer of security to ensure that incoming access tokens are valid and meet specific criteria before the APIM starts processing requests to the added MS Graph API endpoints. The policy checks the value of the audience claim in an access token obtained from Microsoft Entra ID with in the custom connector. The audience claim typically specifies the intended recipient of the token, ensuring that the token is meant for the intended API.

By configuring the following JWT validation policy in the <inbound> policy section below the node <base />, you enforce the validation of the access token, and if the token is invalid, an error message is returned.  Don’t forget to replace the TenantId and the required claims value to the client id of the app APIM PP Resource.

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">

<openid-config url="https://login.microsoftonline.com/replaceherewithTenantId/v2.0/.well-known/openid-configuration" />
<issuers> <issuer>https://sts.windows.net/replaceherewithTenantId/</issuer>
</issuers>
<required-claims>
<claim name="aud">
<value>api://replaceherewiththeClientIDoftheApp-APIM PP Resource</value>
</claim>
</required-claims>
</validate-jwt>

Note:  If you attempt to establish the connection from the Test Tab and subsequently execute the action, you will encounter the following error “Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.

Creating a Product:

To enable the custom connector to generate tokens for API access from API Management, it’s necessary to associate the APIs with a Product that doesn’t require a subscription key. Follow these steps:

  • In the left navigation pane, go to Products and click on + Add.
  • Provide the Product Name, Description, uncheck the box Require subscription option, select the relevant API, and proceed to create the Product.

Testing the Custom connector:

Navigate to the Power Platform Maker portal and access the custom connector interface. Edit the connector to initiate the creation of a connection within the Test tab. Click on + New connection and click Create. Notably, you’ll observe that it doesn’t prompt for the API Subscription key, as discussed in the Part 2 of the article.

Once the connection is created, return to the edit mode of the custom connector to initiate testing of the actions. Navigate to the Test tab, where you can select the specific connection and choose the operation you wish to test. Test the operation and validate the results of the custom connector action.

Summary:

This concludes the blog series, where we delved into the secure access of Microsoft Graph APIs in Power Platform with the help of Azure API management, employing both Subscription keys and Entra ID OAuth authentication. Demonstrated the usage of managed identities in Power Platform, the methods explored here, particularly for securing Microsoft Graph API with application permissions, are adaptable for various services. Addressing the significant security risk of Broken Access Control, I have highlighted the importance of correctly implementing authentication mechanisms to prevent potential exploitation by attackers.

For those with existing Entra ID app registrations seeking to enhance security with API Management, the credential manager feature offers a solution. Utilizing the Grant Type Authorization code for Delegated Permission and Client Credentials for Application Permission ensures a comprehensive approach to safeguarding your applications and APIs. 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 Azure Managed identities in Power Apps and Power Automate to access Microsoft Graph API – Part 2

In Part 1 of the blog series on using Managed identities in Power Apps and Power Automate to access Microsoft Graph API securely, I have delved into the setup and configuration of the Azure API management service with the necessary Microsoft Graph permissions for the managed identity. Building upon that foundation, Part 2 aims to take it further your integration journey in making the API’s available as a connector in Power Apps and Power Automate secured with API key Authentication.

Azure API Management Instance: Managing API Subscription Keys

APIs published through the Azure API Management instance are by default secured by Subscription keys. These keys play a crucial role in establishing connections in Power Apps or Power Automate after exporting APIs as custom connectors.

To manage these keys, navigate to the left navigation menu under the “Subscriptions” blade in the Azure portal within your API Management (APIM) instance. Here, you have the option to generate a new key or utilize an existing one. Copy the key from the portal to create the connection in the later section.

You can test the API by using the Subscription key from Postman as shown below:            

Exporting API as a Connector in Power Platform:

To harness the capabilities of the APIs within your API Management instance secured with the Managed identities, exporting them as connectors in Power Platform is a major step in order to be used in Power Apps and Power Automate. Follow these simple steps for a seamless integration:

In the left navigation menu, navigate to Power Platform under the APIs blade.

  • Click on Create a connector to initiate the connector creation process.
  • Choose the specific API (e.g., msgraph) that you wish to export as a connector.
  • Select the Power Platform environment where you have Maker/Admin role access.
  • Under API Display Name, enter a name for the connector. This will be the identifier for your connector within Power Platform.
  • Click on the “Create” button to complete the process.

Once the connector is created, navigate to your Power Apps or Power Automate portal. You’ll see the API listed under Custom Connectors on the left navigation bar in Environment where the connector has been created from the API Management instance.

  • Click on the Edit icon to initiate the analysis and testing of connector actions.
  • Explore the Definition tab to view the view the API operations within the APIM instance now listed as Actions.
  • Verify the Authentication type of the connector by navigating to the Security tab, where the setting is configured to API key for streamlined validation.
  • Begin by creating a connection in the Test tab. Click on + New connection to start testing.
  • Enter the Subscription key, which you previously copied from the Azure portal for the API Management (APIM) instance. This key establishes the secure link between your connector and the APIM services. If there is no error, the connection will be created.

In the event of encountering below error message indicating that connection creation has been blocked by Data Loss Prevention (DLP) policy

Add the Gateway URL copied from the API management instance under the Overview section on the portal as a connector pattern allowed in the Business/Non Business category of the DLP policy.

Note: Please be aware that in the API Management instance, within the APIs Policies section, if you haven’t included the wildcard (*) as I did for CORS, and have instead specified particular URLs like https://make.powerapps.com, an additional policy in the Custom connector is required to be added under the Definitions tab. Specifically, you need to add a policy to set the request Origin header.

Testing the Custom Connector:

Once the connection is created, return to the edit mode of the custom connector to initiate testing of the actions. Navigate to the Test tab, where you can select the specific connection and choose the operation you wish to test. Test the operation and validate the results of the custom connector action.

Summary:

This completes the Part 2 of the blog series where we have explored the process of accessing Microsoft Graph APIs securely within the API management with Subscription key authentication using managed identities (System and User) as a connector in Power Platform. In our next article, we will delve into the enhancing security further by implementing OAuth authentication within the custom connector for API management APIs. Stay tuned. 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 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.