Reputation: 8258
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.
The problem I have is when the token expires, due to async nature of Javascript.
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).
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?
Upvotes: 0
Views: 983
Reputation: 8258
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
Upvotes: 1