在 iframe 中自动登录远程站点内部

auto login remote site inner in iframe

本文关键字:站点 内部 程站点 iframe 登录      更新时间:2023-09-26

我有一个现有的远程站点,该站点具有要访问的身份验证,现在我想使用 iframe 将此站点合并到我自己的站点中。是否有任何解决方案可以帮助在加载iframe时自动登录远程站点?

<iframe src="http://remote.com/list"></iframe>

如果要访问 http://remote.com/list,则需要登录,并且只能发布用户名/密码。加载 iframe 时如何自动登录?

以下是一些限制

  • 登录仅适用于开机自检方法
  • iframe/JavaScript存在跨域问题
  • 不提供登录 API
  • 在远程站点中无法进行其他修改

一切皆有可能。但是,由于泄露了对远程页面的访问详细信息,下面的解决方案非常不安全。

<form id="login" target="frame" method="post" action="http://remote.com/login">
    <input type="hidden" name="username" value="login" />
    <input type="hidden" name="password" value="pass" />
</form>
<iframe id="frame" name="frame"></iframe>
<script type="text/javascript">
    // submit the form into iframe for login into remote site
    document.getElementById('login').submit();
    // once you're logged in, change the source url (if needed)
    var iframe = document.getElementById('frame');
    iframe.onload = function() {
        if (iframe.src != "http://remote.com/list") {
            iframe.src = "http://remote.com/list";
        }
    }
</script>

usernamepassword输入的值在客户端是可读的。

如果您拥有其他站点,则可以尝试通过某些令牌进行身份验证。

将授权令牌传递到 iframe 中的 URL。

这是我执行此操作的实现。但这并不能解决跨域问题。对于跨域问题,您可以尝试使用jQuery的JSONP方法(我还没有尝试将jQuery与此解决方案结合使用)。

<iframe id="MyIFrame" width="400" height="400"></iframe>
<script type="text/javascript">
    var iframeURL = 'http://mysite.com/path/applicationPage.aspx';
    var iframeID = 'MyIFrame';
    function loadIframe(){
        //pre-authenticate
        var req = new XMLHttpRequest();
        req.open("POST",this.iframeURL, false, "username", "password"); //use POST to safely send combination
        req.send(null); //here you can pass extra parameters through
        //setiFrame's SRC attribute
        var iFrameWin = document.getElementById(this.iframeID);
        iFrameWin.src = this.iframeURL + "?extraParameters=true";
    }
    //onload, call loadIframe() function
    loadIframe();   
</script>

做不到。就这么简单。跨域限制非常专门用于阻止您执行此类操作。

唯一的例外是,如果您是远程站点的所有者并完全控制服务器,因此您可以添加 CORS 标头以允许您自己的外部服务权限访问它。