【发布时间】: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