How to customize response body for CORS terminate-unmatched-request in Azure APIM

Glenn Tan 0 Reputation points
2024-07-31T16:41:46.79+00:00

Is it possible to change the empty response body returned by the CORS terminate-unmatched-request behavior in Azure API Management? I would like to return a custom message instead. I have searched for solutions, but I haven't found anything that works.

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,175 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. hossein jalilian 8,150 Reputation points
    2024-07-31T18:59:32.57+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    It is not possible to directly customize the response body for the CORS terminate-unmatched-request behavior in Azure API Management.

    By setting terminate-unmatched-request attribute to false in your CORS policy, APIM will allow the request to proceed normally without adding CORS headers to the response.

    You can use a combination of the CORS policy and other policies like <choose> and <set-body> to achieve your desired result.

    <cors allow-credentials="false" terminate-unmatched-request="false">
      <allowed-origins>
        <origin>https://allowed-origin.com</origin>
      </allowed-origins>
    </cors>
    <choose>
      <when condition="@(context.Request.Headers.GetValueOrDefault("Origin","") != "https://allowed-origin.com")">
        <return-response>
          <set-status code="403" reason="Forbidden" />
          <set-body>{"error": "CORS policy violation: Origin not allowed"}</set-body>
        </return-response>
      </when>
    </choose>
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is 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.