SSO 登录流程、401 自动跳转、访客模式、请求拦截器与用户信息获取
简单来说,认证就是回答一个问题:"你是谁?"
想象你去公司大楼,门口有保安拦住你,你需要出示工牌(证明你是员工)才能进入。在 Web 应用中,这个"工牌"就是你的登录凭证(通常是 Cookie 或 Token)。
Kuai 前端使用公司的 SSO(单点登录)系统。整个流程就像一个"接力赛":
https://kuauth.example.com/loginpage,登录后重定向回来用代码表示整个流程:
// 用户打开浏览器访问 Kuai 浏览器 → Kuai 后端: GET /api/user/info (带 Cookie) // 场景 A:Cookie 有效 Kuai 后端 → 浏览器: 200 OK { name: "张三", role: "admin" } // 场景 B:Cookie 无效或过期 Kuai 后端 → 浏览器: 401 Unauthorized 前端 JS 捕获 401 → window.location = "https://kuauth.example.com/loginpage?redirect=..." 用户在 SSO 页面登录 → SSO 重定向回 Kuai → 自动带上新 Cookie
你不需要在每个 API 调用里手动检查 401。项目在请求封装层统一处理了这个逻辑。
核心代码在 src/services/request/index.js:
// 简化后的核心逻辑 async function request(url, options = {}) { // 发送请求时自动带上 Cookie const response = await fetch(url, { ...options, credentials: 'include', // 关键!携带 Cookie }); // 检查 401 状态码 if (response.status === 401) { // 不是访客模式 → 跳转 SSO 登录 if (!isGuestMode()) { window.location.href = 'https://kuauth.example.com/loginpage' + '?redirect=' + encodeURIComponent(window.location.href); } return { data: null, err: 'Unauthorized' }; } // 正常返回 { data, err } 结构 const data = await response.json(); return { data, err: null }; }
浏览器默认不会在跨域请求中携带 Cookie。credentials: 'include' 告诉浏览器:"这个请求需要带上 Cookie",这样后端才能识别你是谁。
有时候你需要分享一个页面给外部用户,但对方没有公司账号。这时候就用到"访客模式"。
在 URL 后面加上 ?mode=guest:
// 正常访问(需要登录) https://kuai.example.com/share/abc123 // 访客模式(无需登录) https://kuai.example.com/share/abc123?mode=guest
| 行为 | 正常模式 | 访客模式 |
|---|---|---|
| 收到 401 时 | 跳转 SSO 登录页 | 返回空响应,不跳转 |
| 适用路由 | 所有页面 | 仅 /share/* |
| 用户信息 | 完整用户信息 | 无 / 匿名 |
请求封装中的判断逻辑:
// 检测是否为访客模式 function isGuestMode() { const params = new URLSearchParams(window.location.search); return params.get('mode') === 'guest'; } // 在 401 处理中使用 if (response.status === 401) { if (isGuestMode()) { // 访客模式:不跳转,静默处理 return { data: null, err: 'Guest: no auth' }; } else { // 正常模式:跳转登录 window.location.href = SSO_LOGIN_URL; } }
项目使用原生 fetch API 的封装(不是 Axios),但实现了类似"拦截器"的功能。
credentials: 'include'{ data, err } 对象?mode=guest 参数检测import request from '@/services/request'; import * as userServices from '@/services/modules/user'; // 方式一:使用模块化的 API 服务(推荐) const { data, err } = await userServices.getUserInfo(); if (err) { console.error('获取用户信息失败:', err); } else { console.log('你好,', data.name); } // 方式二:直接使用 request const { data, err } = await request('/api/custom-endpoint', { method: 'POST', body: JSON.stringify({ key: 'value' }), });
传统的 try-catch 会让代码嵌套很深。{ data, err } 模式让错误处理变成简单的 if 判断,代码更扁平、更易读。这是 Go 语言风格的错误处理思路。
登录成功后,前端需要获取当前用户的信息(姓名、头像、角色等)。
// src/services/modules/user.js import request from '@/services/request'; // 获取当前登录用户信息 export const getUserInfo = () => request('/api/user/info'); // 获取用户列表 export const getUserList = (params) => request('/api/user/list', { params });
// 在页面组件中 'use client'; import { useSelector } from 'react-redux'; import { useEffect } from 'react'; export default function DashboardPage() { // 从 Redux store 获取用户信息 const user = useSelector(state => state.user); return ( <div> <h1>欢迎回来, {user.name}</h1> <p>角色: {user.role}</p> </div> ); }
getUserInfo() APIdispatch 到 Redux storeuseSelector 读取用户信息
用户打开页面
│
▼
前端发送请求 (credentials: 'include')
│
▼
后端检查 Cookie ──── 有效 ──→ 返回 200 + 数据
│
无效/过期
▼
返回 401 Unauthorized
│
▼
前端拦截器捕获 401
│
├── 是访客模式? ──→ 返回空数据,不跳转
│
└── 不是访客 ──→ 跳转 SSO 登录页
│
▼
用户在 SSO 登录
│
▼
SSO 重定向回原页面
│
▼
前端重新请求(带新 Cookie)
│
▼
后端验证通过 → 返回数据