Created
February 13, 2015 21:14
-
-
Save antoniocapelo/96c3d7989cf19a4f49e4 to your computer and use it in GitHub Desktop.
AngularJS HTTP Interceptor for Bearer Token Auth Requests
This file contains 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
response.status === 401
this code should come under responseError