Configure CORS for APIs secured with Azure AD hosted on Azure

When building APIs that will be used from SharePoint Framework solutions, you have to configure CORS for them. If you're also securing them with Azure AD and host them on Azure, there is one more thing you need to consider.

Calling API on different domain

For security reasons, web browsers don't allow JavaScript scripts running on a web page to call APIs from another domain. Using Cross-Origin Resource Sharing (CORS) policies, APIs can override this behavior and specify which domains are allowed to call them. Whenever a piece of JavaScript issues a web request to an API on a different domain, the web browser contacts the API and evaluates its CORS policies. Based on the CORS settings, the web browser either allows the request or not.

CORS setting in Azure

When building APIs, you can specify their CORS policy directly in their code. This simplifies the deployment of the API and its configuration, but it also requires a new deployment each time the CORS policy needs to be changed. If you're hosting your APIs on Azure App Service, which is the foundation of Azure Functions, Azure API Apps and Azure Web Apps, you can use the Azure Portal to configure the CORS settings for your API instead. Without having to redeploy your code, you can change for example which domains are allowed to call your API or which request types are allowed.

Managing CORS settings for Azure App Service

Enterprise APIs are not anonymous

Most likely your enterprise APIs are secured with Azure AD and, before you can use them, you have to authenticate using your organizational account. Typically, you would use the OAuth implicit flow in your client-side solution to obtain an access token and call the enterprise API. But if your API is secured with the same Azure AD as the one used by your Office 365 tenant, you can also use the existing SharePoint Online authentication cookie, to call your API. There are a number of challenges that you have to deal with in order to implement OAuth implicit flow yourself, so using the existing authentication cookie simplifies things a lot. But there is a catch.

Azure AD, App Services, SharePoint Online authentication cookie and CORS

If you want to use the existing SharePoint Online authentication cookie to authenticate with your API secured with Azure AD, you must clear the CORS settings in the Azure Portal and configure CORS in your APIs code instead.

Delete Azure App Service CORS settings in the Azure Portal

If you configure CORS using the Azure Portal, authentication will fail without giving you any clue why.

This is a known limitation of the Azure Portal which should be fixed in the future.

But for now remember, if you want to call your APIs from the SharePoint Framework and authenticate using the existing SharePoint cookie, clear the CORS configuration for your App Service.

Comments

comments powered by Disqus