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

如何在客戶端(vue.js)實現自動刷新?

How to implement auto refresh in client side(vue.js)?(如何在客戶端(vue.js)實現自動刷新?)
本文介紹了如何在客戶端(vue.js)實現自動刷新?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

注意:我已經分離了我的客戶端(Vue.js)和服務器(DjangoRest).我正在使用 JWT 驗證從客戶端向服務器發出的每個請求.流動-客戶端將用戶憑據發送到服務器.如果憑據有效,服務器會發回刷新和訪問令牌.客戶端存儲訪問和刷新令牌.我已將刷新令牌到期時間設置為 1 周,訪問時間為 30 分鐘.接下來,我想確保訪問令牌在到期前 15 分鐘自動刷新.為此,將存儲在客戶端的刷新令牌發送到服務器,然后服務器發出新的訪問令牌和刷新令牌,將其發送回客戶端.我如何在 Vuex 商店中實現這一點?我是 web 開發和 vue.js 的新手.如果有人能提供一些代碼或詳細解釋,那就太好了.

Note: I have seperated my client(Vue.js) and server(DjangoRest). I'm using JWT to validate every request made from the client to the server. Flow- Client sends user credentials to server. Server sends back a refresh and access token if credentials are valid. Client stores the access and refresh token. I have set the refresh token expiry to 1 week,access to 30 mins. Next, I want to make sure that the access token is auto refreshed 15 mins prior to its expiry. To do this, the stored refresh token in client side is send to the server, the server then issues a new access token and refresh token, sends it back to the client. How do i implement this in the Vuex store?. I'm a complete newbie to web development and vue.js. It would be great if someone could provide some code or explain in details.

我已經在商店中實現了 loginUser、logout user、registerUser 并且它們工作正常.但我堅持使用自動刷新邏輯.我的猜測是客戶端必須反復檢查剩余的訪問令牌到期時間.剩下大約 15 分鐘時,我們必須初始化自動刷新功能.請幫我解決這個邏輯.

I have already implemented loginUser,logout user,registerUser in store and they are working fine. But I'm stuck with the auto refresh logic. My guess is that the client has to repeatedly check the access token expiry time left. When about 15 mins is left, we have to initialize the autorefresh function. Please help me with this logic.

這是我的 Vueex 商店:

Here's my Vueex store:

