The pain of handling CORS headers

This is a sort of collection of all real-life issues that make usage of cross-origin ajax such a pain the ass.

Favorite reference is the MDN page.

The crucial points are:

  • the server response headers must always mention the OPTIONS method, otherwise all preflighted requests will fail silently
  • using the Authorisation header in the request triggers the preflight
  • client code must explicitly set xhr.withCredentials = true
  • server code must explicitly mention the domains from where it expects to receive requests with credentials
  • if the server uses wildcards in the Access-Control-Allow-Origin header, they will be held valid only for client requests that do not send credentials
  • what else?

Example of client code (http://www.client_site.com/my_page.html):


 $.ajax({
   url: 'http://www.example.com/back-office/list',
   type: 'GET',
   dataType: 'json',
   data: data,
   crossDomain: true,
   xhrFields: { withCredentials: true },
   headers: { 
     "Authorization":"Basic " + btoa(username + ":" + password),
     "Accept":"application/json" 
   },
   success: function(data) { bla bla }
 }

Example of PHP client code (http://www.example.com/back-office/list):


  $response->header('Access-Control-Allow-Origin', 'http://www.client_site.com');
  $response->header('Access-Control-Allow-Methods', 'GET, OPTIONS, HEAD');
  $response->header('Access-Control-Allow-Headers', 'Authorization');
  $response->header('Access-Control-Allow-Credentials', 'true');

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