Monday, May 22, 2023

Enabling CORS in Locally Running In-Process Azure Function

In this post, let's see how we can enable CORS in locally running In-Process Azure Function. 

I had a simple In-Process HTTP Trigger Azure Function that exposes SignalRConnectionInfo. When running locally, a web app that is again running locally is failing to call the endpoint. The fetch request to the HTTP endpoint (http://localhost:7071/api/negotiate?negotiateVersion=1) is getting the status CORS error.
CORS Error
But when I sent a cURL request to the endpoint, it's working fine. When deployed to Azure, again everything is working as expected (after updating CORS policies of course).

So something fishy was going on.

In Azure Functions Core Tools, when you are starting a function app, luckily you can configure CORS options.
func --help
So what I did was, modify launchSettings.json by adding commandLineArgs as follows (I was using Visual Studio). 
{
  "profiles": {
    "FunctionApp": {
      "commandName""Project",
      "commandLineArgs""--cors https://tenant1-dev20.localhost:4200 --cors-credentials true",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT""Development"
      }
    }
  }
}
The key things here to get it to work are, 
  • --cors: Don't specify star (*). Instead, provide comma-separated CORS origins with no spaces
  • --cors-credentials: Set this to true
And that did it.
CORS Working
More information:

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment