How to make CORS-friendly API

In this blog we will explore how to use API keys to enable Cross-Origin Resource Sharing (CORS)

API Keys are unique string (usually random number). An API key identifies a particular client that consumes the API. A client can be a web-based application or a native client.

An API key is generally generated on request of the client developer to consume the API. Normally, there is a control panel, where the API developers logs in and request to create a new “application”. The developer inputs the domain(s) on which the web-app will be hosted and submits the form. As a result, an API key is generated.

There are plenty of online resources that describe CORS in details, so I won’t go in much details.

CORS

CORS stands for Cross-Origin Resource Sharing. Its a security-mechanism built into the browsers to ensure that only authorized websites are allowed to call a web-service. Normally website hosted on one domain needs to call web-service hosted on another domain. Unless the server, allows that domain to make API calls, this is rejected.

The CORS mechanism is implemented by client sending some HTTP headers in the request and performing certain operations when different headers are received by the client.

When calling an API in cross-origin mode, an extra header is added with the request to identify the domain from where the client-app is loaded from. The header name is “Origin”. This is done automatically by the browser, if an HTTP request is made to some domain, which is different from the domain the app is loaded.

Some of the more important headers are as follows:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers
  • Access-Control-Expose-Headers

Details of these headers can be found here and here

The important point to note that CORS is implemented in the client browser. The client does not know if the request is allowed untill it gets the headers in response. So from the server point-of-view, a request is received and a response is sent. It is, when the response is received on the client, it is checked whether the request was approved or not and act accordingly.

It is also important to note that there are two types of requests, normal and pre-flight. More information on this is available here

This part builds on the previous tutorials. We will do the following steps

  • Create migration
  • Add migration code Code here
  • Run the migrations
  • Create models using gii: Apikey and Origin
  • Add relation in Origin model
  • Add class in directory. Code here
  • Add event handlers. Code here

We can now create an API key and add as one of the allowed origins. We can use this fiddle to make an API call.

Additional Resources

HTML5 Security Cheatsheet — CORS

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.