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've tracked down:
$http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password);
I've tried:
.config(['$http', function($http) { $http.defaults.headers.common['Authorization'] = 'Basic ' + login + ':' + password); }])
As well as appending it directly to the request:
$http({method: 'GET', url: url, headers: {'Authorization': 'Basic auth'}})})
But nothing works. How to solve this?
$http is an AngularJS service for reading data from remote servers.
To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.
The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.
You're mixing the use cases; instantiated services ($http
) cannot be used in the config phase, while providers won't work in run blocks. From the module docs:
- Configuration blocks - […] Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
- Run blocks - […] Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
So use either of the following:
app.run(['$http', function($http) { $http.defaults.headers.common['Authorization'] = /* ... */; }]);
app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.headers.common['Authorization'] = /* ... */; }])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With