vue3 最佳实战-实现单点登录

578 阅读1分钟
  1. 根据URL获取临时code标识来校验是否登录过
const url = window.location.href.replace('#/login', '')
const code = getQueryString(url, 'code')
  1. 如果没有cdoe或者code失效,需重定向到第三方登录页面(后端重定向)
// APP_CONFIG.baseURL请求地址  clientCode 客户端标识
window.location.href = `${APP_CONFIG.baseURL}/auth/login?clientCode=${APP_CONFIG.clientCode}`(相当于调用接口)
  1. 登录成功后,重定向到需进入的系统
重新执行步骤1
  1. 获取code成功之后,通过code获取token成功进入系统内部。
  2. 完整代码如下:
//登录接口
export function loginByCode(params) {
  return request({
    url:'接口路径',
    method: 'post',
    params
  }).then((res) => {
    const {access_token,refresh_token} = res.data
    setAccessToken(access_token);
    setRefreshToken(refresh_token);
    return res;
  });
}
//通过URL获取参数
export function getQueryString(url, paramName){
    if (!url) {
      url = window.location.href;
    }
    const queryStr = url.split('?')[1];
    if (!queryStr) {
      return null;
    }
    const queryParams = queryStr.split('&');
    for (const param of queryParams) {
      const [key, value] = param.split('=');
      if (decodeURIComponent(key) === paramName) {
        return decodeURIComponent(value);
      }
    }
    return null;
  }
//执行登录方法
const doLogin = async () => {
  const url = window.location.href.replace('#/login', '')
  const code = getQueryString(url, 'code')
  if (!code) {
    ssoLogin()
  } else { 
    try {
      const result = await loginByCode({
        code,
        clientCode:'客户端标识',
      })
      if (result.code == 200) { 
        window.location.href = '/'
      }
     } catch (error) { 
    }
   
  }
}
const ssoLogin = () => {
  window.location.href = `${APP_CONFIG.baseURL}/auth/login?clientCode=${APP_CONFIG.clientCode}`
}