Fotis Adamakis
Fotis Adamakis

Reputation: 284

Ajax authentication with jQuery

I'm able to recieve the requested xml with

curl -X GET -u username:password url

but not with

$.get('url',
        {username:"username",password:"password"},
        function (data) {


        });

No javascript errors, no cross domain policy issues. It might be a syntax error but I failed to find a decent tutorial yet. Any suggestions please?

Upvotes: 6

Views: 52641

Answers (3)

Stuart Hallows
Stuart Hallows

Reputation: 8953

As an alternative to beforeSendyou could use the headers property to add the authorization header.

$.ajax({
    type: 'GET',
    url: 'url',
    dataType: 'json',
    headers: {
        "Authorization": make_base_auth(user, password)
    }
    success: function () {});
});

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148514

I think you'd need the plain format :

$.ajax({
    type: 'GET',
    url: 'url',
    dataType: 'json',
    //whatever you need
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth(user, password));
    },
    success: function () {});
});

function make_base_auth(user, password) {
    var tok = user + ':' + password;
    var hash = btoa(tok);
    return 'Basic ' + hash;
}

Upvotes: 23

Satish
Satish

Reputation: 6485

As pointed in the other answer, you should be using beforeSend function of Jquery Ajax to add authorization header

function setAuthHeader(xhr){
            var creds = username + ':' + password;
            var basicScheme = btoa(creds);
            var hashStr = "Basic "+basicScheme;
            xhr.setRequestHeader('Authorization', hashStr);
    }

  $.get('url',
         beforeSend: setAuthHeader,
        function (data) {


     });

Upvotes: 1

Related Questions