Просмотр исходного кода

fix: SSO登录后跳转主页又跳回登录页的问题

根因:SSO回调成功后,token存入localStorage但initialState.currentUser仍为undefined,
layout的onPageChange检查到currentUser为空即跳转登录。

修复:
1. SSO回调换码成功后获取用户信息并更新initialState.currentUser
2. layout onPageChange加兜底保护:localStorage有token时不因currentUser为空跳转登录
kinglee 1 неделя назад
Родитель
Сommit
782a6a0359
2 измененных файлов с 23 добавлено и 2 удалено
  1. 5 1
      src/layouts/index.tsx
  2. 18 1
      src/pages/auth/callback/index.tsx

+ 5 - 1
src/layouts/index.tsx

@@ -294,8 +294,12 @@ export default (props: any) => {
     }
 
     // if user is not logged in, redirect to login page
+    // but skip if token exists in localStorage (SSO just completed, initialState not yet updated)
     if (!initialState?.currentUser && location.pathname !== loginPath) {
-      history.push(loginPath);
+      const hasToken = localStorage.getItem('token');
+      if (!hasToken) {
+        history.push(loginPath);
+      }
     } else if (location.pathname === '/') {
       // Pick a landing route the caller can actually see. Access
       // extensions can narrow ``canSeeAdmin`` to ``false`` even when

+ 18 - 1
src/pages/auth/callback/index.tsx

@@ -1,8 +1,9 @@
 import { useEffect, useRef, useState } from 'react';
 import { Spin, message } from 'antd';
-import { history } from 'umi';
+import { history, useModel } from 'umi';
 import { request } from 'umi';
 import { DEFAULT_ENTER_PAGE } from '@/config/settings';
+import { queryCurrentUserState } from '@/services/profile/apis';
 
 /**
  * SSO 回调页面
@@ -12,6 +13,7 @@ import { DEFAULT_ENTER_PAGE } from '@/config/settings';
 const SSOCallback = () => {
   const [loading, setLoading] = useState(true);
   const processedRef = useRef(false);
+  const { setInitialState } = useModel('@@initialState') || {};
 
   useEffect(() => {
     const exchangeCode = async () => {
@@ -51,6 +53,21 @@ const SSOCallback = () => {
           }
           localStorage.setItem('user', JSON.stringify(result.data.user));
 
+          // 获取用户信息并更新 initialState,避免 onPageChange 跳转登录
+          try {
+            const userInfo = await queryCurrentUserState({
+              skipErrorHandler: true,
+            });
+            if (setInitialState) {
+              setInitialState((prev: any) => ({
+                ...prev,
+                currentUser: userInfo,
+              }));
+            }
+          } catch {
+            // 获取用户信息失败不影响登录流程,后续请求会处理
+          }
+
           message.success('登录成功');
           // 使用 replace 避免后退回到回调页
           history.replace(DEFAULT_ENTER_PAGE.user);