Skip to content

Instantly share code, notes, and snippets.

@JosephScript
Last active March 14, 2017 05:24
Show Gist options
  • Save JosephScript/17d4d53bfa35b6fa226c to your computer and use it in GitHub Desktop.
Save JosephScript/17d4d53bfa35b6fa226c to your computer and use it in GitHub Desktop.
An authorization interceptor for AngularJS. This relies on an authorization service, and will send JWT headers with every request. If a 401 error is encountered, the user is redirected to the login page.
app.factory('authInterceptor', ['$q', '$location', 'authService', function ($q, $location, authService) {
return {
request: function (config) {
config.headers = config.headers || {};
if (authService.isAuthed()) {
config.headers.Authorization = 'Bearer ' + authService.getToken();
}
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
$location.path("/login");
}
return response || $q.when(response);
}, responseError: function (response) {
if (response.status === 401) {
$location.path("/login");
}
return $q.reject(response);
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment