10

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?

mike44
  • 802
  • 5
  • 15
  • 36

3 Answers3

6

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,
});
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
5
$.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));             
    }
});
Rick Pastoor
  • 3,625
  • 1
  • 21
  • 24
Adith
  • 177
  • 2
  • 6
  • 2
    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. – Dave Newton Nov 15 '14 at 22:26
  • 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. – rodrigobartels Feb 01 '17 at 17:08
0
$.ajax({//No need to pass credentials 
            type: "get",
            async: false,
            url: "https://someurl/",
            xhrFields: {
                withCredentials: true
            },            
            success: function (data) {
                //do something
            }
        })
Ankita Singh
  • 579
  • 6
  • 7