【功能优化】WebSocket 使用 refreshToken 认证,解决无法刷新访问令牌的问题
parent
5f496038c5
commit
b6635a5d5c
|
@ -1,6 +1,7 @@
|
||||||
import { onBeforeUnmount, reactive, ref } from 'vue';
|
import { onBeforeUnmount, reactive, ref } from 'vue';
|
||||||
import { baseUrl, websocketPath } from '@/sheep/config';
|
import { baseUrl, websocketPath } from '@/sheep/config';
|
||||||
import { copyValueToTarget } from '@/sheep/util';
|
import { copyValueToTarget } from '@/sheep/util';
|
||||||
|
import { getRefreshToken } from '@/sheep/request';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* WebSocket 创建 hook
|
* WebSocket 创建 hook
|
||||||
|
@ -8,12 +9,8 @@ import { copyValueToTarget } from '@/sheep/util';
|
||||||
* @return {{options: *}}
|
* @return {{options: *}}
|
||||||
*/
|
*/
|
||||||
export function useWebSocket(opt) {
|
export function useWebSocket(opt) {
|
||||||
const getAccessToken = () => {
|
|
||||||
return uni.getStorageSync('token');
|
|
||||||
};
|
|
||||||
|
|
||||||
const options = reactive({
|
const options = reactive({
|
||||||
url: (baseUrl + websocketPath).replace('http', 'ws') + '?token=' + getAccessToken(), // ws 地址
|
url: (baseUrl + websocketPath).replace('http', 'ws') + '?token=' + getRefreshToken(), // ws 地址
|
||||||
isReconnecting: false, // 正在重新连接
|
isReconnecting: false, // 正在重新连接
|
||||||
reconnectInterval: 3000, // 重连间隔,单位毫秒
|
reconnectInterval: 3000, // 重连间隔,单位毫秒
|
||||||
heartBeatInterval: 5000, // 心跳间隔,单位毫秒
|
heartBeatInterval: 5000, // 心跳间隔,单位毫秒
|
||||||
|
@ -22,12 +19,9 @@ export function useWebSocket(opt) {
|
||||||
destroy: false, // 是否销毁
|
destroy: false, // 是否销毁
|
||||||
pingTimeout: null, // 心跳检测定时器
|
pingTimeout: null, // 心跳检测定时器
|
||||||
reconnectTimeout: null, // 重连定时器ID的属性
|
reconnectTimeout: null, // 重连定时器ID的属性
|
||||||
onConnected: () => {
|
onConnected: () => {}, // 连接成功时触发
|
||||||
}, // 连接成功时触发
|
onClosed: () => {}, // 连接关闭时触发
|
||||||
onClosed: () => {
|
onMessage: (data) => {}, // 收到消息
|
||||||
}, // 连接关闭时触发
|
|
||||||
onMessage: (data) => {
|
|
||||||
}, // 收到消息
|
|
||||||
});
|
});
|
||||||
const SocketTask = ref(null); // SocketTask 由 uni.connectSocket() 接口创建
|
const SocketTask = ref(null); // SocketTask 由 uni.connectSocket() 接口创建
|
||||||
|
|
||||||
|
@ -58,7 +52,8 @@ export function useWebSocket(opt) {
|
||||||
// 情况一:实例销毁
|
// 情况一:实例销毁
|
||||||
if (options.destroy) {
|
if (options.destroy) {
|
||||||
options.onClosed();
|
options.onClosed();
|
||||||
} else { // 情况二:连接失败重连
|
} else {
|
||||||
|
// 情况二:连接失败重连
|
||||||
// 停止心跳检查
|
// 停止心跳检查
|
||||||
stopHeartBeat();
|
stopHeartBeat();
|
||||||
// 重连
|
// 重连
|
||||||
|
@ -140,10 +135,8 @@ export function useWebSocket(opt) {
|
||||||
copyValueToTarget(options, opt);
|
copyValueToTarget(options, opt);
|
||||||
SocketTask.value = uni.connectSocket({
|
SocketTask.value = uni.connectSocket({
|
||||||
url: options.url,
|
url: options.url,
|
||||||
complete: () => {
|
complete: () => {},
|
||||||
},
|
success: () => {},
|
||||||
success: () => {
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
initEventListeners();
|
initEventListeners();
|
||||||
};
|
};
|
||||||
|
|
|
@ -12,224 +12,226 @@ import AuthUtil from '@/sheep/api/member/auth';
|
||||||
import { getTerminal } from '@/sheep/util/const';
|
import { getTerminal } from '@/sheep/util/const';
|
||||||
|
|
||||||
const options = {
|
const options = {
|
||||||
// 显示操作成功消息 默认不显示
|
// 显示操作成功消息 默认不显示
|
||||||
showSuccess: false,
|
showSuccess: false,
|
||||||
// 成功提醒 默认使用后端返回值
|
// 成功提醒 默认使用后端返回值
|
||||||
successMsg: '',
|
successMsg: '',
|
||||||
// 显示失败消息 默认显示
|
// 显示失败消息 默认显示
|
||||||
showError: true,
|
showError: true,
|
||||||
// 失败提醒 默认使用后端返回信息
|
// 失败提醒 默认使用后端返回信息
|
||||||
errorMsg: '',
|
errorMsg: '',
|
||||||
// 显示请求时loading模态框 默认显示
|
// 显示请求时loading模态框 默认显示
|
||||||
showLoading: true,
|
showLoading: true,
|
||||||
// loading提醒文字
|
// loading提醒文字
|
||||||
loadingMsg: '加载中',
|
loadingMsg: '加载中',
|
||||||
// 需要授权才能请求 默认放开
|
// 需要授权才能请求 默认放开
|
||||||
auth: false,
|
auth: false,
|
||||||
// ...
|
// ...
|
||||||
};
|
};
|
||||||
|
|
||||||
// Loading全局实例
|
// Loading全局实例
|
||||||
let LoadingInstance = {
|
let LoadingInstance = {
|
||||||
target: null,
|
target: null,
|
||||||
count: 0,
|
count: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 关闭loading
|
* 关闭loading
|
||||||
*/
|
*/
|
||||||
function closeLoading() {
|
function closeLoading() {
|
||||||
if (LoadingInstance.count > 0) LoadingInstance.count--;
|
if (LoadingInstance.count > 0) LoadingInstance.count--;
|
||||||
if (LoadingInstance.count === 0) uni.hideLoading();
|
if (LoadingInstance.count === 0) uni.hideLoading();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @description 请求基础配置 可直接使用访问自定义请求
|
* @description 请求基础配置 可直接使用访问自定义请求
|
||||||
*/
|
*/
|
||||||
const http = new Request({
|
const http = new Request({
|
||||||
baseURL: baseUrl + apiPath,
|
baseURL: baseUrl + apiPath,
|
||||||
timeout: 8000,
|
timeout: 8000,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
header: {
|
header: {
|
||||||
Accept: 'text/json',
|
Accept: 'text/json',
|
||||||
'Content-Type': 'application/json;charset=UTF-8',
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
platform: $platform.name,
|
platform: $platform.name,
|
||||||
},
|
},
|
||||||
// #ifdef APP-PLUS
|
// #ifdef APP-PLUS
|
||||||
sslVerify: false,
|
sslVerify: false,
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
// 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
|
// 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
|
||||||
withCredentials: false,
|
withCredentials: false,
|
||||||
// #endif
|
// #endif
|
||||||
custom: options,
|
custom: options,
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @description 请求拦截器
|
* @description 请求拦截器
|
||||||
*/
|
*/
|
||||||
http.interceptors.request.use(
|
http.interceptors.request.use(
|
||||||
(config) => {
|
(config) => {
|
||||||
// 自定义处理【auth 授权】:必须登录的接口,则跳出 AuthModal 登录弹窗
|
// 自定义处理【auth 授权】:必须登录的接口,则跳出 AuthModal 登录弹窗
|
||||||
if (config.custom.auth && !$store('user').isLogin) {
|
if (config.custom.auth && !$store('user').isLogin) {
|
||||||
showAuthModal();
|
showAuthModal();
|
||||||
return Promise.reject();
|
return Promise.reject();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 自定义处理【loading 加载中】:如果需要显示 loading,则显示 loading
|
// 自定义处理【loading 加载中】:如果需要显示 loading,则显示 loading
|
||||||
if (config.custom.showLoading) {
|
if (config.custom.showLoading) {
|
||||||
LoadingInstance.count++;
|
LoadingInstance.count++;
|
||||||
LoadingInstance.count === 1 &&
|
LoadingInstance.count === 1 &&
|
||||||
uni.showLoading({
|
uni.showLoading({
|
||||||
title: config.custom.loadingMsg,
|
title: config.custom.loadingMsg,
|
||||||
mask: true,
|
mask: true,
|
||||||
fail: () => {
|
fail: () => {
|
||||||
uni.hideLoading();
|
uni.hideLoading();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 增加 token 令牌、terminal 终端、tenant 租户的请求头
|
// 增加 token 令牌、terminal 终端、tenant 租户的请求头
|
||||||
const token = getAccessToken();
|
const token = getAccessToken();
|
||||||
if (token) {
|
if (token) {
|
||||||
config.header['Authorization'] = token;
|
config.header['Authorization'] = token;
|
||||||
}
|
}
|
||||||
config.header['terminal'] = getTerminal();
|
config.header['terminal'] = getTerminal();
|
||||||
|
|
||||||
config.header['Accept'] = '*/*';
|
config.header['Accept'] = '*/*';
|
||||||
config.header['tenant-id'] = tenantId;
|
config.header['tenant-id'] = tenantId;
|
||||||
return config;
|
return config;
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @description 响应拦截器
|
* @description 响应拦截器
|
||||||
*/
|
*/
|
||||||
http.interceptors.response.use(
|
http.interceptors.response.use(
|
||||||
(response) => {
|
(response) => {
|
||||||
// 约定:如果是 /auth/ 下的 URL 地址,并且返回了 accessToken 说明是登录相关的接口,则自动设置登陆令牌
|
// 约定:如果是 /auth/ 下的 URL 地址,并且返回了 accessToken 说明是登录相关的接口,则自动设置登陆令牌
|
||||||
if (response.config.url.indexOf('/member/auth/') >= 0 && response.data?.data?.accessToken) {
|
if (response.config.url.indexOf('/member/auth/') >= 0 && response.data?.data?.accessToken) {
|
||||||
$store('user').setToken(response.data.data.accessToken, response.data.data.refreshToken);
|
$store('user').setToken(response.data.data.accessToken, response.data.data.refreshToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 自定处理【loading 加载中】:如果需要显示 loading,则关闭 loading
|
// 自定处理【loading 加载中】:如果需要显示 loading,则关闭 loading
|
||||||
response.config.custom.showLoading && closeLoading();
|
response.config.custom.showLoading && closeLoading();
|
||||||
|
|
||||||
// 自定义处理【error 错误提示】:如果需要显示错误提示,则显示错误提示
|
// 自定义处理【error 错误提示】:如果需要显示错误提示,则显示错误提示
|
||||||
if (response.data.code !== 0) {
|
if (response.data.code !== 0) {
|
||||||
// 特殊:如果 401 错误码,则跳转到登录页 or 刷新令牌
|
// 特殊:如果 401 错误码,则跳转到登录页 or 刷新令牌
|
||||||
if (response.data.code === 401) {
|
if (response.data.code === 401) {
|
||||||
return refreshToken(response.config);
|
return refreshToken(response.config);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 错误提示
|
// 错误提示
|
||||||
if (response.config.custom.showError) {
|
if (response.config.custom.showError) {
|
||||||
uni.showToast({
|
uni.showToast({
|
||||||
title: response.data.msg || '服务器开小差啦,请稍后再试~',
|
title: response.data.msg || '服务器开小差啦,请稍后再试~',
|
||||||
icon: 'none',
|
icon: 'none',
|
||||||
mask: true,
|
mask: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 自定义处理【showSuccess 成功提示】:如果需要显示成功提示,则显示成功提示
|
// 自定义处理【showSuccess 成功提示】:如果需要显示成功提示,则显示成功提示
|
||||||
if (response.config.custom.showSuccess
|
if (
|
||||||
&& response.config.custom.successMsg !== ''
|
response.config.custom.showSuccess &&
|
||||||
&& response.data.code === 0) {
|
response.config.custom.successMsg !== '' &&
|
||||||
|
response.data.code === 0
|
||||||
|
) {
|
||||||
uni.showToast({
|
uni.showToast({
|
||||||
title: response.config.custom.successMsg,
|
title: response.config.custom.successMsg,
|
||||||
icon: 'none',
|
icon: 'none',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回结果:包括 code + data + msg
|
// 返回结果:包括 code + data + msg
|
||||||
return Promise.resolve(response.data);
|
return Promise.resolve(response.data);
|
||||||
},
|
},
|
||||||
(error) => {
|
(error) => {
|
||||||
const userStore = $store('user');
|
const userStore = $store('user');
|
||||||
const isLogin = userStore.isLogin;
|
const isLogin = userStore.isLogin;
|
||||||
let errorMessage = '网络请求出错';
|
let errorMessage = '网络请求出错';
|
||||||
if (error !== undefined) {
|
if (error !== undefined) {
|
||||||
switch (error.statusCode) {
|
switch (error.statusCode) {
|
||||||
case 400:
|
case 400:
|
||||||
errorMessage = '请求错误';
|
errorMessage = '请求错误';
|
||||||
break;
|
break;
|
||||||
case 401:
|
case 401:
|
||||||
errorMessage = isLogin ? '您的登陆已过期' : '请先登录';
|
errorMessage = isLogin ? '您的登陆已过期' : '请先登录';
|
||||||
// 正常情况下,后端不会返回 401 错误,所以这里不处理 handleAuthorized
|
// 正常情况下,后端不会返回 401 错误,所以这里不处理 handleAuthorized
|
||||||
break;
|
break;
|
||||||
case 403:
|
case 403:
|
||||||
errorMessage = '拒绝访问';
|
errorMessage = '拒绝访问';
|
||||||
break;
|
break;
|
||||||
case 404:
|
case 404:
|
||||||
errorMessage = '请求出错';
|
errorMessage = '请求出错';
|
||||||
break;
|
break;
|
||||||
case 408:
|
case 408:
|
||||||
errorMessage = '请求超时';
|
errorMessage = '请求超时';
|
||||||
break;
|
break;
|
||||||
case 429:
|
case 429:
|
||||||
errorMessage = '请求频繁, 请稍后再访问';
|
errorMessage = '请求频繁, 请稍后再访问';
|
||||||
break;
|
break;
|
||||||
case 500:
|
case 500:
|
||||||
errorMessage = '服务器开小差啦,请稍后再试~';
|
errorMessage = '服务器开小差啦,请稍后再试~';
|
||||||
break;
|
break;
|
||||||
case 501:
|
case 501:
|
||||||
errorMessage = '服务未实现';
|
errorMessage = '服务未实现';
|
||||||
break;
|
break;
|
||||||
case 502:
|
case 502:
|
||||||
errorMessage = '网络错误';
|
errorMessage = '网络错误';
|
||||||
break;
|
break;
|
||||||
case 503:
|
case 503:
|
||||||
errorMessage = '服务不可用';
|
errorMessage = '服务不可用';
|
||||||
break;
|
break;
|
||||||
case 504:
|
case 504:
|
||||||
errorMessage = '网络超时';
|
errorMessage = '网络超时';
|
||||||
break;
|
break;
|
||||||
case 505:
|
case 505:
|
||||||
errorMessage = 'HTTP 版本不受支持';
|
errorMessage = 'HTTP 版本不受支持';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (error.errMsg.includes('timeout')) errorMessage = '请求超时';
|
if (error.errMsg.includes('timeout')) errorMessage = '请求超时';
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
if (error.errMsg.includes('Network'))
|
if (error.errMsg.includes('Network'))
|
||||||
errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
|
errorMessage = window.navigator.onLine ? '服务器异常' : '请检查您的网络连接';
|
||||||
// #endif
|
// #endif
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error && error.config) {
|
if (error && error.config) {
|
||||||
if (error.config.custom.showError === false) {
|
if (error.config.custom.showError === false) {
|
||||||
uni.showToast({
|
uni.showToast({
|
||||||
title: error.data?.msg || errorMessage,
|
title: error.data?.msg || errorMessage,
|
||||||
icon: 'none',
|
icon: 'none',
|
||||||
mask: true,
|
mask: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
error.config.custom.showLoading && closeLoading();
|
error.config.custom.showLoading && closeLoading();
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
|
// Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
|
||||||
let requestList = [] // 请求队列
|
let requestList = []; // 请求队列
|
||||||
let isRefreshToken = false // 是否正在刷新中
|
let isRefreshToken = false; // 是否正在刷新中
|
||||||
const refreshToken = async (config) => {
|
const refreshToken = async (config) => {
|
||||||
// 如果当前已经是 refresh-token 的 URL 地址,并且还是 401 错误,说明是刷新令牌失败了,直接返回 Promise.reject(error)
|
// 如果当前已经是 refresh-token 的 URL 地址,并且还是 401 错误,说明是刷新令牌失败了,直接返回 Promise.reject(error)
|
||||||
if (config.url.indexOf('/member/auth/refresh-token') >= 0) {
|
if (config.url.indexOf('/member/auth/refresh-token') >= 0) {
|
||||||
return Promise.reject('error')
|
return Promise.reject('error');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
|
// 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
|
||||||
if (!isRefreshToken) {
|
if (!isRefreshToken) {
|
||||||
isRefreshToken = true
|
isRefreshToken = true;
|
||||||
// 1. 如果获取不到刷新令牌,则只能执行登出操作
|
// 1. 如果获取不到刷新令牌,则只能执行登出操作
|
||||||
const refreshToken = getRefreshToken()
|
const refreshToken = getRefreshToken();
|
||||||
if (!refreshToken) {
|
if (!refreshToken) {
|
||||||
return handleAuthorized()
|
return handleAuthorized();
|
||||||
}
|
}
|
||||||
// 2. 进行刷新访问令牌
|
// 2. 进行刷新访问令牌
|
||||||
try {
|
try {
|
||||||
|
@ -240,34 +242,34 @@ const refreshToken = async (config) => {
|
||||||
throw new Error('刷新令牌失败');
|
throw new Error('刷新令牌失败');
|
||||||
}
|
}
|
||||||
// 2.1 刷新成功,则回放队列的请求 + 当前请求
|
// 2.1 刷新成功,则回放队列的请求 + 当前请求
|
||||||
config.header.Authorization = 'Bearer ' + getAccessToken()
|
config.header.Authorization = 'Bearer ' + getAccessToken();
|
||||||
requestList.forEach((cb) => {
|
requestList.forEach((cb) => {
|
||||||
cb()
|
cb();
|
||||||
})
|
});
|
||||||
requestList = []
|
requestList = [];
|
||||||
return request(config)
|
return request(config);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
|
// 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
|
||||||
// 2.2 刷新失败,只回放队列的请求
|
// 2.2 刷新失败,只回放队列的请求
|
||||||
requestList.forEach((cb) => {
|
requestList.forEach((cb) => {
|
||||||
cb()
|
cb();
|
||||||
})
|
});
|
||||||
// 提示是否要登出。即不回放当前请求!不然会形成递归
|
// 提示是否要登出。即不回放当前请求!不然会形成递归
|
||||||
return handleAuthorized()
|
return handleAuthorized();
|
||||||
} finally {
|
} finally {
|
||||||
requestList = []
|
requestList = [];
|
||||||
isRefreshToken = false
|
isRefreshToken = false;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 添加到队列,等待刷新获取到新的令牌
|
// 添加到队列,等待刷新获取到新的令牌
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
requestList.push(() => {
|
requestList.push(() => {
|
||||||
config.header.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
|
config.header.Authorization = 'Bearer ' + getAccessToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
|
||||||
resolve(request(config))
|
resolve(request(config));
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理 401 未登录的错误
|
* 处理 401 未登录的错误
|
||||||
|
@ -279,22 +281,22 @@ const handleAuthorized = () => {
|
||||||
// 登录超时
|
// 登录超时
|
||||||
return Promise.reject({
|
return Promise.reject({
|
||||||
code: 401,
|
code: 401,
|
||||||
msg: userStore.isLogin ? '您的登陆已过期' : '请先登录'
|
msg: userStore.isLogin ? '您的登陆已过期' : '请先登录',
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/** 获得访问令牌 */
|
/** 获得访问令牌 */
|
||||||
const getAccessToken = () => {
|
export const getAccessToken = () => {
|
||||||
return uni.getStorageSync('token');
|
return uni.getStorageSync('token');
|
||||||
}
|
};
|
||||||
|
|
||||||
/** 获得刷新令牌 */
|
/** 获得刷新令牌 */
|
||||||
const getRefreshToken = () => {
|
export const getRefreshToken = () => {
|
||||||
return uni.getStorageSync('refresh-token');
|
return uni.getStorageSync('refresh-token');
|
||||||
}
|
};
|
||||||
|
|
||||||
const request = (config) => {
|
const request = (config) => {
|
||||||
return http.middleware(config);
|
return http.middleware(config);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default request;
|
export default request;
|
||||||
|
|
Loading…
Reference in New Issue