feat: 通过限制Token时间实现用户被动退出

This commit is contained in:
谢泓 2022-07-18 16:16:21 +08:00
parent 2ae903ddb5
commit 972627c32d
4 changed files with 43 additions and 0 deletions

View File

@ -2,6 +2,11 @@
import axios from 'axios'
// 引入 ElMessage 消息提示
import { ElMessage } from 'element-plus'
// 导入比较 Token 时间的方法
import { diffTokenTime } from '@/utils/auth'
import store from '@/store'
// axios 基础配置
const service = axios.create({
// 基础路径
@ -35,6 +40,13 @@ service.interceptors.response.use(
// 请求拦截器
service.interceptors.request.use(
(config) => {
if (localStorage.getItem('token')) {
if (diffTokenTime()) {
// 通过 vuex 实现退出操作
store.dispatch('app/logout')
return Promise.reject(new Error('token 失效了'))
}
}
config.headers.Authorization = localStorage.getItem('token')
return config
},

View File

@ -1,5 +1,6 @@
import { login as loginApi } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'
export default {
namespaced: true,
@ -17,6 +18,7 @@ export default {
.then((res) => {
console.log(res)
commit('setToken', res.token)
setTokenTime()
router.replace('/menu')
resolve()
})
@ -24,6 +26,12 @@ export default {
reject(err)
})
})
},
// Token 超时退出到登录界面
logout({ commit }) {
commit('setToken', '')
localStorage.clear()
router.replace('/login')
}
}
}

18
src/utils/auth.js Normal file
View File

@ -0,0 +1,18 @@
import { TOKEN_TIME, TOKEN_TIME_VALUE } from './constant'
// 登录时开始 Token 时间
export const setTokenTime = () => {
localStorage.setItem(TOKEN_TIME, Date.now())
}
// 获取 Token 时间
export const getTokenTime = () => {
return localStorage.getItem(TOKEN_TIME)
}
// 比较 Token 是否已经过期
export const diffTokenTime = () => {
const currentTime = Date.now()
const tokenTime = getTokenTime()
return currentTime - tokenTime > TOKEN_TIME_VALUE
}

5
src/utils/constant.js Normal file
View File

@ -0,0 +1,5 @@
export const TOKEN_TIME = 'tokenTime'
// TOKEN 有效期时间 - 1h
export const TOKEN_TIME_VALUE = 1 * 60 * 60 * 1000
// TOKEN 有效期时间 - 6s
// export const TOKEN_TIME_VALUE = 6 * 1000