我已经用angularjs开发了单页应用程序。我已经实现了刷新令牌机制。刷新令牌假设每30分钟刷新一次。我正在尝试处理拦截器的responseError中的刷新令牌。如果返回401未经授权的错误,我将尝试保留请求。一旦返回401错误,是否有机制保存所有请求,然后刷新令牌,并使用新令牌恢复所有请求。
这是处理刷新令牌的正确方式吗?下面是示例代码
$provide.factory('httpTokenInterceptor', function ($q, $injector, $cookies) {
return {
// On request sending
request: function (config) {
config.headers = config.headers || {};
// get this data from $cookies
var globals = $cookies.getObject('globals') || {};
//console.log(globals);
if (globals.authData)
config.headers.Authorization = 'Bearer ' + globals.authData.access_token;
return config;
},
// On response failure
responseError: function (rejection) {
console.log('AuthTokenHttpInterceptor responseError');
console.log(rejection);
if (rejection.status === 401) {
//hold current and all pending request
var aService = $injector.get('authenticationService');
aService.getRefreshToken().then(function(response) {
//need to resume all the request here
deferred.resolve(response);
});
return deferred.promise;
}
return $q.reject(rejection);
}
};
});
发布于 2017-04-14 13:23:59
简而言之,您不希望像这样延迟任何HTTP调用。
您的解决方案将在其中一个HTTP调用失败后刷新您的令牌。此外,为了清楚起见,您的代码添加了HTTP头,即使是在获取资源的Authorization
调用上也是如此。如果你不想这样做,那么你也应该限制它。
对于一种解决方案,请查看此link。它不使用任何特定的库来处理JWT令牌,但是您必须围绕此实现创建一个包装器,以便在需要进行HTTP调用的任何地方使用它。
我的建议(以及处理JWT令牌时的个人偏好)是使用angular-jwt
库。它真的很容易设置,你可以在here查看它。
还有更复杂的库,比如auth0
,它可以做很多其他的事情,并且可以与angular-jwt
库结合使用。查看此link,了解如何在HTTP调用之前和页面刷新时处理令牌刷新。
希望这能有所帮助。
发布于 2017-08-29 07:12:14
您可以保留请求并使用AngularJS拦截器恢复它们。
authInterceptor.$inject = ['$q', '$rootScope'];
function authInterceptor($q, $rootScope) {
return {
request: function(config) {
var deferred = $q.defer();
$rootScope.$watch('continue', function(value) {
if(value === true)
deferred.resolve(config);
});
return deferred.promise;
}
};
}
在上面的示例中,所有请求都会一直有效,直到$rootScope.continue
变为true
。否则,他们将永远等待。
https://stackoverflow.com/questions/43405878
复制