Azure API Management CORS: Why do I get "Headers starting with 'Access-Control-' were removed..."

csikos.balint picture csikos.balint · Feb 27, 2017 · Viewed 8.9k times · Source

With a simple policy below:

<policies>
    <inbound>
        <cors>
            <allowed-origins>
                <origin>http://microfost.com/</origin>
            </allowed-origins>
            <allowed-methods preflight-result-max-age="300">
                <method>GET</method>
                <method>POST</method>
                <method>PATCH</method>
                <method>DELETE</method>
            </allowed-methods>
            <allowed-headers>
                <header>content-type</header>
                <header>accept</header>
                <header>Authorization</header>
            </allowed-headers>
        </cors>
    </inbound>
</policies>  

HTTP request

OPTIONS https://XXXX.azure-api.net/demo/XXX/XXX/* HTTP/1.1
Host: XXXX.azure-api.net
Ocp-Apim-Trace: true
Ocp-Apim-Subscription-Key: <secret>
Origin: http://microfost.com
Access-Control-Request-Headers: Authorization
Access-Control-Request-Method: GET

Response content

Access-Control-Allow-Origin: http://microfost.com
Ocp-Apim-Trace-Location: <trace>
Date: Mon, 27 Feb 2017 20:09:14 GMT
Content-Length: 0

I get this message and expect Origin response header I do not receive anything for 2 out of 3 APIs (1 API is working with the same policy as expected).

**Inbound**
[...]
cors (0 ms)
"Cross domain request was well formed and was allowed to proceed. CORS related headers were added to the response."

**Backend**

No records.
Outbound

cors (0 ms)
{
    "message": "Headers starting with 'Access-Control-' were removed from the response. ",
    "headers": []
}
transfer-response (0 ms)
{
    "message": "Response headers have been sent to the caller."
}

This seems to me a nonsense behavior and might be a bug. Before submitting it I would like to ask you if there is any explanation? Why do I get this?

Headers starting with 'Access-Control-' were removed from the response.

Answer

Vitaliy Kurokhtin picture Vitaliy Kurokhtin · Mar 1, 2017

There a two ways to do CORS in Azure API Management. Automatic - just drop and configure CORS policy in a desired scope and APIM will take care of responding on OPTIONS requests that match existing operations.

Or you can choose manual way - create a separate operation that responds to OPTIONS method and form response manually right in the policy, possibly using return-response policy.

The problem you're having is because you have both. They're basically in conflict. CORS policy identifies request as cross origin and schedules processing on after request is complete, but return-response policy on OPTIONS operation level breaks this processing pipeline and returns response immediately before CORS policy can take action.

Since you're using CORS policy you should remove OPTIONS operation from your API to make things work.