在异步 JS 中刷新 OAuth2 令牌

编程入门 行业动态 更新时间:2024-10-26 12:33:02
本文介绍了在异步 JS 中刷新 OAuth2 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个与 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 令牌

本文发布于:2023-10-29 08:29:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!