How can I customize CORS policy response

Lily 116 Reputation points
2024-05-02T06:55:44.5566667+00:00

Hi,

We're testing the CORS policy and need to know if it's possible to customize the response code/body.

<cors allow-credentials="false" terminate-unmatched-request="true">
  <allowed-origins>
    <origin>origin uri</origin>
  </allowed-origins>
</cors>

When the request doesn't match allowed origins under terminate-unmatched-request="true", the response is a 200 with an empty value.

User's image

Our client finds this confusing; it's hard to tell if the empty response indicates normal operation or a CORS block.

Can you advise if we can customize the response? Thank you.

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

1 answer

Sort by: Most helpful
  1. Ryan Hill 27,111 Reputation points Microsoft Employee
    2024-05-07T20:10:57.8066667+00:00

    Hi @Lily,

    I know APIM does allow conditionally overriding header values. You may be able to use the set-body policy to override as well.

    <cors allow-credentials="false">
        <allowed-origins>
            <origin>https://test.org</origin>
        </allowed-origins>
    </cors>
    <choose>
        <when condition="@(context.Request.Headers.GetValueOrDefault("Origin","").Contains("allowedOrigin.com"))">
            <set-body template="none" />
        </when>
        <otherwise />
    </choose>
    

    However, what I suggest is setting terminate-unmatched-request to false, per Scenario 7: terminate-unmatched-request on https://techcommunity.microsoft.com/t5/azure-paas-blog/how-to-troubleshoot-cors-error-in-azure-api-management-service/ba-p/2241695

    0 comments No comments