Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mkhizeryounas/3ad391fae6055ec1202ab11552e70c30 to your computer and use it in GitHub Desktop.
Save mkhizeryounas/3ad391fae6055ec1202ab11552e70c30 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');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment