pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

使用過期令牌發出同時 API 請求時如何避免多個令

How to avoid multiple token refresh requests when making simultaneous API requests with an expired token(使用過期令牌發出同時 API 請求時如何避免多個令牌刷新請求)
本文介紹了使用過期令牌發出同時 API 請求時如何避免多個令牌刷新請求的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

使用 JWT 的 API 請求在 flask 和 Vue.js 中實現.JWT 存儲在 cookie 中,服務器會為每個請求驗證 JWT.

API request using JWT is implemented in flask and Vue.js. The JWT is stored in a cookie, and the server validates the JWT for each request.

如果令牌已過期,將返回 401 錯誤.如果您收到 401 錯誤,請按照以下代碼刷新令牌,再次發出原始 API 請求.以下代碼對所有請求都是通用的.

If the token has expired, a 401 error will be returned. f you receive a 401 error, refresh the token as in the code below, The original API request is made again. The following code is common to all requests.

http.interceptors.response.use((response) => {
    return response;
}, error => {
    if (error.config && error.response && error.response.status === 401 && !error.config._retry) {
        error.config._retry = true;
        http
            .post(
                "/token/refresh",
                {},
                {
                    withCredentials: true,
                    headers: {
                        "X-CSRF-TOKEN": Vue.$cookies.get("csrf_refresh_token")
                    }
                }
            )
            .then(res => {
                if (res.status == 200) {
                    const config = error.config;
                    config.headers["X-CSRF-TOKEN"] = Vue.$cookies.get("csrf_access_token");
                    return Axios.request(error.config);
                }
            })
            .catch(error => {

            });
    }
    return Promise.reject(error);
});

在令牌過期的情況下同時發出多個 API 請求時無用地刷新令牌.例如,請求 A、B 和 C 幾乎同時執行.由于每個請求都返回 401,每個攔截器都會刷新令牌.

When making multiple API requests at the same time with the token expired Uselessly refreshing the token. For example, requests A, B, and C are executed almost simultaneously. Since 401 is returned with each request, Each interceptor will refresh the token.

沒有真正的傷害,但我認為這不是一個好方法.有一個很好的方法可以解決這個問題.

There is no real harm, but I don't think it's a good way. There is a good way to solve this.

我的想法是首先發出 API 請求來驗證令牌過期,該方法是在驗證和刷新完成后發出請求A、B、C.由于 cookie 是 HttpOnly,因此無法在客戶端 (JavaScript) 驗證到期日期.

My idea is to first make an API request to validate the token expiration, This method is to make requests A, B, and C after verification and refresh are completed. Because cookies are HttpOnly, the expiration date cannot be verified on the client side (JavaScript).

對不起,英語不好...

Sorry in poor english...

推薦答案

你需要做的是在攔截器之外維護一些狀態.說什么

What you'll need to do is maintain some state outside the interceptor. Something that says

等等,我正在獲取新令牌.

Hold up, I'm in the middle of getting a new token.

最好通過保留對 Promise 的引用來實現.這樣,第一個 401 攔截器可以創建 Promise,然后所有其他請求都可以等待它.

This is best done by keeping a reference to a Promise. That way, the first 401 interceptor can create the promise, then all other requests can wait for it.

let refreshTokenPromise // this holds any in-progress token refresh requests

// I just moved this logic into its own function
const getRefreshToken = () => http.post('/token/refresh', {}, {
  withCredentials: true,
  headers: { 'X-CSRF-TOKEN': Vue.$cookies.get('csrf_refresh_token') }
}).then(() => Vue.$cookies.get('csrf_access_token'))

http.interceptors.response.use(r => r, error => {
  if (error.config && error.response && error.response.status === 401) {
    if (!refreshTokenPromise) { // check for an existing in-progress request
      // if nothing is in-progress, start a new refresh token request
      refreshTokenPromise = getRefreshToken().then(token => {
        refreshTokenPromise = null // clear state
        return token // resolve with the new token
      })
    }

    return refreshTokenPromise.then(token => {
      error.config.headers['X-CSRF-TOKEN'] = token
      return http.request(error.config)
    })
  }
  return Promise.reject(error)
})

