When I use $resource for a REST login, the transformRequest doesn't add the Authorization header as intended. Using a $.ajax call it does work as intended. So using:
$scope.login2 = function() {
function setHeader(xhr){xhr.setRequestHeader("Authorization", "Basic " + btoa($scope.gebruikersnaam + ':' + $scope.wachtwoord))}
$.ajax({type: "POST", url: "http://localhost:8000/authview/", beforeSend: setHeader}).
fail(function(resp){
console.log('bad credentials.')
}).
done(function(resp){
console.log('welcome ' + resp.email)
})
}
I get the authorization header added to the request:
Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
But when doing:
$scope.login = function() {
api.auth.login($scope.getCredentials()).
$promise.
then(function(data){
// on good username and password
$scope.gebruikersnaam = data.username;
}).
catch(function(data){
// on incorrect username and password
alert(data.data.detail);
});
};
where "api.auth.login" is defined like:
kmregistratieApp.factory('api', function($resource){
function add_auth_header(data, headersGetter){
var headers = headersGetter();
headers['Authorization'] = ('Basic ' + btoa(data.username + ':' + data.password));
}
return {
auth: $resource('http://localhost:8000/authview/', {}, {
login: {method: 'POST', transformRequest: add_auth_header},
logout: {method: 'DELETE'}
}),
users: $resource('http://localhost:8000/authview/', {}, {
create: {method: 'POST'}
})
};
});
After "headers['Authorization'] = ('Basic ' + ..." (when debugging) I can see it sitting in headersGetter:
headers: Object
Authorization: "Basic YWRtaW46cGFzc3dvcmQ="
accept: "application/json, text/plain, */*"
content-type: "application/json;charset=utf-8"
But it doesn't turn up in the Network tab when inspecting the headers. So my question is why doesn't the $resource way of working not add the Authorization header?
TransformRequest is not meant to be used to modify headers. See AngularJS changelog. Scroll a bit downwards and you will see this:
HTTP headers can only be specified when using $http. Example: