角度刷新令牌授权问题

时间:2015-11-12 19:55:52

标签: javascript angularjs access-token

我有一个Angular客户端。我使用Asp.Net WebApi创建了一个Bearer Token Authorization系统。它使用具有短暂指定时间的访问令牌,并使用长期指定时间刷新令牌。当访问令牌过期并向具有多个$ http请求的页面发出请求时,我遇到了问题。我有一个服务设置用于检索数据,其中,如果第一个响应返回401,它将从刷新令牌服务器获取新令牌,然后再次请求数据。发生的事情是两个安全请求几乎同时触发,它们都失败401,它们都得到一个新令牌,第一个令牌检索被第二个无效。

两个修正案跳了出来。 1.)将调用链接到我的数据服务。 2)以页面对所有数据发出一个请求的方式排列我的请求。我不打算详细说明为什么这两种方法都是不可接受的,我相信你知道为什么。

我想到了对令牌服务器的“锁定”请求,而其他请求正在进行中或为令牌请求设置队列服务,我显然试图避免瓶颈,同时保持我的保证链的完整性。< / p>

我确信其他人已经经历过这种情况,只是想知道其他人采取了什么措施。

提前致谢!

1 个答案:

答案 0 :(得分:3)

你是否覆盖了角度app.config方法中的$ httpProvider?

使用$httpProvider.interceptors.push(<Your auth interceptor>);

如果没有,拦截器将监视您的角应用程序所做的所有请求,并使用下面的“可选功能”处理它们。

您可以设置一个工厂来处理下面的一块骨头。 这基本上一次只需要一个请求。因此,对于模拟请求问题,第一个请求将通过工厂请求函数并设置标头。然后将发出请求并且将响应响应函数。如果响应返回错误,则将调用工厂响应错误函数,如果将评估401的状态代码,则可以实现请求新承载令牌的方法。完成后,第二个请求将发送,新的承载令牌已经设置好,你应该好好去。

angular.module('authInterceptor', []).factory('Interceptor', Interceptor);

function Interceptor($q, $cookie){
    var factory = {
        response: response,
        responseError: responseError,
        request: request,
        };

    //////////////////

    //This will setup the http request
    //Since your using a bearer token and refresh token you will want to add the bearer token the the header of all the requests
    function request(config) {
        //Set config.headers to existing headers or if none exists set it to an empty object
        config.headers = config.headers || {};

        //Grab you auth data from storage
        //I usually store the object from the /token request in $cookie
        var authData = $cookies.getObject("authData");

        //If authData exists set it as a Authorization header
        if (authData) {
            config.headers.Authorization = "Bearer " + authData.access_token;
        }
    }

    function response(response) {
        return response || $q.when(response);
    }

    //Where the 401 magic happens
    //If your rejection status is a 401(UnAuthorized)
    //You want to request a new token from the authorization service
    function responseError(rejection) {
        var deferred = $q.defer();

        if (rejection.status === 401) {
            //You need to manually inject services or factories since your in the .config method
            var Authentication = $injector.get("Authentication");

            //I usually set up a Authentication Service to do the dirty work so the interceptor doesnt get bloated with code

            //See below for reissue token
            Authentication.reissueToken()
                .then(function () {

                //Valid grant

            }, function (err) {

                //Invalid grant
            });

            //When this get his the original $http request that failed will get resent to the server
            return deferred.promise;
        }

        return $q.reject(rejection);
    }
}


/*Reissue token 
         * Grabs the authData from storage, using the bearer token make a request to the token endpoint
         * If the refresh token hasnt expired the success will send back a new bearer token.
         * Update the auth cookie with the new token object
         * If the refresh token has expired the request will result in an invalid_grant request will
         * be rejected, user must log in again*/
 function reissueToken() {
        var deferred = $q.defer();
        var authData = $cookies.getObject("authData");

        if (authData) {
            var token = authData.refresh_token;
            var data = "grant_type=refresh_token&refresh_token=" + token + "&client_id=" + clientId;

            $http.post("/token", data)
                .success(function (newToken) {
                    //Update wherever you store the authorization data
                }).error(function (err, status) {
                    deferred.reject();
            });
        } else {
            deferred.reject();
        }

        return deferred.promise;
    }

您可以为拦截器

阅读更多here ctrl + f
相关问题