本地主机:提供的 postMessage 目标来源与收件人窗口的来源不匹配

Amd*_*Ali 3 html javascript node.js reactjs

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

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

这是一些代码:

应用程序.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>
    )
  }
Run Code Online (Sandbox Code Playgroud)

登录选项卡

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;
Run Code Online (Sandbox Code Playgroud)

这是节点响应:

身份验证.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'));

    }
);
Run Code Online (Sandbox Code Playgroud)

成功.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>
Run Code Online (Sandbox Code Playgroud)

问题是,在身份验证后,由于此错误,我无法关闭弹出窗口:

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

我试图将 success.html 中的 window.opener.location 更改为 'localhost:3000' 并且它完美运行,但对于生产环境来说这不是一个好主意。

Amd*_*Ali 5

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

window.opener.postMessage(
      {
        status: 'success'
      },
      '*'
    );
Run Code Online (Sandbox Code Playgroud)

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

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

希望这会帮助某人。