【问题标题】:localhost : postMessage target origin provided does not match the recipient window's originlocalhost : 提供的 postMessage 目标来源与收件人窗口的来源不匹配
【发布时间】:2020-02-03 02:38:06
【问题描述】:

所以我正在尝试构建一个使用 sso 对用户进行身份验证的应用程序。这是工作流程:

  • 在 localhost:3000 上启动应用程序(我正在使用一个反应单一的网络 申请)
  • 将显示一个弹出窗口(实际上弹出窗口将调用我的节点 js 身份验证路由 localhost:4000/authenticate 将用户重定向到 sso 身份验证页面)
  • 认证后sso服务器会将用户重定向到节点回调路由(http://localhost:4000/authenticate/callback
  • node检查这是否是一个有效的用户并返回一个成功消息(实际上node会发送一个html + javascript代码来关闭弹出窗口)。
  • 如果收到消息成功,我们会让用户加载应用程序

这里有一些代码:

App.js

 handleLogIn() {
    const msg = loginTab('http://localhost:4000/authenticate');
    msg.then(response => {
      console.log(response)
    });
  }

  render() {


    let loginButton = (<button onClick={this.handleLogIn.bind(this)}>Sign in</button>)

    return (
      <div>
        {loginButton}
      </div>
    )
  }

loginTab.js

const loginTab = (myUrl) => {
  const windowArea = {
    width: Math.floor(window.outerWidth * 0.8),
    height: Math.floor(window.outerHeight * 0.5),
  };

  if (windowArea.width < 1000) { windowArea.width = 1000; }
  if (windowArea.height < 630) { windowArea.height = 630; }
  windowArea.left = Math.floor(window.screenX + ((window.outerWidth - windowArea.width) / 2));
  windowArea.top = Math.floor(window.screenY + ((window.outerHeight - windowArea.height) / 8));

  const sep = (myUrl.indexOf('?') !== -1) ? '&' : '?';
  const url = `${myUrl}${sep}`;
  const windowOpts = `toolbar=0,scrollbars=1,status=1,resizable=1,location=1,menuBar=0,
    width=${windowArea.width},height=${windowArea.height},
    left=${windowArea.left},top=${windowArea.top}`;

  const authWindow = window.open(url, '_blank', windowOpts);
  // Create IE + others compatible event handler
  const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
  const eventer = window[eventMethod];
  const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';

  // Listen to message from child window
  const authPromise = new Promise((resolve, reject) => {
    eventer(messageEvent, (msg) => {
      if (!~msg.origin.indexOf(`${window.location.protocol}//${window.location.host}`)) {
        authWindow.close();
        reject('Not allowed');
      }

      if (msg.data.payload) {
        try {
          resolve(JSON.parse(msg.data.payload));
        }
        catch(e) {
          resolve(msg.data.payload);
        }
        finally {
          authWindow.close();
        }
      } else {
        authWindow.close();
        reject('Unauthorised');
      }
    }, false);
  });

  return authPromise;
};

export default loginTab;

这是节点响应:

身份验证.js

router.post(process.env.SAML_CALLBACK_PATH,
    function (req, res, next) {
        winston.debug('/Start authenticate callback ');
        next();
    },
    passport.authenticate('samlStrategy'),
    function (req, res, next) {

        winston.debug('Gsuite user successfully authenticated , email : %s', req.user.email)
        return res.sendFile(path.join(__dirname + '/success.html'));

    }
);

成功.html

<!doctype html>
<html lang="fr">
<head>
  <title>Login successful</title>
</head>
<body>
  <h1>Success</h1>
  <p>You are authenticated...</p>
</body>
<script>
  document.body.onload = function() {

    console.log( window.opener.location)
    window.opener.postMessage(
      {
        status: 'success'
      },
      window.opener.location
    );
  };
</script>
</html>

问题是验证后我无法关闭弹出窗口,因为这个错误:

在“DOMWindow”上执行“postMessage”失败:提供的目标源(“http://localhost:4000”)与接收窗口的源(“http://localhost:3000”)不匹配。

我尝试将 success.html 中的 window.opener.location 更改为 'localhost:3000' 并且效果很好,但对于生产环境来说这不是一个好主意。

【问题讨论】:

  • 听起来像是 CSP 错误。也许看看这个。 ponyfoo.com/articles/content-security-policy-in-express-apps
  • 感谢您的帮助马克,但对我来说这似乎不是一个安全问题,因为我正在禁用 chorme 安全性(使用此选项 --disable-web-security)并且它工作正常如果我将 window.opener.location 更改为 localhost:3000
  • developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… 该错误肯定来自框架祖先问题。我刚刚使用 PostMessage API 完成了一个项目并抛出了那个错误。这就是我修复它的方法。
  • 感谢您的评论马克。我尝试使用 frameguard 将 Header 添加到我的响应中 [现在我收到了这个 X-Frame-Options: ALLOW-FROM localhost:3000 ] 但不幸的是我仍然有同样的错误。
  • stackoverflow.com/questions/10205192/… 阅读此内容。这应该可以解决您的问题(我希望)=)

标签: javascript html node.js reactjs


【解决方案1】:

好吧,我尝试了很多方法,并使用这种技术解决了我的问题。 在开发环境中,我使用了一颗星来让它工作(这不是一个好习惯)。

window.opener.postMessage(
      {
        status: 'success'
      },
      '*'
    );

在生产中,我使用的是真实域名而不是像这样的本地主机:

window.opener.postMessage(
      {
        status: 'success'
      },
      'http://my-server-domain:3000'
    );

希望这会对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2019-12-30
    • 2019-05-25
    • 2021-05-26
    • 2018-01-15
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多