I have an angular application that is hitting a node API. Our backend developer has implemented basic auth on the API, and I need to send an auth header in my request.
I have a service factory that has an angular request interceptor like so:
var module = angular.module('MyAuthServices', ['ngResource']);
module
.factory('MyAuth', function () {
return {
accessTokenId: null
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('MyAuthRequestInterceptor');
})
.factory('MyAuthRequestInterceptor', [ '$q', '$location', 'MyAuth',
function ($q, $location, MyAuth) {
return {
'request': function (config) {
if (sessionStorage.getItem('accessToken')) {
console.log("token["+window.localStorage.getItem('accessToken')+"], config.headers: ", config.headers);
config.headers.authorization = sessionStorage.getItem('accessToken');
}
return config || $q.when(config);
}
,
responseError: function(rejection) {
console.log("Found responseError: ", rejection);
if (rejection.status == 401) {
console.log("Access denied (error 401), please login again");
//$location.nextAfterLogin = $location.path();
$location.path('/init/login');
}
return $q.reject(rejection);
}
}
}]);
Then on logging in in my login controller I store the accesstoken using this line:
sessionStorage.setItem('currentUserId', $scope.loginResult.user.id);
sessionStorage.setItem('accessToken', $scope.loginResult.id);
sessionStorage.setItem('user', JSON.stringify($scope.loginResult.user));
sessionStorage.setItem('userRoles', JSON.stringify($scope.loginResult.roles));
This way I can assign the headers to the request on every request made after I log in. This is just the way I do it, and is totally up for criticism, but it appears to work very well.
In the $http doc you can see that you should set the default headers using $httpProvider:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Basic auth';
}]);