令牌刷新后,AngularJS重试所有请求

时间:2018-06-29 18:49:46

标签: angularjs angular-http-interceptors refresh-token

我的AngularJS应用程序中的刷新令牌有问题。我使用了this http缓冲区服务来存储所有请求,然后在令牌刷新后重试它们。主要问题是它发出了2个请求:其中一个导致401错误,下一个请求成功,并且导致不刷新数据。该如何解决?

这是我的代码:

var refreshTokenTaskRunning = false;

var _responseError = function (rejection) {
  if (rejection.status === 401) {
    var authData = localStorageService.get('authorizationData');
    var authService = $injector.get('authService');

    if (authData && authData.refreshToken) {
      if (refreshTokenTaskRunning == false) {
        refreshTokenTaskRunning = true;

        authService.refreshToken()
          .success(function (response) {
            localStorageService.set('authorizationData', {
              token: response.access_token, userName: response.userName, userRole: response.userRole, userId: response.userId, refreshToken: response.refresh_token
            });

            var promise = $httpBuffer.store(rejection.config);
            refreshTokenTaskRunning = false;
            $httpBuffer.retryAll();

            return promise;
          })
          .error(function (response) {
            refreshTokenTaskRunning = false;
            $httpBuffer.rejectAll();

            authService.logOut();
            $location.path('/login');
          })
      }
      else
        return $httpBuffer.store(rejection.config);
    }
    else {
      authService.logOut();
      $location.path('/login');
    }
  }

  return $q.reject(rejection);
}

0 个答案:

没有答案