前端实现单点登录
# 前端单点登录
为了把多个系统内部做成单点登录,各个系统又部署在不同域名下,就变成跨域共享token,这时想到了淘宝天猫的单点登录,而淘宝天猫登录页面是通过iframe内嵌了一个淘宝登录页,在天猫登录页,实际上是走了淘宝登录页的接口,并且登录成功后cookie也是设在淘宝域名底下,在淘宝iframe中登录成功后,通过postMessage进行iframe父子窗口通讯,天猫登录页得知淘宝中已经登录成功,就会通过get请求,去请求淘宝的认证接口,此时就会带上淘宝域名下cookie中的token,认证接口认证token的有效性,并且返回token,此时天猫登录页节能拿到淘宝域名下的token,实现token共享
# postMessage跨域和dns解析,给父级发消息
window.parent.postMessage({
token: localStorage.getItem('token')
}, '*')
1
2
3
2
3
# 子系统接收token
window.addEventListener('message', (e) => {
if(e.data && e.data.token) {
localStorage.setItem('token',e.data.token)
} else {
let redirectUrl = window.location.href
window.location.href = `http://www.baidu.com/login?redirectUrl=${redirectUrl}`
}
})
let iframe = document.createElement('iframe')
iframe.width = 0
iframe.height = 0
iframe.style.display = none
document.body.appendChild(iframe)
iframe.src = 'http://localhost:8080'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
上次更新: 2024/04/26, 0:04:00