feat: add switch autofresh token

This commit is contained in:
chansee97 2024-06-13 12:34:46 +08:00
parent 808c4d0cdf
commit 9aed794344
6 changed files with 23 additions and 7 deletions

3
.env
View File

@ -15,3 +15,6 @@ VITE_STORAGE_PREFIX=
# 版权信息
VITE_COPYRIGHT_INFO= Copyright © 2024 chansee97
# 自动刷新token
VITE_AUTO_REFRESH_TOKEN=Y

View File

@ -1,7 +1,7 @@
{
"name": "nova-admin",
"type": "module",
"version": "0.9.3",
"version": "0.9.4",
"private": true,
"description": "a clean and concise back-end management template based on Vue3, Vite5, Typescript, and Naive UI.",
"author": {

View File

@ -18,12 +18,19 @@ const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthenticati
// 服务端判定token过期
refreshTokenOnSuccess: {
// 当服务端返回401时表示token过期
isExpired: (response, _method) => {
return response.status === 401
isExpired: (response, method) => {
const isExpired = method.meta && method.meta.isExpired
return response.status === 401 && !isExpired
},
// 当token过期时触发在此函数中触发刷新token
handler: async (_response, _method) => {
handler: async (_response, method) => {
// 此处采取限制,防止过期请求无限循环重发
if (!method.meta)
method.meta = { isExpired: true }
else
method.meta.isExpired = true
await handleRefreshToken()
},
},

View File

@ -70,6 +70,13 @@ export function handleServiceResult(data: any, isSuccess: boolean = true) {
*/
export async function handleRefreshToken() {
const authStore = useAuthStore()
const isAutoRefresh = import.meta.env.VITE_AUTO_REFRESH_TOKEN === 'Y'
if (!isAutoRefresh) {
await authStore.logout()
return
}
// 刷新token
const { data } = await fetchUpdateToken({ refreshToken: local.get('refreshToken') })
if (data) {
local.set('accessToken', data.accessToken)

View File

@ -29,6 +29,8 @@ interface ImportMetaEnv {
readonly VITE_HOME_PATH: string
/** 版权信息 */
readonly VITE_COPYRIGHT_INFO: string
/** 是否自动刷新token */
readonly VITE_AUTO_REFRESH_TOKEN: 'Y' | 'N'
/** 后端服务的环境类型 */
readonly MODE: ServiceEnvType

View File

@ -18,9 +18,6 @@ async function expiredToken() {
<n-button type="error" @click="expiredToken">
click
</n-button>
<n-alert title="关于401-token失效刷新" type="warning" class="mt-1">
请在控制台将网络速率设置为最低1kb左右后点击查看否则会造成请求大量发送
</n-alert>
</n-card>
</template>