以安全的方式跨域 iframe

Cross domain iframe in a safe way

提问人:godhar 提问时间:8/24/2023 更新时间:8/24/2023 访问量:144

问:

我想看看在可以访问我们域的第三方域上使用 iframe 的安全性。我们希望避免身份验证,但它仍然需要安全。我正在使用 nuxt3 进行测试,因为我们的域运行这个。

我相信在前端域之间以及后端域之间使用是绕过同源策略的一种可以的方法。window.postMessage()"frame-ancestors": "domain-to-whitelist"

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        'frame-ancestors': ['https://localhost:3008']
      },
    },
  })
);

当我尝试调用 iframe 应显示的域时,我的浏览器仍然会抱怨。postMessage()

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3008') 
does not match the recipient window's origin ('null').

我无法让 POC 工作,我想知道这是否是一场大雁追逐,因为绕过同源策略是继承的坏主意

域 A - iframe 的父级

app.vue

   <iframe id="my-frame" sandbox="allow-scripts" height="200px" width="2000px"> 
    </iframe>
  
    onMounted(() => {
        document.getElementById('my-frame').contentWindow.postMessage({
        data: 'data',
     }, "http://parent-domain")
   })

域 B(内容 iframe 最终应显示)

nuxt.script.js

  const domainRequest = (e) => {
      console.log('parent event', e);
    };
  
    window.addEventListener('message', domainRequest, false);
JavaScript 节点.js iframe postmessage nuxt3

评论

0赞 CBroe 8/24/2023
您在 iframe 上没有属性,那么您实际在何时何地将内容加载到其中?现在,错误消息抱怨它的源是 null - 如果你当时没有从实际的 HTTP(S) 源加载任何内容到它,这将是有道理的。src
0赞 godhar 8/25/2023
是的,你是绝对正确的,我没有在任何地方引用孩子的起源。谢谢

答: 暂无答案