Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 Authentication on Ajax API call

Tags:

jquery

ajax

I'm trying to get a basic API call to work however the API provider does not offer any developer support. They require that each call send in a base64 basic authentication header. When I use their online API testing utility my keys are valid but I can not get it to work within my own code or in a JSFiddle.net. I even tried to copy the "Authentication: Basic ...." value that is returned from the testing utility within my code and that did not work.

I have looked at numerous examples within Stackoverflow and I use similar code for other APIs with no problem. The base64 basic auth is new to me and when I run the code in IE the debugger states a syntax error which I can't find. I was expecting a 401 error if any error was to occur.

Any thoughts on the error or additional ways to debug it?

$(document).ready(function() {
    var mySecret = "somevalue";
    var myClientId = "somevalue";
    $.ajax({
        url: "https://www.udemy.com/api-2.0/courses/",
        type: 'GET', 
        dataType: "json", 
        contentType: "text/plain",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Basic " + btoa(myClientId+":"+ mySecret));
        },
        success: function(data) {
            alert("hi");
        }
    }); 
});
like image 843
BlackBerry Special Avatar asked Jul 10 '15 19:07

BlackBerry Special


2 Answers

What you've probably got here is a problem with CORS or Cross Origin Resource Sharing. It prevents sites from arbitrarily making requests to willy nilly. The reasons for it are complicated, but it keeps you safe! Although, it's a major pain.

Fire up your handy dandy Chrome Dev Tools and take a look at what's actually happening to that network request. It definitely doesn't work in JSFiddle because of the same-origin policy (CORs).

You can get the JSON in the Browser because that's not a Cross Site Request. Look at which headers are being sent back and forth, and see if there's a way in your Udemy API portal to set an acceptable Origin for the Allow-Origin header. Your IP address probably if you're working locally.

like image 108
Breedly Avatar answered Oct 07 '22 17:10

Breedly


You can encode like this:

var header = {"Authorization": "Basic " + btoa(username + ":" + password)};

Add the header to the ajax call like this:

$.ajax({
    url: "https://www.udemy.com/api-2.0/courses/",
    type: 'GET', 
    dataType: "json", 
    contentType: "text/plain",
    header,
    success: function(data) {
        alert("hi");
    }
}); 

This works for me anyways. You'll need CORS too as suggested.

like image 25
Martin Verner Avatar answered Oct 07 '22 17:10

Martin Verner