我有一个会话在 20 分钟不活动后过期的应用程序。这个应用程序的用户很懒惰,所以我想他们会在早上喝完咖啡后继续使用这个应用程序,并且对与 Web API 通信会抛出的错误感到惊讶。我的想法是拦截重定向到登录页面,服务器可能会在会话到期后下次访问 Web API 时引发。
所以我写了一个拦截器:
@Injectable()
export class SessionEndInterceptor implements HttpInterceptor {
constructor() {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
{
const initialUrl = req.url;
return next.handle(req).pipe(
map((event: HttpEvent<any>) => {
const res = (event instanceof HttpResponse) && event as HttpResponse<any>;
if (res && this.checkIfSessionEnd(initialUrl, res.url)) {
window.location.href = this.replaceRedirectionWithCurrentLocation(
res.url
);
} else {
return event;
}
})
);
}
}
private checkIfSessionEnd(initialUrl: string, currentUrl: string): boolean {
const isInitialUrlLogin = this.isLoginUrl(initialUrl);
const isResponseUrlLogin = this.isLoginUrl(currentUrl);
const isRedirectionToLogin = !isInitialUrlLogin && isResponseUrlLogin;
return isRedirectionToLogin;
}
...
}
Run Code Online (Sandbox Code Playgroud)
但问题是这部分(event instanceof HttpResponse)永远不是真的,所以我不能做res.url和比较 URL。我想知道如何获取响应的 URL(或任何其他想法)。
更新
假设会话已过期。
1 - 客户端(Angular)按下按钮后,向服务器发出 GET 请求。
2 - 服务器(具体为 FormsAuthetication),检测到会话已过期,并发送 302 代码和登录页面的 URL。
3 - 客户端看到它并跟随它(没有办法阻止浏览器跟随重定向),然后向服务器发出另一个 GET 请求,要求登录页面。
4 - 现在客户端正在接收登录页面的 HTML,并抛出错误,因为它正在等待 JSON 格式的数据。
好吧,我想要的是,通过将初始请求的 URL 与当前 URL 进行比较,如果它们不同并且其中之一恰好是登录页面,则将客户端重定向window.location.href到登录页面,因此他别无选择如果他想继续工作,除了重新登录。
更新二
我知道无法检测到 302 重定向。所以我想要的是将登录页面的 200 响应的 URL 与初始响应(触发重定向到登录页面的那个)进行比较。
| 归档时间: |
|
| 查看次数: |
1862 次 |
| 最近记录: |