【问题标题】:can I wait to return my response to get an Access token?我可以等待返回我的回复以获取访问令牌吗?
【发布时间】:2018-03-14 12:58:00
【问题描述】:

您好,我目前正在尝试通过我的服务获取访问令牌,但是,问题是当我没有访问令牌时,我尝试使用将创建令牌的特殊 url 刷新页面,不幸的是函数仍然运行而无需等待此 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;
    }
});

【问题讨论】:

  • 如果CustomService 返回一个promise,可以用来延迟。我们需要查看CustomService 的代码以了解如何修改它以使用拦截器。因为调用 Promise 的 .then 方法会返回一个新的派生 Promise,所以很容易创建一个 Promise 链。有关详细信息,请参阅AngularJS $q Service API Reference - Chaining Promises
  • @georgeawg 感谢您的帮助!我添加了我的 CustomService 代码,我删除了一些信息,但是,我可以转换为使用承诺延迟的 getURL 这是您的建议吗?

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


【解决方案1】:

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

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

  • 如果检查的是false,则重定向到特殊的url $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);
},

【讨论】:

  • 感谢您的帮助!我尝试了你的方法,我有一个问题,我遇到的问题是当我调用 $window.location.href 重新加载页面时,我如何等待新页面加载并检索新令牌?似乎请求不止一次被调用,它没有给第一次调用加载的机会
猜你喜欢
  • 2013-02-16
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 2021-06-19
  • 2012-05-11
  • 1970-01-01
相关资源
最近更新 更多