vue 前端 用iframe实现单点登录两个不同域名Vue项目相互跳转并且传递Token

coldriversnow 2024-08-18 17:33:01 阅读 93

什么是单点登录

单点登录,字面意思 :仅点一次就可以登录。

       在公司的业务系统中,往往会有多个系统,并且这几个系统对应的都是同一个登录接口。次次登录对于公司用户体验肯定是不好的,对于后端上请求登录接口的频率也会增多。所以就有了这个单点登录:多个系统使用同一个登录接口,只需要登录一次就可以使得多个系统免登进入。

A网页:

<code> data: function() {

return {

qdmDdUrl: 'http://127.0.0.1:8081/#/Loginst?dd=1',

Isdddl: false

};

},

Jumpshuangd() {

var that = this;

this.Isdddl = true;

var token = '', username = 'AAA', password = 'BBB';

axios

.ajax({

url: 'xxxxxxxxxx',

method: 'post',

isShowLoading: false,

data: {

username: username,

password: password,

}

}).then(res => {

token = res.data.access_token;

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

//设置iframe样式,使其不可见

iframe.setAttribute(

'style',

'position:absolute;width:10px;height:10px;left:-20px;top:-20px;'

);

iframe.setAttribute(

'allow',

'payment'

);

//将iframe地址改为目标系统

iframe.src = this.qdmDdUrl;

document.body.append(iframe);

iframe.onload = () => {

iframe.contentWindow.postMessage(

{ token: token, name: username },//可以以对象形式传参,也可以直接传字符串"aaa"

that.qdmDdUrl//嵌入页面的路径,也可以直接传"*"

);

setTimeout(function() {

iframe.remove();

}, 5000);

// //新开页签,跳转到目标系统地址

setTimeout(function() {

that.Isdddl = false;

window.open('http://127.0.0.1:8081/#/dashboard', '_blank');

}, 2000);

};

});

}

需要实现免登录的子系统,可在index.html中添加:

created() {

let that=this;

// 父页面发送的消息

let dd = this.$route.query.dd;

if (dd == 1) {

window.parent.postMessage('childLoaded', '*');

window.addEventListener('message',e => {

const origin = [

'http://http://127.0.0.1:8081',

'http://http://127.0.0.1:8080',

.....

]

if(origin.includes(event.origin)){

if (e.data.type == undefined) {

window.localStorage.setItem('cookie', event.data.tooken)

}

}

})

}

},



声明

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