Я простая (половина закончена) 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.