chenfei-hnu / Blog

个人整理的跟前端相关的文档 ( This is some front-end development related documentation )
9 stars 2 forks source link

SSO远程登录解决方案 #60

Open chenfei-hnu opened 2 years ago

chenfei-hnu commented 2 years ago

SSO远程登录 在一个统一登录平台上,使用对端提供的远程登录方案,比如利用jwt生成token,再通过cookie传token进行验证登录等不需要输入账号密码的方式进行认证登录 1.cookie传token 统一登录平台根据对端要求生成token,拼接合理的cookie,并在访问对端时,带上cookie进行认证 2.url传token 使用cookie进行传值,会有一些同源限制,如果是iframe内嵌会出现问题,可以使用url传值解决 3.纯前端利用form自动登录,需要账号密码,非SSO方案

<body>
</body>
<script>
    const openPostWindow = () =>{
        // 创建 form 表单
        let data = {
            username: 'admin',
            password: 'admin'
        };
        let name = '_self';
        let url = 'http://xxx/login';
        let tempForm = document.createElement('form');
        tempForm.id = 'tempForm';
        tempForm.action = url;
        tempForm.method = 'post';
        tempForm.target = name;

        // 创建 用户名输入框
        let userName = document.createElement('input');
        userName.type = 'hidden';
        userName.name = 'email';
        userName.value = data.username;

        // 创建 密码输入框
        let passWord = document.createElement('input');
        passWord.type = 'hidden';
        passWord.name = 'password';
        passWord.value = data.password;

        tempForm.appendChild(userName);
        tempForm.appendChild(passWord);    

        // 将 form 表单插入 body
        document.body.appendChild(tempForm);

        // 增加提交监听 处理浏览器的兼容性
        if (window.attachEvent) {
            tempForm.attachEvent('onsubmit', () => { window.open(url, name); });
        } else if (window.addEventListener) {
            tempForm.addEventListener('onsubmit', () => { window.open(url, name); });  
        }

        // 触发监听 处理浏览器的兼容性
        if(tempForm.fireEvent){
            tempForm.fireEvent('onsubmit');
        }else{
            let evt = document.createEvent('HTMLEvents');
            evt.initEvent('onsubmit', true, true);
            tempForm.dispatchEvent(evt);
        }

        // form 表单提交事件
        tempForm.submit();
        // 从 body 中移除 form 表单
        document.body.removeChild(tempForm);

    }
    openPostWindow();
</script>