-
-
Save tabuna/5ad76f3a56bc54f66d47f8bf7278f58b to your computer and use it in GitHub Desktop.
AngularJS 1.x : send JWT and expired refresh token
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
// module is your angular module | |
module.config(authInterceptorConfig); | |
/* @ngInject*/ | |
function authInterceptorConfig($httpProvider) { | |
$httpProvider.interceptors.push('authInterceptor'); | |
} | |
module.factory('authInterceptor', authInterceptor); | |
/* @ngInject */ | |
function authInterceptor($q, $injector, $location, $cookies) { | |
var replays = []; | |
var refreshTokenPromise; | |
var factory = { | |
request: request, | |
responseError: responseError | |
}; | |
return factory; | |
////////// | |
// Add authorization token to headers | |
function request(config) { | |
config.headers = config.headers || {}; | |
if ($cookies.get('token')) { | |
config.headers.Authorization = 'Bearer ' + $cookies.get('token'); | |
} | |
return config; | |
} | |
// Intercept 401s and redirect you to login | |
function responseError(response) { | |
if (response.status === 401 && $cookies.get('token')) { | |
return checkAuthorization(response); | |
} | |
return $q.reject(response); | |
///////// | |
function checkAuthorization(res) { | |
return $q(function(resolve, reject) { | |
var replay = { | |
success: function(){ | |
$injector.get('$http')(res.config).then(resolve, reject); | |
}, | |
cancel: function(){ | |
reject(res); | |
} | |
}; | |
replays.push(replay); | |
if (!refreshTokenPromise) { | |
refreshTokenPromise = $injector.get('Auth') // REFRESH TOKEN HERE | |
.refreshToken() | |
.then(clearRefreshTokenPromise) | |
.then(replayRequests) | |
.catch(cancelRequestsAndRedirect); | |
} | |
}); | |
//////////// | |
function clearRefreshTokenPromise(auth) { | |
refreshTokenPromise = null; | |
return auth; | |
} | |
function replayRequests(auth) { | |
replays.forEach(function(replay) { | |
replay.success(); | |
}); | |
replays.length = 0; | |
return auth; | |
} | |
function cancelRequestsAndRedirect() { | |
refreshTokenPromise = null; | |
replays.forEach(function(replay) { | |
replay.cancel(); | |
}); | |
replays.length = 0; | |
$cookies.remove('token'); | |
var $state = $injector.get('$state'); | |
// SET YOUR LOGIN PAGE | |
$state.go('login'); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment