Delen via


CORS and Azure API Management

I was working on publishing an API via Azure Mobile Services and I wanted to manage it with API Management. I got everything published and from within the API Management development console everything worked fine. Then I wrote an application to consume the API and that’s where I ran into a problem. It took hours of searching to find the solution so I hope this helps someone else avoid the problem.

CORS stands for Cross-Origin-Resource-Sharing (detailed information can be found at the W3C here). I’ll give it to you in a nutshell here. It is a security mechanism to ensure that data designed to be used for a domain stays in that domain and can’t be used outside of it. In other words it’s a security mechanism. In addition, whether or not you are allowed to access the data is accomplished by a response, not request, header. That means that you cannot make a request to a server for it to serve up data that is protected against CORS. It is the source server that must allow a CORS request.

So, back to the story. I built a small website that retrieved the data from API Management and continued to get a CORS error. I tried everything on the client I could to make it work. I finally found the W3C documentation which pointed me to the server. I checked API Management and I couldn’t find anything on CORS… until I found the Policy tab.

image

Clicking the Policies tab on the left hand side (highlighted) brings us to this screen:

image

On the Policies tab, select the Product, API and specific call. You’ll notice on the right side the CORS policy (as well as others that I would urge you to explore). Put your cursor after the <inbound> tag and above the <base/> tag then click the CORS policy (note that this is an inbound request because the client makes a request of the server and the server sends the response saying yes you can have it). There are some other default CORS options but the way I configured it was to allow requests from anywhere because it was simply a demonstration API.

This should get you past your CORS problem.