Skip to content

Instantly share code, notes, and snippets.

@martianyi
Last active March 21, 2017 02:23
Show Gist options
  • Save martianyi/864044e8148b882717e7 to your computer and use it in GitHub Desktop.
Save martianyi/864044e8148b882717e7 to your computer and use it in GitHub Desktop.
angularjs security interceptor
var securityInterceptor = angular.module('security.interceptor', []);
//securityInterceptor, add token to page_header
securityInterceptor.factory('securityInterceptor', ['$q', '$cookieStore', '$location', 'toaster',
function ($q, $cookieStore, $location, toaster) {
var token = $cookieStore.get('token');
return {
'request': function (config) {
config.headers = config.headers || {};
if (token) {
config.headers.Authorization = 'Token ' + token;
}
return config;
},
'responseError': function (rejection) {
if (rejection.status === 401) {
$location.path('/login');
}
else if (rejection.status === 403) {
toaster.pop('error', '', 'Unauthorized');
$location.path('/login').replace();
}
return $q.reject(rejection);
}
};
}]);
//add the securityInterceptor to http config
securityInterceptor.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('securityInterceptor');
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment