Cross-Origin Resource Sharing (CORS) allows a user agent gain permission to access a web- or REST service from a server on a different domain than the site currently in use.
Modern browsers does not allow websites with Javascript that calls external URL’s. Unless you have CORS configured, you will experiences a Cross Site Scripting error.
Microsoft Azure API Management also supports CORS. When setting up CORS you set up the following:
- Inbound rules:
- Configure the URL’s that are allowed to call your service
- Configure the allowed methods (GET, PUT, POST, …)
- Configure the allowed headers
- Outbound rules:
- Add Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers to the response.
So in the Azure API Management publisher portal, go to Policies, select the Product and API to configure and select “Configure Policy”:
Add CORS to the inbound rules and set the headers in the outbound rules:
<policies> <inbound> <base /> <cors allow-credentials="true"> <allowed-origins> <origin>http://website1.com</origin> <origin>http://website2.com</origin> </allowed-origins> <allowed-methods> <method>GET</method> </allowed-methods> <allowed-headers> <header>content-type</header> <header>accept</header> </allowed-headers> </cors> </inbound> <backend> <base /> </backend> <outbound> <base /> <set-header name="Access-Control-Allow-Origin" exists-action="override"> <value>@(context.Request.Headers.GetValueOrDefault("Origin",""))</value> </set-header> <set-header name="Access-Control-Allow-Credentials" exists-action="override"> <value>true</value> </set-header> </outbound> <on-error> <base /> </on-error> </policies>
Configuration breakdown:
- Inbound:
- CORS allow-credentials=true allows API Management to accept credentials
- The allowed-origins is a list of origins that have access to your service. You can add as many domains as you like.
- Allowed-methods lists the methods you allow
- Allowed-headers lists the headers you allow
- Outbound:
- The 2 headers Access-Control-Allow-Origin and Access-Control-Allow-Credentials are set in the header. This code automatically adds the calling domain to the Access-Control-Allow-Origin header.
The cool part of this configuration is that you not only allow cross scripting, but you also control which domains have access to your service. If you call the API Management endpoint from a Restlet or POSTMAN Client you get the following error:
{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }
MORE TO READ:
- Cross-Origin Resource Sharing (CORS) from Mozilla
- API Management policy expressions from Microsoft
- https://cors.io/ a nifty CORS tester