发送静默请求以刷新令牌

Send silent request to refresh tokens

我在前端和基于 JWT 的身份验证系统中使用 Vue.js。我有刷新令牌和访问令牌。访问令牌的到期时间很短,而刷新令牌的到期时间更长。我想向服务器发送请求以静默刷新用户的访问令牌。我知道访问令牌什么时候过期。我想在它过期前 1 分钟左右刷新它。我该如何实施?我想通过在我的根组件上放置一个计数器来做到这一点,但我没有确切的解决方案。谢谢。

我遇到了与您类似的问题,并在提取您答案的同一搜索中找到了这个 Vue JWT Auth。实施比我最初预期的更具挑战性。

我的应用程序需要在页面重新加载时和 API 调用之前立即刷新 JWT 令牌。为此,我使用 axios 来使用 APIs,允许使用拦截器来检查令牌的有效性。为了保持 UX 流畅,我使用 vuex 存储来维护令牌,升级到 localStorage,然后在每个前一阶段都不成功的情况下向外部请求新令牌。

商店外的组件如下所示:

src/utils/apiAxios.js:用于消耗APIs

import axios from 'axios'
import config from '../../config'
import store from '../store'

const apiAxios = axios.create({
 baseURL: `${config.dev.apiURL}api/`,
 timeout: 1000,
 headers: {'Content-Type': 'application/json'}
})

// before any API call make sure that the access token is good
apiAxios.interceptors.request.use(function () {
 store.dispatch('isLoggedIn')
})

export default apiAxios

src/main.js 添加了这些行:

import store from './store'

router.beforeEach((to, from, next) => {
  let publicPages = ['/auth/login/', '/auth/register/']
  let authRequired = !publicPages.includes(to.path)
  let loggedIn = store.dispatch('isLoggedIn')

  if (authRequired && !loggedIn) {
    return next('/auth/login/')
  }

  next()
})

src/store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'

import auth from './modules/auth'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    auth
  },
  strict: debug,
  plugins: debug ? [createLogger()] : []
})

src/store/modules/auth.js:

import axios from 'axios'
import jwtDecode from 'jwt-decode'
import router from '../../utils/router'
import apiAxios from '../../utils/apiAxios'
import config from '../../../config'

