2016-05-23 2 views
2

Я простая (половина закончена) HTTP-перехватчик, которая добавляет в Bearer маркер (хранится в $window.sessionsStorage) в заголовок, так чтобы запросы REST API может быть заверен:

function accessTokenHttpInterceptor($window, $http) { 

    // Try to get token details from sessionStorage 
    var accesstoken=$window.sessionStorage.getItem('userInfo-accesstoken'); 
    var refreshtoken=$window.sessionStorage.getItem('userInfo-refreshtoken'); 
    var tokenexpiry=$window.sessionStorage.getItem('userInfo-tokenexpiry'); 

    return { 

    request: function($config) { 

     // Check if the access token, refresh token and expiry date exists: 
     if (accesstoken == undefined || refreshtoken == undefined || tokenexpiry == undefined) { 
     console.log('Missing token details'); 
     // TODO REDIRECT TO LOGIN PAGE 
     } 

     // We have an access token. Has it expired? 
     var expiry = new Date($window.sessionStorage['userInfo-tokenexpiry']) 
     var now = new Date 
     if (now > expiry) { 
     console.log('Token expired'); 
     // TODO REFRESH THE TOKEN 
     }; 

     // Set the authorization header 
     $config.headers['Authorization'] = 'Bearer ' + accesstoken; 
     return $config; 

    }, 
    }; 
} 

accessTokenHttpInterceptor.$inject=['$window']; 

function httpInterceptorRegistry($httpProvider) { 
    $httpProvider.interceptors.push('accessTokenHttpInterceptor'); 
} 

angular 
    .module('myApp') 
    .config(httpInterceptorRegistry) 
    .factory('accessTokenHttpInterceptor', accessTokenHttpInterceptor) 

Как вы можете видеть, я могу узнать, истек ли токен перед вызовом API.

Может ли кто-нибудь помочь мне в том, как обновить токен перед тем, как сделать фактический запрос API? Я бы подумал, что другой запрос http будет снова перехвачен и закончится бесконечным циклом. Токен обновляется путем запроса POST в API, где токен обновления передается как параметр, а не в заголовок авторизации, как и другие запросы API.

ответ

1

Вы можете проверить URL-адрес запроса, чтобы предотвратить бесконечный цикл. Также вместо того, чтобы сразу возвращать конфигурацию, вы можете вернуть обещание, которое разрешается с ним, чтобы вы могли дождаться, пока у вас есть действительный токен. например

{ 
    request: function(config) { 
     if(config.url != 'my/refresh/url') { 
      var promiseToHaveValidToken; 

      var expiry = new Date($window.sessionStorage['userInfo-tokenexpiry']); 
      var now = new Date(); 
      if (now > expiry) { 
       promiseToHaveValidToken = $http.get('my/refresh/url').then(function (response) { 
        return response.data.token; 
       }); 
      } else { 
       promiseToHaveValidToken = $q.resolve(sessionStorage['userInfo-accesstoken']); 
      } 

      return promiseToHaveValidToken.then(function (token) { 
       config.headers['Authorization'] = 'Bearer ' + token; 
       return config; 
      }); 
     } 
    } 
}