import Vue from 'vue'
import Vuex from 'vuex'
import axiosBase from './api/axios-base'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
     accessToken: '' || null,
     refreshToken: '' || null
  },
  getters: {
    loggedIn (state) {
      return state.accessToken != null
    }
  },
  mutations: {
    loginUser (state) {
      state.accessToken = localStorage.getItem('access_token')
      state.refreshToken = localStorage.getItem('refresh_token')
    },
    destroyToken (state) {
      state.accessToken = null
      state.refreshToken = null
    }
  },
  actions: {
    registerUser (context, data) {
      return new Promise((resolve, reject) => {
        this.axios.post('/register', {
          name: data.name,
          email: data.email,
          username: data.username,
          password: data.password,
          confirm: data.confirm
        })
          .then(response => {
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // fetch data from api whenever required.
    backendAPI (context, data) {

    },
    logoutUser (context) {
      if (context.getters.loggedIn) {
        return new Promise((resolve, reject) => {
          axiosBase.post('/api/token/logout/')
            .then(response => {
              localStorage.removeItem('access_token')
              localStorage.removeItem('refresh_token')
              context.commit('destroyToken')
            })
            .catch(error => {
              context.commit('destroyToken')
              resolve()
            })
        })
      }
    },
    autoRefresh (context, credentials) {

    },
    loginUser (context, credentials) {
      return new Promise((resolve, reject) => {
        axiosBase.post('/api/token/', {
          username: credentials.username,
          password: credentials.password
        })
          .then(response => {
            localStorage.setItem('access_token', response.data.access)
            localStorage.setItem('refresh_token', response.data.refresh)
            context.commit('loginUser')
            resolve(response)
          })
          .catch(error => {
            console.log(error)
            reject(error)
          })
      })
    }
  }
})

提前謝謝你.

推薦答案

正如您所指出的,這是一個非常有創意的問題,因此有很多解決方法.

This is very much an idea question as you've pointed out and as such, there are many ways of solving it.

在處理此類機制時,我要記住的一件事是盡可能避免輪詢.這是一個受該設計原則啟發的解決方案.

One thing I try to keep in mind when dealing with such mechanisms is to always avoid polling when possible. Here's a solution inspired by that design principle.

JWT 令牌在非常特定的時間內有效.作為訪問令牌的一部分,剩余的到期時間很容易獲得.您可以使用諸如 jwt-decode 之類的庫來解碼訪問令牌并提取到期時間.設置到期時間后,您有多種選擇:

JWT tokens are valid for a very specific amount of time. The time left for expiration is readily available as part of the access token. You can use a library such as jwt-decode to decode the access token and extract the expiration time. Once you have the expiration time, you have a several options available:

  • 每次發出請求前檢查令牌以了解是否需要刷新
  • 使用 setTimeout 在過期前 X 秒定期刷新
  • Check token every time before making a request to know if it needs to be refreshed
  • Use setTimeout to refresh it periodically X seconds before it expires

您的代碼可以實現如下:
注意:請將以下內容視為偽代碼.我沒有測試它是否有錯誤——語法或其他.

Your code could be implemented as follows:
Note: Please treat the following as pseudo-code. I have not tested it for errors---syntax or otherwise.

export default new Vuex.Store({
  ...
  actions: {
    refreshTokens (context, credentials) {
      // Do whatever you need to do to exchange refresh token for access token
      ...
      // Finally, call autoRefresh to set up the new timeout
      dispatch('autoRefresh', credentials)
    },
    autoRefresh (context, credentials) {
      const { state, commit, dispatch } = context
      const { accessToken } = state
      const { exp } = jwt_decode(accessToken)
      const now = Date.now() / 1000 // exp is represented in seconds since epoch
      let timeUntilRefresh = exp - now
      timeUntilRefresh -= (15 * 60) // Refresh 15 minutes before it expires
      const refreshTask = setTimeout(() => dispatch('refreshTokens', credentials), timeUntilRefresh * 1000)
      commit('refreshTask', refreshTask) // In case you want to cancel this task on logout
    }
  }
})

這篇關于如何在客戶端(vue.js)實現自動刷新?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

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

相關文檔推薦

Is Math.random() cryptographically secure?(Math.random() 在密碼學上是安全的嗎?)
Secure random numbers in javascript?(在javascript中保護隨機數?)
How to avoid multiple token refresh requests when making simultaneous API requests with an expired token(使用過期令牌發出同時 API 請求時如何避免多個令牌刷新請求)
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 鏈接中的授權標頭)
主站蜘蛛池模板: 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 一体化隔油提升设备-餐饮油水分离器-餐厨垃圾处理设备-隔油池-盐城金球环保产业发展有限公司 | 选宝石船-陆地水上开采「精选」色选机械设备-青州冠诚重工机械有限公司 | 哈尔滨发电机,黑龙江柴油发电机组-北方星光| 大型工业风扇_工业大风扇_大吊扇_厂房车间降温-合昌大风扇 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | CE认证_FCC认证_CCC认证_MFI认证_UN38.3认证-微测检测 CNAS实验室 | 耐高温风管_耐高温软管_食品级软管_吸尘管_钢丝软管_卫生级软管_塑料波纹管-东莞市鑫翔宇软管有限公司 | 宝元数控系统|对刀仪厂家|东莞机器人控制系统|东莞安川伺服-【鑫天驰智能科技】 | 层流手术室净化装修-检验科ICU改造施工-华锐净化工程-特殊科室建设厂家 | 天一线缆邯郸有限公司_煤矿用电缆厂家_矿用光缆厂家_矿用控制电缆_矿用通信电缆-天一线缆邯郸有限公司 | 【铜排折弯机,钢丝折弯成型机,汽车发泡钢丝折弯机,线材折弯机厂家,线材成型机,铁线折弯机】贝朗折弯机厂家_东莞市贝朗自动化设备有限公司 | 全自动包装秤_全自动上袋机_全自动套袋机_高位码垛机_全自动包装码垛系统生产线-三维汉界机器(山东)股份有限公司 | 翰墨AI智能写作助手官网_人工智能问答在线AI写作免费一键生成 | 工业CT-无锡璟能智能仪器有限公司| 低压载波电能表-单相导轨式电能表-华邦电力科技股份有限公司-智能物联网综合管理平台 | 衡阳耐适防护科技有限公司——威仕盾焊接防护用品官网/焊工手套/焊接防护服/皮革防护手套 | 钢托盘,铁托盘,钢制托盘,镀锌托盘,饲料托盘,钢托盘制造商-南京飞天金属13260753852 | 防火卷帘门价格-聊城一维工贸特级防火卷帘门厂家▲ | 特材真空腔体_哈氏合金/镍基合金/纯镍腔体-无锡国德机械制造有限公司 | 内窥镜-工业内窥镜厂家【上海修远仪器仪表有限公司】 | 清水混凝土修复_混凝土色差修复剂_混凝土色差调整剂_清水混凝土色差修复_河南天工 | 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | ★店家乐|服装销售管理软件|服装店收银系统|内衣店鞋店进销存软件|连锁店管理软件|收银软件手机版|会员管理系统-手机版,云版,App | vr安全体验馆|交通安全|工地安全|禁毒|消防|安全教育体验馆|安全体验教室-贝森德(深圳)科技 | 传爱自考网_传爱自学考试网| 螺杆泵_中成泵业 | 探伤仪,漆膜厚度测试仪,轮胎花纹深度尺厂家-淄博创宇电子 | China plate rolling machine manufacturer,cone rolling machine-Saint Fighter | 北京森语科技有限公司-模型制作专家-展览展示-沙盘模型设计制作-多媒体模型软硬件开发-三维地理信息交互沙盘 | 999范文网_优质范文下载写作帮手 | EPK超声波测厚仪,德国EPK测厚仪维修-上海树信仪器仪表有限公司 | 滤芯,过滤器,滤油机,贺德克滤芯,精密滤芯_新乡市宇清流体净化技术有限公司 | 合肥白癜风医院_合肥治疗白癜风医院_合肥看白癜风医院哪家好_合肥华研白癜风医院 | 高清视频编码器,4K音视频编解码器,直播编码器,流媒体服务器,深圳海威视讯技术有限公司 | 万濠投影仪_瑞士TRIMOS高度仪_尼康投影仪V12BDC|量子仪器 | NMRV减速机|铝合金减速机|蜗轮蜗杆减速机|NMRV减速机厂家-东莞市台机减速机有限公司 | 阁楼货架_阁楼平台_仓库仓储设备_重型货架_广州金铁牛货架厂 | 二手回收公司_销毁处理公司_设备回收公司-找回收信息网 | 智能风向风速仪,风速告警仪,数字温湿仪,综合气象仪(气象五要素)-上海风云气象仪器有限公司 | 篮球地板厂家_舞台木地板品牌_体育运动地板厂家_凯洁地板 |