我们有一个角度上的应用程序,需要将用户重定向到登录页面(当用户未经身份验证或令牌过期时)。
我们使用一个HttpInterceptor来处理401HTTP状态代码(当然下面的源代码已经简化以使其更清晰)
@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的顶级文档。
有人有主意吗?
发布于 2018-05-23 08:42:57
防止iFrame重定向浏览器的一种方法是使用iframe标记上的sandbox属性。在你的例子中,你应该放这样的东西:
<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts">
这仍将允许它所允许的一切,例如顶部导航(这意味着更改父程序的url )。
您可以在这里找到更多有关它的信息:sandbox.asp
https://stackoverflow.com/questions/50483381
复制相似问题