export default {

  state: {
    authStatus: '',
    jwt: {
      refresh: '',
      access: ''
    },
    endpoints: {
      obtainJWT: config.dev.apiURL + 'auth/',
      refreshJWT: config.dev.apiURL + 'auth/refresh/',
      registerJWT: config.dev.apiURL + 'auth/register/',
      revokeJWT: config.dev.apiURL + 'auth/revoke/',
      verifyJWT: config.dev.apiURL + 'auth/verify/'
    }
  },

  mutations: {
    UPDATE_TOKEN (state, newToken) {
      apiAxios.defaults.headers.common['Authorization'] = `Bearer ${newToken.access}`
      localStorage.setItem('jwtAccess', newToken.access)
      localStorage.setItem('jwtRefresh', newToken.refresh)
      state.authStatus = 'success'
      state.jwt = newToken
    },
    UPDATE_STATUS (state, statusUpdate) {
      state.authStatus = statusUpdate
    },
    REVOKE_TOKEN (state) {
      delete apiAxios.defaults.headers.common['Authorization']
      localStorage.removeItem('jwtAccess')
      localStorage.removeItem('jwtRefresh')
      state.authStatus = ''
      state.jwt = {
        refresh: '',
        access: ''
      }
    }
  },

  getters: {
    authStatus: state => state.authStatus,
    isLoggedIn: getters => {
      // quick check of the state
      return getters.authStatus === 'success'
    }
  },

  actions: {
    login ({ state, commit }, { email, password }) {
      axios({
        url: state.endpoints.obtainJWT,
        method: 'POST',
        data: {
          email: email,
          password: password
        },
        headers: {'Content-Type': 'application/json'}
      })
        .then((response) => {
          commit('UPDATE_TOKEN', response.data)
        })
        .catch((error) => {
          commit('UPDATE_STATUS', error)
          console.log(error)
        })
    },

    register ({ state, commit }, { email, password, firstName, lastName }) {
      axios({
        url: state.endpoints.registerJWT,
        method: 'POST',
        data: {
          email: email,
          password: password,
          first_name: firstName,
          last_name: lastName
        },
        headers: {'Content-Type': 'application/json'}
      })
        .then((response) => {
          commit('UPDATE_TOKEN', response.data)
        })
        .catch((error) => {
          commit('UPDATE_STATUS', error)
          console.log(error)
        })
    },

    logout ({ state, commit }) {
      let refresh = localStorage.getItem('jwtRefresh')
      axios({
        url: state.endpoints.revokeJWT,
        method: 'POST',
        data: { token: refresh },
        headers: {'Content-Type': 'application/json'}
      })
        .then(commit('REVOKE_TOKEN'))
        .catch((error) => {
          commit('UPDATE_STATUS', error)
          console.log(error)
        })
    },

    refreshTokens ({ state, commit }) {
      let refresh = localStorage.getItem('jwtRefresh')
      axios({
        url: state.endpoints.refreshJWT,
        method: 'POST',
        data: {refresh: refresh},
        headers: {'Content-Type': 'application/json'}
      })
        .then((response) => {
          this.commit('UPDATE_TOKEN', response.data)
        })
        .catch((error) => {
          commit('UPDATE_STATUS', error)
          console.log(error)
        })
    },

    verifyToken ({ state, commit, dispatch, getters }) {
      let refresh = localStorage.getItem('jwtRefresh')
      if (refresh) {
        axios({
          url: state.endpoints.verifyJWT,
          method: 'POST',
          data: {token: refresh},
          headers: {'Content-Type': 'application/json'}
        })
          .then(() => {
            // restore vuex state if it was lost due to a page reload
            if (getters.authStatus !== 'success') {
              dispatch('refreshTokens')
            }
          })
          .catch((error) => {
            commit('UPDATE_STATUS', error)
            console.log(error)
          })
        return true
      } else {
        // if the token is not valid remove the local data and prompt user to login
        commit('REVOKE_TOKEN')
        router.push('/auth/login/')
        return false
      }
    },

    checkAccessTokenExpiry ({ state, getters, dispatch }) {
      // inspect the store access token's expiration
      if (getters.isLoggedIn) {
        let access = jwtDecode(state.jwt.access)
        let nowInSecs = Date.now() / 1000
        let isExpiring = (access.exp - nowInSecs) < 30
        // if the access token is about to expire
        if (isExpiring) {
          dispatch('refreshTokens')
        }
      }
    },

    refreshAccessToken ({ dispatch }) {
      /*
       * Check to see if the server thinks the refresh token is valid.
       * This method assumes that the page has been refreshed and uses the
       * @verifyToken method to reset the vuex state.
       */
      if (dispatch('verifyToken')) {
        dispatch('checkAccessTokenExpiry')
      }
    },

    isLoggedIn ({ getters, dispatch }) {
      /*
       * This method reports if the user has active and valid credentials
       * It first checks to see if there is a refresh token in local storage
       * To minimize calls it checks the store to see if the access token is
       * still valid and will refresh it otherwise.
       *
       * @isLoggedIn is used by the axios interceptor and the router to
       * ensure that the tokens in the vuex store and the axios Authentication
       * header are valid for page reloads (router) and api calls (interceptor).
       */
      let refresh = localStorage.getItem('jwtRefresh')
      if (refresh) {
        if (getters.isLoggedIn) {
          dispatch('checkAccessTokenExpiry')
        } else {
          dispatch('refreshAccessToken')
        }
        return getters.isLoggedIn
      }
      return false
    }
  }
}

我在后端使用 django,在令牌中使用 django-rest-framework-simplejwt。返回的 JSON 格式如下:

{
  access: "[JWT string]",
  refresh: "[JWT string]"
}

a token structure 的:

header:

{
  "typ": "JWT",
  "alg": "HS256"
}

payload:

{
  "token_type": "access",
  "exp": 1587138279,
  "jti": "274eb43bc0da429a825aa30a3fc23672",
  "user_id": 1
}

访问刷新端点时,SimpleJWT 要求在 data 中将刷新令牌命名为 refresh;对于验证和撤销(黑名单)端点,需要将刷新令牌命名为 token。根据您用于后端的内容,需要对我所做的进行修改。

访问令牌仅在 api Authentication header 中使用,并在调用突变时更新。

为了获取令牌以便我对其进行解码,我使用了一个简单的 shell 脚本:

#!/usr/bin/env bash

EMAIL="my@email.com"
PASSWORD="aReallyBadPassword"

echo "API Login Token"
JSON_FMT='{"email":"%s","password":"%s"}'
JSON_FMT=` printf "$JSON_FMT" "$EMAIL" "$PASSWORD" `
curl \
    --request POST \
    --header Content-Type:application/json \
    --data $JSON_FMT \
    http://localhost:8000/api/auth/
echo ""