修改token刷新
This commit is contained in:
1 parent
2adaae4151
commit
e15e84aecf
4 files changed
+238
-257
No files matched your search
+81
-76
@@ -1,40 +1,15 @@
|
||||
import Request from "luch-request"
|
||||
import { isEmpty } from "radash"
|
||||
|
||||
import { userApi } from "@@/api"
|
||||
import { router, constant } from "@@/index"
|
||||
import isDevEnv from "./isDevEnv"
|
||||
import { router, constant } from "@@/index"
|
||||
import { userApi } from "../api"
|
||||
|
||||
// 定义常量
|
||||
const TOKEN_KEY = constant.storageConstant.TOKEN
|
||||
const USER_INFO_KEY = constant.storageConstant.USERINFO
|
||||
const REFRESH_TOKEN_URL = "/auth/oauth2/token?grant_type=refresh_token"
|
||||
|
||||
// 定义类型
|
||||
interface LoadingInstance {
|
||||
target: any
|
||||
count: number
|
||||
}
|
||||
|
||||
// 默认请求配置
|
||||
const defaultOptions = {
|
||||
showSuccess: false,
|
||||
// 成功提醒 默认使用后端返回值
|
||||
successMsg: "",
|
||||
// 显示失败消息 默认显示
|
||||
showError: true,
|
||||
// 失败提醒 默认使用后端返回信息
|
||||
errorMsg: "",
|
||||
// 显示请求时loading模态框 默认显示
|
||||
showLoading: true,
|
||||
// loading提醒文字
|
||||
loadingMsg: "加载中",
|
||||
// 需要授权才能请求 默认放开
|
||||
auth: false,
|
||||
}
|
||||
|
||||
// Loading 管理
|
||||
const LoadingInstance: LoadingInstance = {
|
||||
const LoadingInstance: { target: any; count: number } = {
|
||||
target: null,
|
||||
count: 0,
|
||||
}
|
||||
@@ -55,7 +30,21 @@ const http = new Request({
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
},
|
||||
withCredentials: true,
|
||||
custom: defaultOptions,
|
||||
custom: {
|
||||
showSuccess: false,
|
||||
// 成功提醒 默认使用后端返回值
|
||||
successMsg: "",
|
||||
// 显示失败消息 默认显示
|
||||
showError: true,
|
||||
// 失败提醒 默认使用后端返回信息
|
||||
errorMsg: "",
|
||||
// 显示请求时loading模态框 默认显示
|
||||
showLoading: true,
|
||||
// loading提醒文字
|
||||
loadingMsg: "加载中",
|
||||
// 需要授权才能请求 默认放开
|
||||
auth: false,
|
||||
},
|
||||
})
|
||||
|
||||
// 处理请求头 Authorization
|
||||
@@ -71,14 +60,14 @@ http.interceptors.request.use((config) => {
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
const config_header: any = config?.header || {}
|
||||
|
||||
// 设置通用请求头
|
||||
// 设置租户请求头
|
||||
config_header["TENANT-ID"] = "1"
|
||||
if (import.meta.env.VITE_IS_TOC === "true") {
|
||||
config_header["CLIENT-TOC"] = "Y"
|
||||
}
|
||||
|
||||
// 设置认证头
|
||||
if (config.url !== "/sys/auth/refresh-token") {
|
||||
if (config.url !== "/sys/auth/refresh-token" && config.url !== "/auth/oauth2/token") {
|
||||
const authHeader = getAuthHeader(tokenStorage)
|
||||
if (authHeader) {
|
||||
config_header.Authorization = authHeader
|
||||
@@ -131,7 +120,7 @@ const responseHelpers = {
|
||||
// 处理成功提示
|
||||
handleSuccessMessage(response: any) {
|
||||
const { data, config } = response
|
||||
if (data.code === 200 && data.message && config?.custom?.showSuccess) {
|
||||
if (data.code === 0 && data.message && config?.custom?.showSuccess) {
|
||||
uni.showToast({
|
||||
title: config.custom.successMsg || data.message,
|
||||
icon: "none",
|
||||
@@ -142,21 +131,67 @@ const responseHelpers = {
|
||||
// 处理登录过期
|
||||
handleLoginExpired() {
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
uni.removeStorageSync(USER_INFO_KEY)
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
|
||||
router.jump("/pages/test/login")
|
||||
isDevEnv() ? router.jump("/pages/test/login") : router.jump("/pages/tabbar/my")
|
||||
},
|
||||
|
||||
// 检查并刷新token
|
||||
async checkAndRefreshToken(tokenStorage: any) {
|
||||
const { refresh_token, expiresTime } = tokenStorage
|
||||
if (!refresh_token || !expiresTime) return
|
||||
checkAndRefreshToken(tokenStorage: any) {
|
||||
const { accessToken } = tokenStorage
|
||||
if (!accessToken) return
|
||||
|
||||
const now = new Date().getTime()
|
||||
const remain = expiresTime - now
|
||||
if (remain <= 1000 * 60 * 20) {
|
||||
const refreshData = await userApi.refreshToken({ refreshToken: refresh_token })
|
||||
if (!isEmpty(refreshData.data)) {
|
||||
uni.setStorageSync(TOKEN_KEY, refreshData.data)
|
||||
const issuedDate = new Date(accessToken.issuedAt).getTime()
|
||||
console.log(new Date().getTime() - issuedDate)
|
||||
|
||||
if (new Date().getTime() - issuedDate >= 1000 * 1) {
|
||||
// try {
|
||||
// const refreshData: any = await request({
|
||||
// url: "/auth/oauth2/token",
|
||||
// method: "POST",
|
||||
// params: { grant_type: "refresh_token" },
|
||||
// data: JSON.stringify({
|
||||
// scope: "server",
|
||||
// refresh_token: tokenStorage.refreshToken.tokenValue,
|
||||
// }),
|
||||
// header: {
|
||||
// skipToken: true,
|
||||
// Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
|
||||
// "content-type": "application/x-www-form-urlencoded",
|
||||
// },
|
||||
// })
|
||||
|
||||
// if (refreshData.code === 0 && !isEmpty(refreshData.data)) {
|
||||
// console.log("refreshData.data", refreshData.data)
|
||||
|
||||
// // 刷新成功,更新token并重试请求
|
||||
// uni.setStorageSync(TOKEN_KEY, refreshData.data)
|
||||
// }
|
||||
// } catch (refreshError) {
|
||||
// console.error("Token refresh failed:", refreshError)
|
||||
// }
|
||||
try {
|
||||
const params = new URL(window.location.href).searchParams
|
||||
const token = params.get("uabaseToken")
|
||||
if (token) {
|
||||
userApi.auth(token).then((res) => {
|
||||
if (res?.code === 0) {
|
||||
uni.setStorageSync(TOKEN_KEY, res.data)
|
||||
} else {
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
uni.removeStorageSync(USER_INFO_KEY)
|
||||
// uni.showToast({ title: "登录已过期", icon: "none" })
|
||||
return Promise.resolve({
|
||||
code: 1,
|
||||
data: "登录已过期",
|
||||
msg: "登录已过期",
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
uni.hideLoading()
|
||||
uni.showToast({ title: "错误", icon: "none" })
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -165,6 +200,8 @@ const responseHelpers = {
|
||||
// 响应拦截器
|
||||
http.interceptors.response.use(
|
||||
async (response) => {
|
||||
console.log("response", response)
|
||||
|
||||
// 关闭loading
|
||||
if (response.config?.custom?.showLoading) {
|
||||
closeLoading()
|
||||
@@ -195,19 +232,15 @@ http.interceptors.response.use(
|
||||
|
||||
// Token 刷新检查
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
if (!isEmpty(tokenStorage) && response.config.url !== "/sys/auth/refresh-token") {
|
||||
if (!isEmpty(tokenStorage) && !response.config.url?.startsWith("/thirdparty/thirdPartyOAth2/zzdsso")) {
|
||||
await responseHelpers.checkAndRefreshToken(tokenStorage)
|
||||
}
|
||||
|
||||
return Promise.resolve(response.data)
|
||||
},
|
||||
|
||||
// 错误拦截器
|
||||
async (error) => {
|
||||
(error) => {
|
||||
// 处理 424 错误(token过期)
|
||||
if (error.statusCode === 424) {
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
|
||||
if (isDevEnv()) {
|
||||
// 开发环境直接清除token并跳转登录
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
@@ -216,34 +249,6 @@ http.interceptors.response.use(
|
||||
router.jump("/pages/test/login")
|
||||
return false
|
||||
}
|
||||
|
||||
// 生产环境尝试刷新token
|
||||
if (tokenStorage?.refreshToken?.tokenValue) {
|
||||
try {
|
||||
const refreshData = await request({
|
||||
url: REFRESH_TOKEN_URL,
|
||||
method: "POST",
|
||||
data: JSON.stringify({
|
||||
scope: "server",
|
||||
refresh_token: tokenStorage.refreshToken.tokenValue,
|
||||
}),
|
||||
header: {
|
||||
Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
|
||||
"content-type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
})
|
||||
|
||||
if (refreshData.code === 0) {
|
||||
// 刷新成功,更新token并重试请求
|
||||
uni.setStorageSync(TOKEN_KEY, refreshData.data)
|
||||
const config = error.config
|
||||
config.header!.Authorization = `Bearer ${refreshData.data.accessToken.tokenValue}`
|
||||
return http.request(config)
|
||||
}
|
||||
} catch (refreshError) {
|
||||
console.error("Token refresh failed:", refreshError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 显示错误信息
|
||||
|
||||
Reference in new issue
Block a user