更改Iframe src属性无法使用超时,它会再次发送所有应用程序请求

问题描述 投票:0回答:1

这是我第一次使用iframe。

但是,我想在这里做的是,我想使用iframe静默刷新访问令牌。

主要思想是创建一个Iframe,只需将src属性更改为适当的URL即可获得新的访问令牌。

这是我正在执行的流程。

1)登录应用程序。

2)手动登录后获取访问令牌,然后设置超时以调用refreshToken方法,该方法将创建iFrame并将src属性更改为令牌路径。

3)成功获取令牌后,将其存储,然后重置超时以再次重复通话。

但是,我看到它最初可以工作,例如:

登录后,设置了超时时间(例如5秒钟),在5秒钟后,我可以看到存储了一个新令牌,并且有一个请求。但是,在重置超时后,由于请求取消,第二个调用被取消,第三个令牌未存储。

这是我正在做的事情的简单

storeToken(){
  // some code non relevant to the issue that handles a token and stores it
  this.setSilentLoginTimeout(5000);
  return token;
},
setSilentLoginTimeout(timeout) {
  if (this.timer) {
    console.log('clearing timeout');
    window.clearTimeout(this.timer);
  }
  const tokenUrl = this.getTokenUrl();
  this.timer = window.setTimeout(()=>this.refreshTokenSilently(tokenUrl), timeout);
},
refreshTokenSilently(tokenUrl) {
  let iframeElement = document.getElementById("myframe");
  if (iframeElement == null) {
    iframeElement = document.createElement("iframe");
    iframeElement.setAttribute("id", "myframe");
    iframeElement.setAttribute("target", "_self");
    iframeElement.setAttribute("style", "display:none");
    document.getElementsByTagName("body")[0].appendChild(iframeElement);
  }
  iframeElement.setAttribute("src", tokenUrl); // this will execute storeToken() when the iframe gets an access_token in the response url
},

storeToken()方法将在哈希号之后捕获我们从URL中获得的令牌,并将处理存储过程。

但是,我看到最初的呼唤

    iframeElement.setAttribute("src", tokenUrl);

工作,我们在框架中获得了一个令牌并将其存储起来,但是,我发现的问题是,在网络标签中,我可以看到所有API请求都被再次发送,就像重新加载应用程序一样!

但是,第二次致电

    iframeElement.setAttribute("src", tokenUrl);

不起作用,请求在“网络”标签中被取消

我在做什么错,是使用iframe刷新令牌还是更通用的使用iframe调用方法的正确方法?

为了清楚起见,假设我登录我的应用程序时,我们向后端发送了10个请求。

当iframe执行一个方法时,我在网络标签中看到它重新发送10个后端请求,这太奇怪了。

谢谢

javascript iframe oauth-2.0 access-token refresh-token
1个回答
0
投票

我认为使用OIDC Client Library是实现此目的的最佳方法。它具有对静默令牌更新的成熟支持。或者,您至少可以借鉴一些编码思想。

如果有帮助,this sample of mine显示如何在不重新加载整个页面的情况下集成iframe更新功能。

© www.soinside.com 2019 - 2024. All rights reserved.