Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using http basic authentication with Ajax call

I need to contact a server to consume a HTTP service.

Trying to reach the service with the browser, using https://example.com/service I get the basic authentication dialog.

Changing the URL to https://username:[email protected]/service easily bypasses that.

Trying to do the same using Ajax always results in 401 Unauthorized though:

$.ajax({
    url: 'https://username:[email protected]/service',
    // rest repeats
    type: "GET",
    async: true,
    success: function(text) { alert('success'); },
    error: function (text) { alert('error') },
    complete: function(text) { alert('complete'); }
});
$.ajax({
    url: 'https://example.com/service',
    username: username,
    password: password,
    // snip repeat
});
$.ajax({
    url: 'https://example.com/service',
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic "
            + btoa(username + ":" + password));
    },
    // snip repeat
});
like image 697
Ste Avatar asked Jan 12 '15 14:01

Ste


People also ask

Can we use HTTP GET or POST for AJAX calls?

HTTP Request: GET vs. POSTGET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

How can I pass the basic HTTP authentication?

We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.


1 Answers

I struggled with a similar scenario myself.. What did the trick was using jsonp (ugh):

$.ajax({
        url: "https://localhost:8443/v1/accounts",
        type: 'GET',
        dataType: 'jsonp',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
        }
    })
like image 63
Lucas Leite Avatar answered Sep 20 '22 19:09

Lucas Leite