Setting up authorization using AngularJS and angular ui router involves handling a 401 status code from the server when a user attempts to access a protected route.
An HTTP response interceptor has been created to detect the 401 status code and redirect to the login page. However, the redirection is not functioning as expected. Below is the code for the interceptor:
app.config(['$httpProvider', function ($httpProvider) {
// Ensure XHR requests are checked on the server
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.responseInterceptors.push(['$q', '$location', function ($q, $location) {
return function (promise) {
return promise.then(
// Success: return the response
function (response) {
return response;
},
// Error: handle only the 401 status code
function (response) {
if (response.status === 401)
$location.url('/users/login');
return $q.reject(response);
}
);
}
}]);
}]);
UPDATE: A workaround that seems to work involves using $timeout to delay the redirect to the login page.
$timeout(function() { $location.url('/users/login'); }, 0);
This method may change the execution context and effectively place the redirection at the end of the stack. If you have more insights on why this approach works or if there are better alternatives, please share your knowledge!