Cross-domain ajax request basic authentication

28,049

Solution 1

Pass username and password like following code,

$.ajax({
    type: "GET",
    xhrFields: {
        withCredentials: true
    },
    dataType: "jsonp",
    contentType: "application/javascript",
    data: myData,
    async: false,
    crossDomain: true,
    url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
    success: function (jsonData) {
        console.log(jsonData);
    },
    error: function (request, textStatus, errorThrown) {
        console.log(request.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
    username: username,
    password: password,
});

Solution 2

$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});
Share:
28,049
mike44
Author by

mike44

Updated on June 24, 2021

Comments

  • mike44
    mike44 almost 3 years

    I'm making cross-domain ajax request to get some data. The REST service have Basic authentication (set through IIS).

    $.ajax({
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataType: "jsonp",
                contentType: "application/javascript",
                data: myData,
                async: false,
                crossDomain: true,
                url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
                success: function (jsonData) {
                    console.log(jsonData);
                },
                error: function (request, textStatus, errorThrown) {
                    console.log(request.responseText);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
    

    When I make this request, it prompts me to enter credentials & I have to manually enter credentials to get the response. Can we send those credentials through the request itself?

  • Dave Newton
    Dave Newton over 9 years
    I'm not excited about this answer, and here's why: it's redundant (question was answered about a half-year earlier) and it's redundant (jQuery handles the auth stuff for you, AFAICT). If I'm wrong about the latter, edit the answer, and I'll delete this comment.
  • rodrigobartels
    rodrigobartels over 7 years
    Using the beforeSend property worked for me, since username and password for some reason weren't adding the Authorization header. Just in case it helps anyone.