Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to attach an Authorization header to an Ajax request?

I have an ajax GET request I'm firing in a section of Knockout code where I need to ensure the Authorization header is set.

My preference is usually to go with the jQuery shorthand methods like so:

$.getJSON("/api/business", function (allData) {
    var mappedOrgs = $.map(allData, function (item) { return new Business(item) });
    self.businesses(mappedOrgs);
});

This is fine on its own without any auth requirement but if I need to include the bearer token, I've been trying the more long-winded way:

var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
    headers.Authorization = 'Bearer ' + token;
}

$.ajax({
    type: 'GET',
    url: '/api/business',
    headers: headers
}).done(function (data) {
    var mappedOrgs = $.map(data, function (item) { return new Business(item) });
    self.businesses(mappedOrgs);
}).fail(function () { console.error('api call failed'); });

Even trying to force the issue through the $.ajaxSend() method doesn't yield any results.

$(document).ajaxSend(function (event, xhr, settings) {
    var token = sessionStorage.getItem(tokenKey);
    var headers = {};
    if (token) {
        console.info("Found token. Attaching to headers.");
        headers.Authorization = 'Bearer ' + token;
        settings.headers = headers;
        //console.info(headers);
    }
});

So what am I overlooking? I'm checking each request in Fiddler and the Auth header is never attached. There's obviously a right way to do this but I'm missing a step somewhere. Any help appreciated.

like image 542
Phil.Wheeler Avatar asked Sep 27 '22 09:09

Phil.Wheeler


1 Answers

i use the following:

function getListData(url) {
    var d = new $.Deferred();
    cfg.apiLoad();

    $.ajax({
        url: baseUrl + url,
        type: 'GET',
        headers: { "x-access-token": secure.getToken(), "x-access-finger": finger.getFinger() },
        dataType: 'json'
    }).fail(function(a, b, c) {
        cfg.failError(c);
        d.reject(c);
    }).done(function (r) {
        cfg.apiDone(r);
        d.resolve(r.ListResults);
    });

    return d.promise();
}

you can add as many extra headers on there that you wish, ignore the cfg. stuff, but this is in a network file, as in write once, use everywere with
getListData('/api/Name/Endpoint').then(function(r){ '// do something});

this then solves any issues with having to repeat etc and works like a charm. my API returns the same model back for any type of results

like image 140
davethecoder Avatar answered Oct 12 '22 23:10

davethecoder