我有一个与 API 对话的单页应用程序.我拥有这两个部分(API 和单页应用程序又名官方客户端").客户端是 javascript,所以是异步的.
I have a single page app that talks to an API. I own both parts (the API and the single page app aka "official client"). The client is javascript, so asynchronous.
我遇到的问题是令牌何时到期,这是由于 Javascript 的异步性质.
The problem I have is when the token expires, due to async nature of Javascript.
当使用刷新令牌时,我使用的 OAuth2 实现将立即撤销所有以前的访问令牌(根据 OAuth2 规范,这很好).
The implementation of OAuth2 that I use will immediately revoke all previous access tokens, when a refresh token is used (this is fine according to OAuth2 specifications).
因此,我不知道如何在 JS 中刷新令牌而不可能遇到 2 个异步请求不断撤销彼此的令牌的情况.或者一个异步请求撤销访问令牌,另一个请求正要用于发出请求.
Because of this, I do not know how to refresh the token in JS without potentially encountering a scenario where 2 async requests keep revoking each other's token. Or one async request revoking the access token another request was just about to use to make a request.
你们是如何解决这个问题的?
How do you guys solve this issue?
推荐答案发现自己,这对我有用(CoffeeScript,Object.clone 来自 Sugar.JS):
Found out myself, this works for me (CoffeeScript, Object.clone is from Sugar.JS):
tokenReloadPromise = null $.ajaxPrefilter (options, userOptions, xhr)=> if tokenReloadPromise? xhr.abort() tokenReloadPromise.then -> options.noTokenRefresh = true $.ajax(options) else originalOptions = Object.clone(options) # configure access token for request here unless options.noTokenRefresh == true options.error = (xhr)-> if xhr.status == 401 tokenReloadPromise ?= new jQuery.Deferred tokenReloadPromise.then -> originalOptions.noTokenRefresh = true $.ajax(originalOptions) App.execute "refresh:access_token", -> promise = tokenReloadPromise tokenReloadPromise = null promise.resolve() else originalOptions.error.apply(this, arguments) true更多推荐
在异步 JS 中刷新 OAuth2 令牌
发布评论