我可以等待返回我的响应以获取访问令牌吗?

时间:2018-03-13 22:34:53

标签: angularjs oauth-2.0 angular-http-interceptors

您好我正在尝试通过我的服务获取访问令牌,但问题是,当我没有访问令牌时,我尝试使用会创建令牌的特殊网址刷新页面,不幸的是该函数仍在运行,无需等待此URL加载新令牌。有没有办法增加承诺,或者你有不同的方法吗?如果您有任何想法,请告诉我。谢谢!!

代码:

app.factory('HttpInterceptor', function ($q, $window, CustomService) {
  return {
    request: function (config) {
            if(CustomService.getAccessToken() == undefined) {
                $window.location.href = CustomService.getURL();
            }
        config.headers.Authorization = 'Bearer ' + CustomService.getAccessToken(); // this is still undefined since window.location.href is still loading
        return $q.when(config);
    },
    responseError: function(response) {
        if(response.status == 401){
            $window.location.href = CustomService.getURL();
        }
        return $q.reject(response)
    }
  };
});

app.service('CustomService', function($location) {
    this.getAccessToken = function() {
      if(getParam('token')){
          this.token = getParam('token');
      } 
      return this.token;
    }

    this.getURL = function(){
           var redirectUrl = //adds url
        return redirectUrl;
        
    }
    
    function getParam(name) {
      var token = null;
      token = //adds token info
      return token;
    }
});

1 个答案:

答案 0 :(得分:1)

您可以在config.url函数中使用request

  • 首先找出CustomService.getURL()返回的网址格式。
  • 在每个请求中检查config.url是否与CustomService.getURL()匹配且访问令牌为空或已过期。
  • 如果检查true然后继续$window.location.href = CustomService.getURL();

  • 如果检查结果为false,则会重定向到特殊网址$window.location.href = CustomService.getURL();

示例请求代码:

request: function (config) {
   if(CustomService.getAccessToken() == undefined && config.url.indexOf('oauth2')) {  
     //'oauth2' can be of any pattern
     $window.location.href = CustomService.getURL();
   }
   else{
     config.headers.Authorization = 'Bearer ' +  CustomService.getAccessToken(); 
     // this is still undefined since window.location.href is still loading
   }

   return $q.when(config);
},