使用Iframe+Post请求的方式嵌入第三方页面

使用Iframe+Post请求的方式嵌入第三方页面,第1张

背景描述

本身我们有自己的一个系统,之后采购了一个新系统,新系统的页面要嵌入到我们自己系统页面来,两个系统之间的权限交互通过token来进行传递和认证。本身嵌入采用如下方式就非常简单了,就是常规的iframe嵌入页面的方式

//常规的iframe嵌入页面的方式
<iframe :src="this.txtUrl" frameborder="0" width="100%" :style="{height:calHeight}" scrolling="auto"></iframe>

//scrpit部分
data() {
      return {
        txtUrl: "http://domain?token=XXX",
      }
    },

但是安全部门认为这种方式不安全,应该用Post方式嵌入,所以开始尝试Post嵌入页面的过程
所以可以总结需求为:假设我们自己页面的域名是localhost:8080,称为主页面,需要嵌入的页面域名是localhost:8082,称为嵌入页面,点击localhost:8080的一个菜单栏(或者按钮),页面就需要去加载localhost:8082的首页面,并完成权限交互;

具体做法

1.因为要模拟post请求,而且要把token这个参数传递过去,所以主页面的前端可以采用iframe+form表单的形式完成post请求的提交,代码如下:

//页面部分
<div style="height: 100%;">

     <form id="idForm" action="http://localhost:8766/getTest" method="post" target="iframe">
       <input id="input1" type="hidden" name="token" value="">
     </form>
     <iframe name="iframe" id="librarySearch" class="exportTable" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>
   </div>
//这个button就模拟了在域名是localhost:8080的页面点击菜单栏,加载页面的过程
   <button @click="clickFun"></button>
//============================================================================
//scrpit部分
methods: {
   clickFun(){
     document.getElementById("input1").value ="123";
     document.getElementById("idForm").submit(); // 触发form中submit方法

   }

如上,这个button就模拟了在域名是主页面的页面点击菜单栏,加载页面的过程。主页面需要携带token过去,clickFun模拟了主页面传递给其token的过程,在实际生产中,这个token可能需要和主页面所在的后端服务交互产生。

2.iframe中的action=“http://localhost:8766/getTest” 是嵌入页面对应的后端提供的一个接口,这个接口会完成token的接收、向页面种cookie,并且返回一个302的response,重定向到嵌入页面,这样主页面请求了这个接口之后,就会完成页面的重定向,iframe里面的内容就会完成页面刷新,变为第三方页面。
http://localhost:8766/getTest这个服务代码为:

//嵌入页面的服务端口:8766
 @PostMapping(value = "/getTest")
   public void getTokenPost(HttpServletResponse response, @RequestParam String token) {
       response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);

       Cookie cookie = new Cookie("XXX", "XXX");
       cookie.setMaxAge(1000); // Cookie的存活时间(自定义)
       cookie.setPath("/"); // 默认路径
       response.addCookie(cookie);
       response.setHeader("Location", "http://localhost:8080/");//Location为嵌入页面的地址
   }

3.运行起来之后,就可以完成iframe通过post请求的方式嵌入第三方页面,并完成认证的过程了

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/945341.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存