刷新令牌是如何工作的,以及上次失败的http请求是如何再次调用的,给出401.

How refresh token works and how last failed http request called again which gave 401...?

本文关键字:http 失败 请求 何再次 给出 调用 何工作 工作 刷新 令牌      更新时间:2023-09-26

我正在使用angularjs处理OAuth2。现在我陷入了使用OAuth进行身份验证的困境,无法重新发送最后一个401 api。任何想法。

我正在使用这个oauth2 repo。

Controller.js

app.controller('validate', ['$scope', '$rootScope', '$location', 'fullname', '$http', '$timeout', '$cookies', 'OAuth', function ($scope, $rootScope, $location, fullname, $http, $timeout, $cookies, OAuth) {
OAuth.getAccessToken($scope.user).then( function successCallBack(response){
            $scope.response = response;
            if($scope.response.status == 200){
                console.log($scope.response.data);
                $scope.accessToken      = $scope.response.data.access_token;
                $scope.refreshToken     = $scope.response.data.refresh_token;
                localStorage.setItem("accessToken", $scope.accessToken);
                localStorage.setItem("refreshToken", $scope.refreshToken);
                var userId = response.headers('userid');
                console.log(userId);
                $cookies.put("userId", userId);
                window.location.href = 'user_profile.php';
            }
        }, function errorCallBack(response){
            console.log(response);
        });
}]);

app.js

app.config(['OAuthProvider', function(OAuthProvider) {
OAuthProvider.configure({
  baseUrl: 'http://testzone.xxxxxx.net/api/LoginTest/Login/web/',
  clientId: '123456789',
  clientSecret: 'otszh9nonaosok88gsswc8k4w8ww04s',
  grantPath: 'api/oauth2/token',
  revokePath: 'api/oauth2/revoke'
});
}]);
app.run(['$rootScope', '$window', 'OAuth', '$cookies', '$timeout', function($rootScope, $window, OAuth, $cookies, $timeout) {
$rootScope.$on('oauth:error', function(event, rejection) {
  // Ignore `invalid_grant` error - should be catched on `LoginController`.
  if ('invalid_token' === rejection.data.error || 'invalid_grant' === rejection.data.error || 'invalid_request' === rejection.data.error || 'invalid_client' === rejection.data.error || 'unauthorized_client' === rejection.data.error || 'unsupported_grant_type' === rejection.data.error) {
        $cookies.remove('userId');
        $timeout(function(){
            window.location.href = 'index.php';
        },200);
  }
  // Refresh token when a `invalid_token` error occurs.
  if ('expired_token' === rejection.data.error) {
      console.log(rejection);
      OAuth.getRefreshToken();
  }
  console.log(rejection);
  console.log(rejection.data.error);
  console.log(rejection.data.error_description);
  // Redirect to `/login` with the `error_reason`.
  //return $window.location.href = 'index.php';
});
}]);

感谢

在分析错误响应时可以执行以下操作:

if (rejection.status === 401) {
    var authService = $injector.get('oAuthService');
    var authData = ipCookie(oAuthConstants.oAuthCookieName);
    var $http = $http || $injector.get('$http');
    var deferred = $q.defer();
    if (authData) {
        authService.refreshToken().then(function () {
            //this repeats the request with the original parameters
            return deferred.resolve($http(rejection.config));
        });
    }
    return deferred.promise;
}
else if (rejection.status === 403) {
    var toaster = $injector.get('toaster');
    toaster.pop('error', "Access Denied", "You are not authorized to do this request.");
}
else {
    return $q.reject(rejection);
}

重复上一次401 api调用的关键是:

return deferred.resolve($http(rejection.config));

我希望它能有所帮助。

  • refresh token是一种特殊类型的JWT,用于在任何时候获得更新的id_token

  • 刷新令牌携带获取新访问令牌所需的信息。换句话说,每当访问特定资源需要访问令牌时,客户端都可以使用刷新令牌来获得由认证服务器发布的新访问令牌。

以及如何在angular js中使用它查看此链接,单击此处它将指导你如何做。


看看这个相关的项目,你可以从中得到想法。github代码