hookehuyr

feat(auth): 添加认证请求头管理功能

在登录时设置用户ID和Token到请求头,并在登出或401时清除
新增setAuthHeaders和clearAuthHeaders工具函数
确保每个请求都携带最新的用户认证信息
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
10 import { ref, provide, inject, onMounted } from 'vue' 10 import { ref, provide, inject, onMounted } from 'vue'
11 import { logoutAPI, getUserInfoAPI } from '@/api/users' 11 import { logoutAPI, getUserInfoAPI } from '@/api/users'
12 import { getAuthInfoAPI } from '@/api/auth' 12 import { getAuthInfoAPI } from '@/api/auth'
13 +import { clearAuthHeaders, setAuthHeaders } from '@/utils/axios'
13 14
14 // 创建认证上下文的Symbol key,用于provide/inject依赖注入 15 // 创建认证上下文的Symbol key,用于provide/inject依赖注入
15 // 使用Symbol确保key的唯一性,避免命名冲突 16 // 使用Symbol确保key的唯一性,避免命名冲突
...@@ -116,6 +117,8 @@ export function provideAuth() { ...@@ -116,6 +117,8 @@ export function provideAuth() {
116 // 清理本地存储的用户信息和登录时间戳 117 // 清理本地存储的用户信息和登录时间戳
117 localStorage.removeItem('currentUser') 118 localStorage.removeItem('currentUser')
118 // localStorage.removeItem('loginTimestamp') 119 // localStorage.removeItem('loginTimestamp')
120 + // 清除认证请求头
121 + clearAuthHeaders()
119 } 122 }
120 } catch (error) { 123 } catch (error) {
121 console.error('注销失败:', error) 124 console.error('注销失败:', error)
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
2 * @Author: hookehuyr hookehuyr@gmail.com 2 * @Author: hookehuyr hookehuyr@gmail.com
3 * @Date: 2022-05-28 10:17:40 3 * @Date: 2022-05-28 10:17:40
4 * @LastEditors: hookehuyr hookehuyr@gmail.com 4 * @LastEditors: hookehuyr hookehuyr@gmail.com
5 - * @LastEditTime: 2025-06-13 09:56:29 5 + * @LastEditTime: 2025-07-01 16:23:59
6 * @FilePath: /mlaj/src/utils/axios.js 6 * @FilePath: /mlaj/src/utils/axios.js
7 * @Description: 7 * @Description:
8 */ 8 */
...@@ -17,10 +17,40 @@ axios.defaults.params = { ...@@ -17,10 +17,40 @@ axios.defaults.params = {
17 }; 17 };
18 18
19 /** 19 /**
20 + * 设置用户认证信息到请求头
21 + * @param {string} userId - 用户ID
22 + * @param {string} userToken - 用户Token
23 + */
24 +export const setAuthHeaders = (userId, userToken) => {
25 + if (userId && userToken) {
26 + axios.defaults.headers['User-Id'] = userId;
27 + axios.defaults.headers['User-Token'] = userToken;
28 + }
29 +};
30 +
31 +/**
32 + * 清除用户认证信息
33 + */
34 +export const clearAuthHeaders = () => {
35 + delete axios.defaults.headers['User-Id'];
36 + delete axios.defaults.headers['User-Token'];
37 +};
38 +
39 +/**
20 * @description 请求拦截器 40 * @description 请求拦截器
21 */ 41 */
22 axios.interceptors.request.use( 42 axios.interceptors.request.use(
23 config => { 43 config => {
44 + /**
45 + * 司总授权信息
46 + * 动态获取 user_info 并设置到请求头
47 + * 确保每个请求都带上最新的 user_info
48 + */
49 + const user_info = localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')) : {};
50 + if (user_info) {
51 + config.headers['User-Id'] = user_info.user_id;
52 + config.headers['User-Token'] = user_info.HTTP_USER_TOKEN;
53 + }
24 // const url_params = parseQueryString(location.href); 54 // const url_params = parseQueryString(location.href);
25 // GET请求默认打上时间戳,避免从缓存中拿数据。 55 // GET请求默认打上时间戳,避免从缓存中拿数据。
26 const timestamp = config.method === 'get' ? (new Date()).valueOf() : ''; 56 const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
...@@ -46,6 +76,8 @@ axios.interceptors.response.use( ...@@ -46,6 +76,8 @@ axios.interceptors.response.use(
46 if (response.data && response.data.code === 401) { 76 if (response.data && response.data.code === 401) {
47 // 清除用户登录信息 77 // 清除用户登录信息
48 localStorage.removeItem('currentUser'); 78 localStorage.removeItem('currentUser');
79 + // 清除认证请求头
80 + clearAuthHeaders();
49 // 跳转到登录页面,并携带当前路由信息 81 // 跳转到登录页面,并携带当前路由信息
50 const currentPath = router.currentRoute.value.fullPath; 82 const currentPath = router.currentRoute.value.fullPath;
51 router.push(`/login?redirect=${encodeURIComponent(currentPath)}`); 83 router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
......
...@@ -184,6 +184,7 @@ import { useTitle } from "@vueuse/core"; ...@@ -184,6 +184,7 @@ import { useTitle } from "@vueuse/core";
184 import { smsAPI } from "@/api/common"; 184 import { smsAPI } from "@/api/common";
185 import { showToast } from "vant"; 185 import { showToast } from "vant";
186 import UserAgreement from "@/components/ui/UserAgreement.vue"; 186 import UserAgreement from "@/components/ui/UserAgreement.vue";
187 +import { setAuthHeaders } from "@/utils/axios";
187 188
188 const userAgreementRef = ref(null); 189 const userAgreementRef = ref(null);
189 190
...@@ -278,6 +279,13 @@ const handleSubmit = async () => { ...@@ -278,6 +279,13 @@ const handleSubmit = async () => {
278 if (response.code !== 1) { 279 if (response.code !== 1) {
279 error.value = response.msg || "登录失败,请检查您的输入项"; 280 error.value = response.msg || "登录失败,请检查您的输入项";
280 return; 281 return;
282 + } else {
283 + // 获取data里面的 user_id, HTTP_USER_TOKEN, 并设置到后面所有的请求头里面,headers.User-Id, headers.User-Token
284 + const { user_id, HTTP_USER_TOKEN } = response?.data?.user_info || {};
285 + if (user_id && HTTP_USER_TOKEN) {
286 + // 设置认证请求头
287 + setAuthHeaders(user_id, HTTP_USER_TOKEN);
288 + }
281 } 289 }
282 290
283 const { code, data } = await getUserInfoAPI(); 291 const { code, data } = await getUserInfoAPI();
......