Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture HTTP 401 with Angular.js interceptor

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.

like image 338
Csati Avatar asked Jan 20 '14 09:01

Csati


2 Answers

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'); }]) 
like image 93
Igor S. Avatar answered Sep 23 '22 21:09

Igor S.


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);   } }]; 
like image 43
Gecko Avatar answered Sep 25 '22 21:09

Gecko