Azure App Service Introduction Series – API Apps: CORS

CORS stands for Cross-Origin Resource Sharing. It is a specification that specifies how a web server can allow its resources to be accessed by scripts running inside web pages on another domain.

So saying it another way: by default for security reasons, if you have a client side script inside a web page on domain1.com trying to access a resource (for example a web page or an API) on domain2.com, the browser will simply ignore the response. Read again: the API will send the response; it’s the browser that will ignore it.

Using CORS, the server and client use http headers to make accessing cross-origin resource possible. Where an origin is the combination of scheme (ex: http), host, and port of a URL.

Let’s see CORS in action with our API App.

I have created a client MVC application that calls our published API using JQuery. Here is the JQuery snippet:

1

When I issue the call, the API will reply but the browser will ignore the response. If we examine Fiddler:

2

We see that the request was issued to the API App, and the Origin is the localhost:13548 – which is my client MVC application.

As you can see, the API did reply with the response. However, the browser will just ignore the response because the request was issued from a different origin than that of the resource (in this case the API).

To fix this, go to the Azure portal, and locate the CORS tab for the API App:

3

As you can see, I just supplied the domain of my local application in the allowed origins.

Now when I run the JQuery code again, I see this in Fiddler:

4

The difference is in the response. Now there is an Access-Control-Allow-Origin header which specifies that the client application is allowed to consume the API resource. In this case the browser will allow the response.

Couple of notes:

  • CORS is not the only solution to the cross-origin resource problem. Other alternatives exist such as JSONP. But CORS is the most modern. For example JSONP only supports GET, while CORS supports other verbs such as PUT for example.
  • Not all browsers support CORS. Specifically older browsers do not. Typically all new browser version support CORS however. Review the list of browser support and compare it to your scenario.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s