Skip to content

Instantly share code, notes, and snippets.

@antoniocapelo
Created February 13, 2015 21:14
Show Gist options
  • Save antoniocapelo/96c3d7989cf19a4f49e4 to your computer and use it in GitHub Desktop.
Save antoniocapelo/96c3d7989cf19a4f49e4 to your computer and use it in GitHub Desktop.
AngularJS HTTP Interceptor for Bearer Token Auth Requests
app.factory('BearerAuthInterceptor', function ($window, $q) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($window.localStorage.getItem('token')) {
// may also use sessionStorage
config.headers.Authorization = 'Bearer ' + $window.localStorage.getItem('token');
}
return config || $q.when(config);
},
response: function(response) {
if (response.status === 401) {
// Redirect user to login page / signup Page.
}
return response || $q.when(response);
}
};
});
// Register the previously created AuthInterceptor.
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('BearerAuthInterceptor');
});
@jeevad
Copy link

jeevad commented Jul 18, 2016

response.status === 401 this code should come under responseError

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment