vben admin: logout退出时,访问接口时没有携带authorization

一,原因

根因:auth/logout 使用的是 baseRequestClient,而 Authorization 只配置在 requestClient 上。

调用链如下:

  1. 退出时调用 logoutApi():[auth.ts (line 46)](src/api/core/auth.ts:46)。
  2. logoutApi() 使用 baseRequestClient.post():[auth.ts (line 47)](src/api/core/auth.ts:47)。
  3. Authorization: Bearer xxx 仅在 requestClient 的请求拦截器中设置:[request.ts (line 64)](src/api/request.ts:64)。
  4. baseRequestClient 是另外创建的 Axios 实例,只设置了 baseURL,没有注册这个拦截器:[request.ts (line 114)](src/api/request.ts:114)。

所以请求不带 token。withCredentials: true 只是允许携带 Cookie,不会自动生成 Authorization。

这不是 token 提前被清空造成的,因为先执行 await logoutApi(),之后才执行 resetAllStores():[auth.ts (line 86)](src/store/auth.ts:86)。

历史原因是为了避免登出接口返回 401 后触发重新认证,再次调用登出形成递归,
因此曾将登出从 requestClient 改为 baseRequestClient。但这同时移除了自动附加 token 的能力。

二,解决:

在调用时显式传入token:

src/api/core/auth.ts

import { useAccessStore } from '@vben/stores';
/**
 * 退出登录
 */
export async function logoutApi() {
  const token = useAccessStore().accessToken;
  return baseRequestClient.post('/auth/logout', undefined, {
    withCredentials: true,
    headers: {
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
  });
}

 

posted @ 2026-10-26 22:11  刘宏缔的架构森林  阅读(10)  评论(0)    收藏  举报