Labithiotis
Labithiotis

Reputation: 4129

jQuery Basic Auth error sending credentials

Having an issue where I "think" the credentials aren't being set even though there specified in beforeSend. It's all setup to be dynamic, including headers and basic auth (it's for api docs).

Basic auth is being passed in fine i.e : "Basic XXXXXXXX"

Server has Access-Control-Allow-Origin "*"

var $button = $(this).button('loading'),
    $parent = $(this).parents('.api-test-response:first'),
    $data = $('.api-test-data',$parent),
    headers = {};

 $('.api-test-headers tr',$parent).each(function(){
     if($('.header-toggle', this)[0].checked && $('input.api-test-header-key',this).val() != ""){
         headers[$('input.api-test-header-key',this).val()] = $('input.api-test-header-value',this).val();
     }
 });

 $.ajax({
  async: false,
  cache: false,
  crossDomain: true,
  headers: headers,
  beforeSend: function(xhr) {
    if(headers['Authorization']){
      xhr.withCredentials = true;
      xhr.setRequestHeader('Authorization', headers['Authorization']);                           
    }
    return true;
  },
  url: this.dataset.url,
  method: this.dataset.method || 'get',
  dataType: this.dataset.type || 'json',
  data: $data[0] ? $data[0].value : '',
  success: function(data, status, jqXHR){
    $('pre', $parent).removeClass('hide').find('code').html( !data ? status : data instanceof Object ? syntaxHighlight(data) : data );
  },
  error: function(jqXHR, status, error){
    $('pre', $parent).removeClass('hide').find('code').html( '<div class="badge badge-important">'+ jqXHR.status +'</div> ' + (jqXHR.responseText != '' ? jqXHR.responseText :  status + ' ' + error) );
  }

})
  .always(function (jqXhr) {
      $button.button('reset');
      $("body").scrollspy('refresh');
  })

Error from chrome :

OPTIONS URL 401 (Unauthorized)
XMLHttpRequest cannot load URL. Invalid HTTP status code 401

Response : No Authorisation Provided 

Upvotes: 1

Views: 306

Answers (1)

Labithiotis
Labithiotis

Reputation: 4129

Turns out to be an issue with browser preflight request (options) not contain auth header information and thus being failed by the java service. Resolved the issue by catching and ignoring options request.

Upvotes: 1

Related Questions