Has anyone come up with an assertion for handling CORS on the gateway? I'd like to relieve my backend services from having to handle this aspect. I can easily push headers into the response and wrap it around some logic to detect the HTTP verb, but I'm wondering if someone has done something a little more elegant OR if anyone sees handling CORS on the gateway as "bad practice". Thoughts?
I have had a couple of CORS support requests from some projects where CORS was completely necessary and indeed, as you mentioned, I have simply added the needed headers to the response,
I personally do not think there is an 'APIM worst practice' around it: it depends on the project's need, but I do surely allign the CORS best practices to this: try and be as less general about the domains that the API can be called by (if you see what I mean), don't just allow from any hosts. This would be my suggestion.
and also for the methods allowed, restrict them to the essentials.
Apart from that, I see no issue
I hope this helps
We have created a policy fragment for our RESTful APIs which handles, amongst other stuff, CORS on the gateway. Please have a look at the attached policy (API Policy and Policy Fragment (ApiPolicyWithCORS)). Note: Enable comments for explantions of the various steps. At the end, this policy allows us to configure the CORS behaviour per API policy but still using one generic fragment for all API policies...
In a nutshell what the policy does:
- Check if it's a "normal" API request or a CORS preflight request
- Normal API request:
-- Check if it's a simple CORS request
-- Validate incoming simple CORS headers and set response CORS headers (for error messages)
-- Perform steps necessary for API policy (only routing in the attached sample policy)
-- Set CORS response headers (for api responses from the backend)
- Preflight CORS request:
-- Validate incoming CORS preflight headers and set response CORS headers
There is a Knowledge Article on CA Supportal on CORS implementation. I have used this successfully. Attached is the documentation and the supporting policy from the supportal, in case you do not have access. Please do let me know if you have any queries in implementation.