vue 前端 用iframe实现单点登录

单点登录前端要做什么 前端如何实现单点登录 简单解决单点登录问题_糖糖246的博客-CSDN博客_单点登录前端需要做什么

前端在实现单点登录过程中,最主要的 是按照系统的要求 保存好 可以证明系统登录过的证据。

保存证据(下文统称其为token)的位置:1. localStorage,2. cookie

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

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

toNewPage(){
    //获取目标系统的登录证据token
    ...

    const iframe = document.createElement('iframe')
    //设置iframe样式,使其不可见
    iframe.setAttribute(
      'style',
      'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
    )
    iframe.setAttribute(
      'allow',
      'payment'
    )
    //将iframe地址改为目标系统
    iframe.src='http://127.0.0.1:8010/' 
    document.body.append(iframe)
    iframe.onload = () => {
      //发送消息,'http://127.0.0.1:8010'为目标系统网址,可改为‘*’
      iframe.contentWindow.postMessage({token:'***'},'http://127.0.0.1:8010')
      setTimeout(function () {
        iframe.remove()
      }, 5000)
      //新开页签,跳转到目标系统地址
      setTimeout(function () {
        window.open('http://127.0.0.1:8010/', '_blank')
      }, 0)
    }
}

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

<script>
  window.addEventListener('message',event => {
  const origin = [
    'http://localhost:8080',
    'http://127.0.0.1:8080',
    ...
  ]
    
  if(origin.includes(event.origin)){
    console.log(event)
    window.localStorage.setItem('cookie', event.data.tooken)
  }
})
</script>

 该方法只验证了点击按钮后,跳转到系统B,并且在localStorage中有了cookie记录,没有经过实际系统的检验。如果小伙伴们有什么问题,欢迎下方评论区留言~

当时还用其他方法实现了免登录,小伙伴们也可以瞅瞅

单点登录前端要做什么 前端如何实现单点登录 简单解决单点登录问题_糖糖246的博客-CSDN博客_单点登录前端需要做什么

猜你喜欢

转载自blog.csdn.net/weixin_59128282/article/details/125529323