Search code examples
javascriptajaxjquerybasic-authenticationhttp-authentication

jQuery ajax basic authentication is not working


I am trying to make jQuery AJAX request to some basic http authenticated url. here is my jQuery code:

jQuery.ajax({
  url: "https://abc.com/houses/1/appliance_hints",
  method: 'GET',
  cache: false,
  crossDomain: true,
  beforeSend: function(xhr){
    xhr.setRequestHeader('Authorization', 'Basic Z3NsYWI6cGFzczFnczFhYg==');
  },
  success: function(result){
    alert(result);
  }
});

I am setting request header 'Authorization' here. But here is what i see in request header in FF

Host    <host>
User-Agent  Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Origin  <origin>
Access-Control-Request-Me...    GET
Access-Control-Request-He...    authorization,x-requested-with

Am i doing anything wrong ? I am getting status code 302 in the response. Is there any server side configuration error ?


Solution

  • I've noticed you've added crossDomain: true to you $.ajax call, so I think you are trying to fetch something from a remote domain?

    Anyway to main problem you have is that you violate the Same origin policy.

    If you have control over the remote_url (in your example case abc.com) you could set it to send some header to allow these calls.

    example:

    Access-Control-Allow-Origin: http://permitted_domain.com
    

    php examples:

    header('Access-Control-Allow-Origin: http://permitted_domain.com');
    // or to allow all
    header('Access-Control-Allow-Origin: *');