Wednesday, 20 April 2016

Configuring CORS on apache / httpd

Web development is an area I typically experience the most trauma - and that is no exception when it comes to CORS (or Cross-origin resource sharing).

I was build a pretty simple interface for an API the other day - of which it used basic HTTP authentication and the originating domain was different that that of the API's - hence CORS comes into play.

I spent a good while experimenting with configurations trying to get CORS to function properly with my jquery interface - although kept receiving 401 errors claiming that the request was unauthorized.

The jquery get request was something like follows:

$.ajax
({
  xhrFields: {
    withCredentials: true
  },
  type: "GET",
  url: "http://mydomain.com/api.cgi",
  dataType: 'json',
  async: false,
  username: 'myuser',
  crossDomain: true,
  password: 'mystr0ngpa55w0rd',
  //data: { 'param1': '12345', 'param2': '67890' },
  success: function (){
    alert('Success!');
  },
  failure: function (response, status) {
    alert('Error!');
  }
});
I finally got it working with the following configuration applied on the apache virtual host:

   # CORS configuration for apache
   Header always set Access-Control-Allow-Origin "http://mysource.domain.com"
   Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
   Header always set Access-Control-Max-Age "1000"
   Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
   Header always set Access-Control-Allow-Credentials true

0 comments:

Post a comment