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
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.
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.
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.
FYI on the allows-credentials with CORS thing. It's not supported if you use the portal CORS feature, but if you disable it (by removing all the domains there), you can handle CORS inside your code and customize it. Sample: https://t.co/vUmJ1gOvKR— Chris Anderson 🌌 (@crandycodes) April 25, 2018
I raised this issue recently with the team. I'll end up bringing it up again after //build is done and things are less busy here.— Chris Anderson 🌌 (@crandycodes) April 25, 2018
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.