Search code examples
jqueryajaxcross-domainbasic-authentication

Cross-domain JSON request with BasicAuth


I am developing a website example.com, with an API api.example.com. For now, the website and its API are protected by BasicAuth with an username and a password.

I don't manage to make an AJAX call (I use jQuery) from the website to its API. I tried all I found on the web to add BasicAuth parameters to the call, but nothing works. When I inspect what is going on on the network with Chrome, I find that no headers are submitted, and that the request method is not GET but OPTIONS.

Here is the last thing I tried:

$.ajax({
    url: 'api.example.com/users.json',
    beforeSend: function(xhr) {
        var base64 = btoa(username + ":" + password);
        xhr.setRequestHeader("Authorization", "Basic " + base64);
        xhr.withCredentials = true;
    },
    success: function(data) {
        users = data;
        displayUsers();
    }
});

Could you help me please?


Solution

  • I needed the field xhrFields:

    $.ajax({
        url: 'api.example.com/users.json',
        xhrFields: {
          withCredentials: true
        },
        success: function(data) {
            users = data;
            displayUsers();
        }
    });