- 根据URL获取临时code标识来校验是否登录过
const url = window.location.href.replace('#/login', '')
const code = getQueryString(url, 'code')
- 如果没有cdoe或者code失效,需重定向到第三方登录页面(后端重定向)
window.location.href = `${APP_CONFIG.baseURL}/auth/login?clientCode=${APP_CONFIG.clientCode}`(相当于调用接口)
- 登录成功后,重定向到需进入的系统
重新执行步骤1
- 获取code成功之后,通过code获取token成功进入系统内部。
- 完整代码如下:
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;
});
}
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}`
}