在 JavaScript 中存储刷新令牌,获取新的访问令牌 [英] Storing Refresh Token In JavaScript, Getting New Access Token

查看:75
本文介绍了在 JavaScript 中存储刷新令牌,获取新的访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Web API,它在登录时返回 OAuth2 不记名令牌.我计划通过 JavaScript 将刷新令牌存储在 cookie 中.我应该在我的 JS 中的哪个位置检查访问令牌是否已过期以获取新的令牌...就在每个需要身份验证的后续 API 调用之前或在某种计时器循环上?这将是一个异步网络应用程序,所以我认为计时器循环不是理想的.有什么想法吗?

I have a ASP.NET Web API that returns an OAuth2 bearer token upon login. I plan to store the refresh token in a cookie via JavaScript. Where in my JS should I check if the access token is expired to fetch a new one...right before each subsequent API call that requires authentication or on some sort of timer loop? This will be an async web app, so I didn't think a timer loop would be ideal. Any ideas?

推荐答案

我不会那样做,如果您可以在 javascript 中访问您的 cookie,这意味着任何 XSS 脚本都可以劫持它.Localstorage 也不是一个安全的地方.

I would not do that, if you can access your cookie in javascript it means any XSS script can hijack it. Localstorage is not a safe place either.

我建议在服务器上生成令牌后立即将令牌存储在安全的仅限 http 的 cookie 中,并将该 cookie 附加到响应中.

I would recommend storing the token in a secure http-only cookie right after the token has been generated on the server, and append that cookie to the response.

如果您将 WebAPI 2 与 oAuth 一起使用,则您可以在您的授权服务器提供程序中覆盖 TokenEndPointReponse

If you use WebAPI 2 with oAuth, in your authorizationServer provider you can override the TokenEndPointReponse

    /// <summary>
    /// Called when a request to the Token endpoint is finished and gonna be sent back to the client
    /// We intercept the token and force the client to write a cookie containing the token value.
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override System.Threading.Tasks.Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
    {

        // We set our auth cookie configuration
        var cookieOptions = new CookieOptions
        {
            HttpOnly = true, // immune to JS manipulation
            Secure = insertMagicLogicHere(), // we set the cookie to secure in production environment
            Path = "/",
            Domain = ".mycooldomain.com",
            Expires = DateTime.Now.AddMinutes(GlobalAuthSettings.AuthServerOptions.AccessTokenExpireTimeSpan.TotalMinutes)
        };

        var refreshTokenId = context.OwinContext.Get<string>("as:refreshTokenId");

        // We build the authentication object to store in our cookie
        var ourTokenObject = new AuthCookie
        {
            username = context.Properties.Dictionary["userName"],
            token = context.AccessToken,
            useRefreshTokens = true,
            refreshtoken = refreshTokenId
        };

        // We send it back 
        context.Response.Cookies.Append("mySecureCookie", JsonConvert.SerializeObject(ourTokenObject), cookieOptions);

        return base.TokenEndpointResponse(context);
    }

然后在 javascript 中,您需要确保 cookie 随每个请求一起发送.您可以设置一些 Owin Middleware 来拦截请求,从 cookie 中解析令牌并将令牌设置为 Authorization Header.

Then in javascript you need to make sure the cookie is sent with each request. You can setup some Owin Middleware to intercept requests, parse the token from the cookie and set the token to the Authorization Header.

要刷新令牌,您可以配置一个 Http 拦截器,它会在您收到 401 时自动刷新令牌,并在刷新令牌成功时重试请求.

To refresh the token you can configure an Http Interceptor that will automatically refresh the token if you receive a 401 and retry the request if the refreshtoken has been successful.

这里是一些 Angular 代码

Here is some code in Angular

    //#region Private members

    var _retryHttpRequest = function (config, deferred) {
        $rootScope.httpRetries++;
        console.log('autorefresh');
        $http = $http || $injector.get('$http') || $injector.post('$http');
        $http(config).then(
        function (success) {
            $rootScope.httpRetries--;
            deferred.resolve(success);
        },
        function (error) {
            console.log("Error in response", rejection);
            deferred.reject(error);
        });
    };

    var _refreshToken = function () {
        var deferred = $q.defer();
        // refresh_token=refreshToken because the refresh_token is serialized in the http cookie and not accessible in javascript, the refreshToken is however stored in the cookie so we can resolve that server side
        var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
        $http = $http || $injector.get('$http');
        $http.post(authUrl + '/token', data, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function (response) {
            deferred.resolve(response);
        }).error(function (err, status) {
            deferred.reject(err);
        });
        return deferred.promise;
    };

    //#endregion Private members

    //#region Public members

    function _request(config) {
        config.withCredentials = true; // forces angular to send cookies in each request
        return config;
    }

    // intercept response errors and refresh token if need be
    function _responseError(rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401 || rejection.status === 403) {
            if ($rootScope.httpRetries < 2) {
                console.log("calling refreshToken()");
                _refreshToken().then(function (response) {
                    console.log("token refreshed, retrying to connect");
                    // retry the request if the token was successfully refreshed
                    _retryHttpRequest(rejection.config, deferred);
                }, function (error) {
                    console.log("_refreshToken error", error);
                    deferred.reject(rejection);
                    window.location.reload(true);
                });
            }
            else {
                console.log("_refreshToken error", error);
                deferred.reject(rejection);
                window.location.reload(true);
            }

        } else {
            console.log("Error in response", rejection);
            deferred.reject(rejection);
        }
        return deferred.promise;
    };
    //#endregion Public members

希望这会有所帮助.

这篇关于在 JavaScript 中存储刷新令牌,获取新的访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