I'd like to implement authentication on a single page web app with Angular.js. The official Angular documentation recommends the using of interceptors:
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { return { // ... 'responseError': function(rejection) { // do something on error if (canRecover(rejection)) { return responseOrNewPromise } return $q.reject(rejection); } }; });
The problem is when the server sends 401 error, the browser immediately stops with "Unauthorized" message, or with login pop-up window (when authentication HTTP header is sent by the server), but Angular can't capture with it's interceptor the HTTP error to handle, as recommended. Am I misunderstanding something? I tried more examples found on web (this, this and this for example), but none of them worked.
For AngularJS >1.3 use $httpProvider.interceptors.push('myHttpInterceptor');
.service('authInterceptor', function($q) { var service = this; service.responseError = function(response) { if (response.status == 401){ window.location = "/login"; } return $q.reject(response); }; }) .config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); }])
in app config block:
var interceptor = ['$rootScope', '$q', "Base64", function(scope, $q, Base64) { function success(response) { return response; } function error(response) { var status = response.status; if (status == 401) { //AuthFactory.clearUser(); window.location = "/account/login?redirectUrl=" + Base64.encode(document.URL); return; } // otherwise return $q.reject(response); } return function(promise) { return promise.then(success, error); } }];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With