Capture HTTP 401 with Angular.js interceptor

前端 未结 4 1711
暗喜
暗喜 2020-11-27 17:00

I\'d like to implement authentication on a single page web app with Angular.js. The official Angular documentation recommends the using of interceptors:

$pro         


        
相关标签:
4条回答
  • 2020-11-27 17:20

    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);
      }
    }];
    
    0 讨论(0)
  • 2020-11-27 17:22

    AngularJS interceptors only work for calls made with the $http service; if you navigate to a page that returns a 401, AngularJS never even runs.

    0 讨论(0)
  • 2020-11-27 17:27

    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');
    }])
    
    0 讨论(0)
  • 2020-11-27 17:37

    I don't know why, but response with 401 error goes into success function.

    'responseError': function(rejection)
                    {
                        // do something on error
    
                        if (rejection.status == 401)
                        {
                            $rootScope.signOut();
                        }
    
                        return $q.reject(rejection);
                    },
                    'response': function (response) {
                        // do something on error
                        if (response.status == 401) {
                            $rootScope.signOut();
                        };
                        return response || $q.when(response);
                    }
    
    0 讨论(0)
提交回复
热议问题