Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a JSON web service, that requires basic authentication, using jQuery?

I am somewhat novice at javascript, but I am trying to call a JSON web service that require basic authentication using jQuery (or anything that would work really).

I've not been able to come up with any real answers on Google. Is what I am trying to do possible?

like image 801
aceinthehole Avatar asked May 17 '11 02:05

aceinthehole


People also ask

Is API basic authentication?

With Basic Authentication, you pass your credentials (your Apigee account's email address and password) in each request to the Edge API. Basic Authentication is the least secure of the supported authentication mechanisms. Your credentials are not encrypted or hashed; they are Base64-encoded only.

What is authentication in JavaScript?

Authentication JavaScript is nothing but JavaScript using the client ID to obtain Google ID token through Google Auth 2.0 server and then sending this generated token in request calls. Then the endpoint framework use client ID for authenticating the token ID that the JavaScript application has sent.


2 Answers

You will need to set the appropriate request header to pass the credentials. For example see here.

$.getJSON({
    'url': 'http://host.com/action/',
    'otherSettings': 'othervalues',
    'beforeSend': function(xhr) {
        //May need to use "Authorization" instead
        xhr.setRequestHeader("Authentication",
            "Basic " + encodeBase64(username + ":" + password)
    },
    success: function(result) {
        alert('done');
    }
});

FYI I searched Google for jquery post with basic auth and this was the first link.

like image 174
mellamokb Avatar answered Sep 23 '22 16:09

mellamokb


Here's the way to do it with jQuery for your copy and pasting needs:

$.ajax({
    url: "/somewhere",
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
    },
    success: function(result) {
        console.log(arguments);
    }
});
like image 38
Philipp Gayret Avatar answered Sep 23 '22 16:09

Philipp Gayret