什么是单点登录(SSO)前端用 iframe 实现单点登录 超详细说明!!

桥志三 2024-07-14 17:33:01 阅读 80

目录

什么是单点登录

使用 iframe 实现单点登录


什么是单点登录?

单点登录的英文名叫做:Single Sign On(简称SSO)。

单点登录是一种身份验证过程,允许用户通过一次登录验证即可访问多个应用程序或服务。SSO的关键好处是提高了效率,减少了用户记住多个密码的负担,同时也简化了用户管理。

比如阿里系的淘宝和天猫,很明显地我们可以知道这是两个系统,但是你在使用的时候,登录了天猫,淘宝也会自动登录。

使用 iframe 实现单点登录

对于存在不同域名的系统,我们可以借助iframe的src属性解决跨域问题,然后用iframe的dom元素contentWindowpostMessage向iframe内嵌的网页传递数据,再在被内嵌的网页的代码中添加message事件截取消息,然后去保存token。

需要单点登录系统的域名

<code>// 需要单点登录的目标系统

export const SSOUrl = ["http://localhost:8080","http://localhost:3000","http://localhost:7777"];

系统中点击跳转的回调函数 

export const LoginByUsernameHandler = ({ commit }, userInfo) => {

return new Promise(resolve => {

// 登录接口

loginByUsername(userInfo).then(result => {

var res = result.data;

const data = res.data;

SSOUrl.forEach(item => {

// 创建子域的iframe, 用于传送数据

const iframe = document.createElement("iframe");

// 需要单点登录系统的域名

iframe.src = `${item}/localstorage.html`;

// 设置 ifream 为不可见

iframe.style.display = "none";

// 在节点的最后一个子节点之后插入节点,同时将节点中的字符串替换为等效的 Text 节点。

document.body.append(iframe);

// 使用 postMessage() 发送数据到子系统

setTimeout(function() {

let info = {

userInfo: data.UserInfo,

token: data.Token

};

iframe.contentWindow.postMessage(info, item);

}, 2000);

// 成功后销毁iframe

setTimeout(function() {

iframe.remove();

}, 4000);

});

});

});

}

需要实现免登录的系统下的 单点登录文件 

<code><!DOCTYPE html>

<html lang="zh">code>

<head>

<meta charset="utf-8">code>

<meta http-equiv="X-UA-Compatible" content="IE=edge">code>

<meta name="viewport" content="width=device-width,initial-scale=1.0">code>

<link rel="icon" href="<%= BASE_URL %>favicon.ico">code>

<title></title>

</head>

<body>

<noscript>

<strong>抱歉,javascript被禁用,请开启后重试。</strong>

</noscript>

<div >1111111</div>

</body>

<script>

// 在这个iframe所加载的HTML中绑定一个事件监听器,当事件被触发时,把接收到的token数据写入localStorage

window.addEventListener('message', function (event) {

console.log("子系统接受消息",event)

let tokenCache = { content:event.data.token,dataType : 'string' , datetime : new Date().getTime()}

localStorage.setItem('avue-token', JSON.stringify(tokenCache))

let userCache = { content:event.data.userInfo,dataType : 'string' , datetime : new Date().getTime()}

localStorage.setItem('avue-userInfo', JSON.stringify(userCache))

// console.log("coke",getCookie("Authorization"))

// setCookie("Authorization",event.data,60)

}, false);

</script>

</html>



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。