-
-
Save diegodelfin7/dd9b349a5dde53416fb9c5efeaf18fdd to your computer and use it in GitHub Desktop.
AngularJS HTTP Interceptor for Bearer Token Auth Requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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