How to make DataTable ajax work using Bearer Authorization?
How to make DataTable ajax work using Bearer Authorization?
After 3 days troubleshooting, I've decided to ask the question in this forum. I've tried many ways after reading multiple blogs and discussions here without any luck. The following partial code will work using Basic Authorization, but it will not work when attempting to use Bearer Authorization.
Sample using Basic Authorization
var dt = $('#snowincidentstable').DataTable({
"ajax": {
"processing": true,
"serverSide": true,
"url": snowQueryUrl,
"dataSrc": "result",
"dataType": "json",
"type": "GET",
"crossDomain": true,
"beforeSend": function (xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + btoa('username' + ':' + 'password'));
}
},
rowGroup: {
startRender: null,
endRender: function (rows, group) {
return group + ' (' + rows.count() + ')';
},
dataSrc: 'caller_id'
}
});
Sample using Bearer Authorization
var dt = $('#snowincidentstable').DataTable({
"ajax": {
"processing": true,
"serverSide": true,
"url": snowQueryUrl,
"dataSrc": "result",
"dataType": "json",
"type": "GET",
"crossDomain": true,
"beforeSend": function (xhr) {
xhr.setRequestHeader("Authorization",
"Bearer " + token;
}
},
rowGroup: {
startRender: null,
endRender: function (rows, group) {
return group + ' (' + rows.count() + ')';
},
dataSrc: 'caller_id'
}
});
This question has an accepted answers - jump to answer
Answers
"it will not work" doesn't give much to work with. Are you seeing error messages? Have you done any debugging?
My bad, yes...I've done a lot of troubleshooting. I'm getting Status Code: 401 Unauthorized in the Header when debugging using Chrome. And DataTables warning: table id=snowincidenttable - Ajax error. For more information about this error, please see http://datatables.net/tn/7. See attachment for additional details.
Maybe you need to use POST instead of GET?
You could try setting the header directly instead of see the third post here.
The
ajax
option docs state this:So you can use normal jQuery Ajax() options to configure the authentication the way you need. Read through the Ajax Object type docs for the specifics.
Kevin
Thank you Kevin, let me try that.
It was embarrassing to realized that I was getting the token from DEV instance, then trying to request data using that token in TEST instance )-:. So, the approach above to setup the Bearer Authorization does work, thank you very much again for your help and quick reply.
"beforeSend": function (xhr) {
xhr.setRequestHeader("Authorization",
"Bearer " + token;
}