'-'
zhangwei
2025-07-07 85428f0bf3bbf08d65200cffc38dd1e96af34da6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { removeToken, setToken, type DataInfo } from "./auth";
import { subBefore, getQueryMap } from "@pureadmin/utils";
 
/**
 * 简版前端单点登录,根据实际业务自行编写,平台启动后本地可以跳后面这个链接进行测试 http://localhost:8848/#/permission/page/index?username=sso&roles=admin&accessToken=eyJhbGciOiJIUzUxMiJ9.admin
 * 划重点:
 * 判断是否为单点登录,不为则直接返回不再进行任何逻辑处理,下面是单点登录后的逻辑处理
 * 1.清空本地旧信息;
 * 2.获取url中的重要参数信息,然后通过 setToken 保存在本地;
 * 3.删除不需要显示在 url 的参数
 * 4.使用 window.location.replace 跳转正确页面
 */
(function () {
  // 获取 url 中的参数
  const params = getQueryMap(location.href) as DataInfo<Date>;
  const must = ["username", "roles", "accessToken"];
  const mustLength = must.length;
  if (Object.keys(params).length !== mustLength) return;
 
  // url 参数满足 must 里的全部值,才判定为单点登录,避免非单点登录时刷新页面无限循环
  let sso = [];
  let start = 0;
 
  while (start < mustLength) {
    if (Object.keys(params).includes(must[start]) && sso.length <= mustLength) {
      sso.push(must[start]);
    } else {
      sso = [];
    }
    start++;
  }
 
  if (sso.length === mustLength) {
    // 判定为单点登录
 
    // 清空本地旧信息
    removeToken();
 
    // 保存新信息到本地
    setToken(params);
 
    // 删除不需要显示在 url 的参数
    delete params.roles;
    delete params.accessToken;
 
    const newUrl = `${location.origin}${location.pathname}${subBefore(
      location.hash,
      "?"
    )}?${JSON.stringify(params)
      .replace(/["{}]/g, "")
      .replace(/:/g, "=")
      .replace(/,/g, "&")}`;
 
    // 替换历史记录项
    window.location.replace(newUrl);
  } else {
    return;
  }
})();