這篇關于使用過期令牌發出同時 API 請求時如何避免多個令牌刷新請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Is Math.random() cryptographically secure?(Math.random() 在密碼學上是安全的嗎?)
Secure random numbers in javascript?(在javascript中保護隨機數?)
JWT not decoding quot;JWT malformedquot; - Node Angular(JWT 未解碼“JWT malformed;- 節點角度)
How to invalidate a JWT token with no expiry time(如何使沒有到期時間的 JWT 令牌無效)
Authorization header in img src link(img src 鏈接中的授權標頭)
How to implement auto refresh in client side(vue.js)?(如何在客戶端(vue.js)實現自動刷新?)
主站蜘蛛池模板: 微信小程序定制,广州app公众号商城网站开发公司-广东锋火 | 急救箱-应急箱-急救包厂家-北京红立方医疗设备有限公司 | 小型玉石雕刻机_家用玉雕机_小型万能雕刻机_凡刻雕刻机官网 | 组织研磨机-高通量组织研磨仪-实验室多样品组织研磨机-东方天净 传递窗_超净|洁净工作台_高效过滤器-传递窗厂家广州梓净公司 | 工业制氮机_psa制氮机厂家-宏骁智能装备科技江苏有限公司 | 福州时代广告制作装饰有限公司-福州广告公司广告牌制作,福州展厅文化墙广告设计, | 智成电子深圳tdk一级代理-提供TDK电容电感贴片蜂鸣器磁芯lambda电源代理经销,TDK代理商有哪些TDK一级代理商排名查询。-深圳tdk一级代理 | 安全,主动,被动,柔性,山体滑坡,sns,钢丝绳,边坡,防护网,护栏网,围栏,栏杆,栅栏,厂家 - 护栏网防护网生产厂家 | 早报网| 西安中国国际旅行社(西安国旅) | 重庆轻质隔墙板-重庆安吉升科技有限公司 | 泰国试管婴儿_泰国第三代试管婴儿_泰国试管婴儿费用/多少钱_孕泰来 | 慢回弹测试仪-落球回弹测试仪-北京冠测精电仪器设备有限公司 | 青岛侦探_青岛侦探事务所_青岛劝退小三_青岛调查出轨取证公司_青岛婚外情取证-青岛探真调查事务所 | 胜为光纤光缆_光纤跳线_单模尾纤_光纤收发器_ODF光纤配线架厂家直销_北京睿创胜为科技有限公司 - 北京睿创胜为科技有限公司 | CE认证_FCC认证_CCC认证_MFI认证_UN38.3认证-微测检测 CNAS实验室 | 薪动-人力资源公司-灵活用工薪资代发-费用结算-残保金优化-北京秒付科技有限公司 | 常州企业采购平台_常州MRO采购公司_常州米孚机电设备有限公司 | 排烟防火阀-消防排烟风机-正压送风口-厂家-价格-哪家好-德州鑫港旺通风设备有限公司 | MVR蒸发器厂家-多效蒸发器-工业废水蒸发器厂家-康景辉集团官网 | 温控器生产厂家-提供温度开关/热保护器定制与批发-惠州市华恺威电子科技有限公司 | loft装修,上海嘉定酒店式公寓装修公司—曼城装饰 | 最新电影-好看的电视剧大全-朝夕电影网 | 泥沙分离_泥沙分离设备_泥砂分离机_洛阳隆中重工机械有限公司 | 郑州爱婴幼师学校_专业幼师培训_托育师培训_幼儿教育培训学校 | 涂层测厚仪_光泽度仪_uv能量计_紫外辐照计_太阳膜测试仪_透光率仪-林上科技 | 继电器模组-IO端子台-plc连接线-省配线模组厂家-世麦德 | R507制冷剂,R22/R152a制冷剂厂家-浙江瀚凯制冷科技有限公司 | 耐高温电缆厂家-远洋高温电缆 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 优考试_免费在线考试系统_培训考试系统_题库系统_组卷答题系统_匡优考试 | CCE素质教育博览会 | CCE素博会 | 教育展 | 美育展 | 科教展 | 素质教育展 | 断桥铝破碎机_发动机破碎机_杂铝破碎机厂家价格-皓星机械 | 100国际学校招生 - 专业国际学校择校升学规划 | 京港视通报道-质量走进大江南北-京港视通传媒[北京]有限公司 | 半容积式换热器_北京浮动盘管换热器厂家|北京亿丰上达 | 热缩管切管机-超声波切带机-织带切带机-无纺布切布机-深圳市宸兴业科技有限公司 | 欧必特空气能-商用空气能热水工程,空气能热水器,超低温空气源热泵生产厂家-湖南欧必特空气能公司 | 自动气象站_气象站监测设备_全自动气象站设备_雨量监测站-山东风途物联网 | 细胞染色-流式双标-试剂盒免费代做-上海研谨生物科技有限公司 | 德国EA可编程直流电源_电子负载,中国台湾固纬直流电源_交流电源-苏州展文电子科技有限公司 |