Bridging the Gap: Calling Azure Functions from SPFx Cross Tenants

Bridging the Gap: Calling Azure Functions from SPFx Cross Tenants

In today's interconnected digital world, integrating cloud services is essential. However, complex environments like multi-tenant Azure setups can pose significant challenges. This blog addresses the hurdles we faced when connecting an SPFx web part to an Azure Function across different tenants.

We'll cover:

  • The problem we encountered
  • Creating a multi-tenant application
  • Configuring the Azure function for authentication
  • Why we require SharePoint Online Client Extensibility Web Application Principal
  • Call Azure function from SPFx code
  • Conclusion

By the end of this post, you'll have a clear understanding of how to overcome these challenges and successfully integrate your Azure Function with an SPFx web part across tenants.


The Client's Need

Our client uses a complex Azure setup with two tenants. One houses their Azure Function, while the other hosts SharePoint Online. We aimed to create an SPFx web part that seamlessly interacts with the function for enhanced functionalities, but secure communication across tenants was crucial


The Problem we encountered

Our client operates in a complex cloud environment with two distinct Azure tenants. One tenant house essential Azure resource (Function app), while the other hosts their SharePoint Online instance. Our objective was to build a solution where SPFx webpart could seamlessly interact with an Azure Function to complete its task, and it was important that the web part and function could securely communicate with each other using user context.

While exploring Microsoft's documentation, Referenced a guide on building a multi-tenant enterprise API with Azure AD and connecting it with SharePoint Framework (link:https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient-enterpriseapi-multitenant). However, it appeared the guide's configuration might not fully align with the current Azure portal interface.

We opted for the multi-tenant application approach to avoid storing sensitive information, like secrets, directly within the SPFx code, which would be required for generating an application token to access the Azure Function.

We meticulously followed the guidelines outlined in the Microsoft document, but unfortunately, we encountered a 403 error - Forbidden when attempting to invoke the Azure Function from SPFx web part using the user context generated token.


The Solution

Prerequsites

  1. The function app must be created before setting up its authentication. If it hasn't been created yet, you can use the following URL to generate the function app: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-function-app-portal?pivots=programming-language-csharp
  2. Get Client Id of "SharePoint Online Client Extensibility Web Application Principal" - - Log in to the Azure tenant where SharePoint is hosted. - Go to App registration in Entra and Search for application with name "SharePoint Online Client Extensibility Web Application Principal" - Copy the application's Client ID and paste it into a notepad. We will need it when enabling authentication on the Function app.
  3. The SPFx solution should be created before setting up the configurations. You can follow the guide here: https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part

Creating a multi-tenant application

  • Sign in to the Microsoft Entra admin center with at least Cloud Application Administrator privileges.
  • Go to Identity > Application > App registrations and choose New Registration.
  • Provide the display name for the application.
  • Under supported account types, select "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)".
  • For the redirect URL, choose "Web" and enter the following value: https://<Function-App-Name>.azurewebsites.net/.auth/login/aad/callback
  • Click on register. At this level, Application will be registered in Entra.
  • In the registered application, go to API Permissions and follow below steps.

  • Go to Expose an API and follow below configurations

  • Enable the "ID Token" option in the Authentication tab of the registered application and save your changes.
  • Copy the Client ID and Application ID URI and paste them into a notepad for future reference.

Configuring the Azure Function for authentication

  1. Go to the Function app that you created as part of the prerequisites.
  2. Click on "Authentication" under Settings.
  3. Click on "Add identity Provider" and select "Microsoft".
  4. Go with default setting for "Choose a tenant for your application and its users".
  5. Under "App Registration", Select "Provide the details of an existing app registration".
  6. Enter Client Id which we have copied earlier in "Application (client) ID".
  7. Leave the "Client Secret" and "Issuer URL" fields blank.
  8. In the Allowed Token Audiences, add the Application ID URI that we copied during the application registration.
  9. In the "Additional Checks" section, select "Allow requests from specific client applications" for "Client application requirement".
  10. Click on the edit icon, add the Client ID of "SharePoint Online Client Extensibility Web Application Principal" to the allowed client applications, and then click OK.
  11. Keep the default setting for "Identity requirement."
  12. Choose "Use default restrictions based on issuer" for the Tenant requirement.
  13. Click "Add" to enable authentication on the Function app.
  14. Confirm that the API is correctly secured by opening a new browser window in private mode and navigating to the API.The URL for your Function App can be found in the overview section of the Function App blade. If the authentication settings have been applied correctly, you should be redirected to the Azure AD login page
  15. Add the SharePoint URL "https://contoso.sharepoint.com" to the CORS settings in the Function app.


Why we require SharePoint Online Client Extensibility Web Application Principal Client Id ?

Developers building a SharePoint Framework solution that requires access to specific resources secured with Azure AD list these resources along with the required permission scopes in the solution manifest.

When deploying the solution package to the app catalog, SharePoint creates permission requests and prompts the administrator to manage the requested permissions.

For each requested permission, a global or SharePoint administrator can decide whether they want to grant or deny the specific permission.

When the administrator grants a specific permission, its added to the SharePoint Online Client Extensibility Azure AD application, which is provisioned by Microsoft in every Azure AD and which is used by the SharePoint Framework in the OAuth flow to provide solutions with valid access tokens.

All permissions granted through web API requests are stored with the SharePoint Online Client Extensibility Azure AD application


Call Azure function from SPFx code

  • With the SPFx solution prepared, go to the package-solution.json file located in the config directory. Add the following code to the JSON file.

"webApiPermissionRequests": [
      {
        "resource": "<multitenant-application-name>",
        "scope": "user_impersonation",
        "appId": "<Application Id>",
        "replyUrl": "https://<function app name>/.auth/login/aad/callback"
      }
    ]        

  • Go to the webpart file and add below code in init method.

this.context.aadHttpClientFactory.getClient('<Client ID of multitenant application>').then((client: AadHttpClient): void => {
      const requestOptions: IHttpClientOptions = {
        body: JSON.stringify({
          any value which accepts by your function
        })
      };
      client.post('https://<function app name>/api/getUserPreferences', AadHttpClient.configurations.v1, requestOptions)
        .then((response: any) => {
          return response.json();
        }).then((res: any) => {
          console.log(res);
        })
        .catch((e: Error) => {
          console.log(e);
        })
    }).catch((err: Error) => {
      debugger;
      console.log(err);
    })        


Conclusion

In this guide, we addressed the challenges of setting up a multi-tenant application. We outlined the process for creating the application and configuring Azure Function authentication. We clarified the necessity of the SharePoint Online Client Extensibility Web Application Principal for integration.

Finally, we demonstrated how to call the Azure Function from SPFx code. This setup ensures secure and efficient interaction between SharePoint and Azure.

Nihar Sagar

Evolving with the Tech Tide | Vision. Clarity. Ingenuity. Audacity.

5 个月

Excellent article! It's refreshing to see such interesting insights and solution presented with clarity and depth. Looking forward to more articles like this ??

Aswath Puthur

Infra Technology Specialist for Modern Workplace at Cognizant | Azure | Exchange | Intune | SharePoint | MS Teams | M365 Security | PowerBi | M365 Applications

7 个月

Insightful!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了