如何在客户端(vue.js)实现自动刷新? [英] How to implement auto refresh in client side(vue.js)?

查看:48
本文介绍了如何在客户端(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)实现自动刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