Configure Azure Function Apps CORS to support custom HTTP headers

Alexandru Scripca 0 Reputation points
2024-07-31T08:36:05.08+00:00

I am running an Azure Function App with HTTP Triggers. I have CORS enabled for it and I have set the Allowed Origins in Azure CORS section. Everything works fine until I make a request from my Web Application and set to submit a custom header with my request. Browser is making a preflight request which retunes a 200, but the headers are empty(there are no Access-Control-Allow* headers) and as a result the subsequent POST request fails with a CORS error.

If I remove the custom header, everything works fine.

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,940 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Chethan 112 Reputation points
    2024-07-31T11:40:11.6566667+00:00

    Hi @Alexandru Scripca

    The issue you are facing is due to the fact that Azure Functions built-in CORS support does not handle preflight requests when custom headers are used. Preflight requests are made by browsers as a security measure to ensure that the server will accept the actual request.
    You need to configure your Azure Function App to explicitly allow the custom headers you are using

    Here’s a workaround for this issue:1. Disable the Azure Functions built-in CORS support.

    1. Implement CORS manually in your Azure Function code Here’s a sample code snippet
          
         // Fetching the name from the path parameter in the request URL
             var response = req.CreateResponse(HttpStatusCode.OK, "Hello World!");
         
             // Define the headers
             response.Headers.Add("Access-Control-Allow-Origin", "*"); // update this to your actual origin
             response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
             response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Your-Custom-Header");
         
             return response;
      
      If this answers your query, do click Accept Answer and Yes for this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.