Last active
March 14, 2017 05:24
-
-
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.
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('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