Azure Functions Access-Control-Allow-Credentials with CORS

There is a known issue documented on GitHub here with a title of Cross origin http request CORS fails with response header missing ‘Access-Control-Allow-Credentials: true’.  Although the issue described and a solution provided, I thought I would write up what I did as I use C# and didn’t see any examples of that, so here goes.

Description

I expect this to be temporary as you see in the GitHub article the solution is in the backlog.  I just learned a lot about these features Azure Functions and CORS while working on this issue and wanted to document my learning.

When a client sends an Origin header to the server, the client would expect a result with the Access-Control-Allow-Origin header with a value of the allowed origin, if it matches the supplied Origin from the client.  Figure 1.

image

Figure 1, Access-Control-Allow-Origin and Access-Control-Allow-Credentials with an Azure Function

This is what CORS is Cross-Origin Resource Sharing.  Sometimes you need to add an additional header called Access-Control-Allow-Credentials in addition to the Access-Control-Allow-Origin header.  Issue is, if you update your code to add that header it does not make it to the client from the Azure Function unless you remove all the allowed origins from the CORS list.  But, if you remove all the allowed origins from the CORS blade in the portal then you cannot run the function from within the portal.  If you remove all the CORS values, you will see an error like that in Figure 2.

Error:  CORS is not configured for this function app.  Please add https://functions.azure.com to your CORS list.  Session Id:  Timesatmp:

image

Figure 2, Access-Control-Allow-Origin and Access-Control-Allow-Credentials with an Azure Function

If you add the headers to the Azure Function like this and remove all the allowed origins, then you will get the headers, Figure 3.

...
var origin = req.Headers.GetValues("Origin").FirstOrDefault();
...
  var response = req.CreateResponse(HttpStatusCode.OK, "Hello " + name);


if (req.Headers.Contains("Origin"))
{
    response.Headers.Add("Access-Control-Allow-Credentials", "true");
    response.Headers.Add("Access-Control-Allow-Origin", origin);
    response.Headers.Add("Access-Control-Allow-Methods", "GET, OPTIONS");
}
return response;
...

image

Figure 3, Access-Control-Allow-Origin and Access-Control-Allow-Credentials with an Azure Function

Solution

Until the official solution is provided you need to determine if this workaround works for you or not.

You can use the Visual Studio Tools for Azure Functions which I discuss here.

Then you can troubleshoot and test your Azure Function locally which I discuss here.

curl -H "Origin: https://www.contoso.com" -G http://localhost:7071/api/SayHello?code=1cee54a4238f471fa4d6dca74c2807bc -d name=Benjamin -v