How can I make $http with authentication? - angularjs

I have make a POST request to an API and they have basic authentication, how can I tell angular $http POST service to pass my credential while making the post requestion?

You can add auth interceptor as follows
angular.module('interceptors.authInterceptor',[])
.factory('authInterceptor', ['$q', function ( $q) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers['Authorization'] = 'Bearer ' + YOUR_AUTH_TOKEN;
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function(rejection) {
}
};
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}]);

Related

How to override header Token with AngularJS

I have problem to override header token with AngularJS becauase already set with AuthInterceptor.
app.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if (localStorage.getItem("token")!=='') {
config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
}
return config;
},
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
I would access another third party URL where using another Token,but always failed, because Token back to current Token in localStorage. I have used TransformRequest, but not work too, what is best practice to solve the problem?
You could check that the URL in the intercepted request is a URL that you want to pass an authorization token. For instance, if the URL to your own API always starts with https://api.myapp.com, you could do it like this:
app.factory('authInterceptor', function ($rootScope, $q, $window) {
var urlForAuthorization = 'https://api.myapp.com';
return {
request: function (config) {
config.headers = config.headers || {};
if (config.url.startsWith(urlForAuthorization)
&& localStorage.getItem("token") !== '') {
config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
}
return config;
}
};
});

angular auth interceptor on selected request

I have written an auth interceptor that adds auth token to the request and handles auth errors if the user is not logged in.
var storeApp = angular.module('storeApp');
storeApp.factory('authInterceptor', function ($q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401 || response.data.error === 'token_not_provided') {
console.log('auth error');
}
return $q.reject(response);
}
};
});
storeApp.config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('authInterceptor');
});
The issue is the auth interceptor is added to every request, regardless the request requires authentication or not. What is the best way to create an auth interceptor that only intercepts when the route requires authentication?
You need the filter out the requests you want in the authInterceptor factory methods
['/whatever/1', '/whatever/2', '/whatever/3'].forEach(function(value){
if (response.config.url.startsWith(value)) {
// do something
}
})
return response;

Skip transformation in $http response in case of error

I have an $http service that make an API call and I have a transformResponse and error interceptor both attached to every call. In case of errors I can see that transform response gets called first, then followed by an interceptor. I do not want the transformation method to be called for error responses, I want it to skip right to the interceptor. How can I achieve that?
I know that I can put if (response.status != 200) into every transformation method, but I have a lot of these methods and I do not want to do that in each of them.
You probably need to go for Interceptors to play with request response in general.
myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
}
return response || $q.when(response);
}
};
});
myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
Perhaps it will also be useful
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.transformResponse.unshift(
function (data, headers) {
/* some code*/
return data;
});
}])

Interceptor in Angular, only for some calls?

I have the following factory in my Angular App. It is used to add bearer token information, to the header of all my outgoing request with $resource. It works as expected.
But i have implemented some external calls, which should not be added with the bearer token. How do i implement a check, so i can control what calls are getting intercepted and which are not?
My code:
.factory('authInterceptor', [
"$q", "$window", "$location", "currentUser", function ($q, $window, $location, currentUser) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + currentUser.getProfile().token;
return config;
},
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
// error handler
}
};
}
])
Add the authInterceptor:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}])
Factory for a resource:
myApp.factory('Random', function ($resource) {
return $resource('domain.com', { }, {
update: {
method: 'PUT'
}
});
});
Call the resource:
Random.query({ });
Any ideas?
There are many ways, for example, you can do something in the request object,
.factory('authInterceptor', [
"$q", "$window", "$location", "currentUser", function ($q, $window, $location, currentUser) {
return {
request: function(config) {
if(config.url !== 'external url') {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + currentUser.getProfile().token;
}
return config;
},
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
// error handler
}
};
}
])
with that conditional, you will skip unwanted url mods.
check out the doc as well,
https://docs.angularjs.org/api/ng/service/$http#usage
you can even create a key for all calls, that switches the interception on / off.

HTTP interceptor: Using url params instead of header for token based auth

I have the following code for token based authentication with my backend api in AngularJS:
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
config.headers = config.headers || {};
if ($localStorage.token) {
config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);
This sets the "Authorization" header to my token.
How do I have to modify my code to use an URL parameter (named "access_token") instead of an header?
You need to use the argument params – {Object.} of config object:
params – {Object.<string|Object>} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
AngularJS reference guide
$httpProvider.interceptors.push(['$q', '$location', '$localStorage', function($q, $location, $localStorage) {
return {
'request': function (config) {
//config.headers = config.headers || {};
config.params = config.params || {};
if ($localStorage.token) {
config.params.access_token = $localStorage.token;
//config.headers.Authorization = 'Bearer ' + $localStorage.token;
}
return config;
},
'responseError': function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/signin');
}
return $q.reject(response);
}
};
}]);

Resources