Angular 并且iframe没有正确的重定向window

Angular and Iframe does not redirect the right window

我们在 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);
                }
            });
    });
}

}

当使用 URL 之类的 https://localhost:4200

从浏览器启动应用程序时一切正常

但是现在,我们需要将我们的应用程序包含在 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的顶层文档。

有人有想法吗?

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

<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts">

这将仍然允许它过去允许的所有内容,接受顶部导航(这意味着更改父级的 url。

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