【问题标题】:Angular and Iframe does not redirect the right windowAngular 和 Iframe 不会重定向正确的窗口
【发布时间】:2018-05-23 08:25:59
【问题描述】:

我们在 Angular 中有一个应用程序,我们需要将用户重定向到登录页面(当用户未通过身份验证或令牌已过期时)。

我们使用一个 HttpInterceptor 来处理 401 HTTP 状态码(下面的源代码当然被简化了,更清楚)

@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
  constructor(private router: Router, private inj: Injector, @Inject(DOCUMENT) private document: any) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        const headers = new HttpHeaders({
            'X-Requested-With': 'XMLHttpRequest',
        });

        const changedReq = req.clone({ headers, withCredentials: true });

        return next.handle(changedReq)
            .map((event: HttpEvent<any>) => {
                return event;
            })
            .do(event => {
            })
            .catch((err: any, caught) => {
                if (err instanceof HttpErrorResponse) {
                    switch (err.status) {
                        case 401:
                          this.document.location.href = <external-url> 
                          return Observable.throw(err);
                        default:
                          return Observable.throw(err);
                    }
                } else {
                    return Observable.throw(err);
                }
            });
    });
}

}

当应用程序从带有https://localhost:4200 之类的 URL 的浏览器启动时,一切正常

但是现在,我们需要将我们的应用程序包含在 iframe 中(我们不会成为父容器的所有者)。

为了在 iframe 中测试我们的应用程序,我们有以下 HTML

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>My Fake Portal</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
    <h1>My Fake Portal</h1>
    <br/>
    <br/>

    <iframe width="100%" src="https://localhost:4200"></iframe>
</body>

</html>

集成有效,但是当 HttpInterceptor 尝试使用 this.document.location.href 访问登录页面时,它会重定向浏览器而不是重定向 iframe(然后销毁父容器)。

this.document 应该是当前文档,而不是 DOM 的顶部文档。

有人有想法吗?

【问题讨论】:

    标签: angular iframe single-sign-on


    【解决方案1】:

    防止 iFrame 重定向浏览器的一种方法是使用 iframe 标记上的 sandbox 属性。在你的情况下,你应该这样写:

    &lt;iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts"&gt;

    这仍然会允许它过去允许的一切,除了顶部导航(这意味着更改父级的 url。

    您可以在此处找到有关它的更多信息:https://www.w3schools.com/tags/att_iframe_sandbox.asp

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多