I have an application with a session that expires after 20 minutes of inactivity. The users of this application are quite lazy, so I suppose they will continue working with the application after their morning coffee and be surprised by the errors the communication with the web API will throw. My idea is to intercept the redirection to the login page the server may provoke with the next access to the web API after the session expiration.
So I wrote an interceptor:
@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;
}
...
}
But the problem is that this part (event instanceof HttpResponse)
is never true, so I can't do res.url
and compare the URLs. I would like to know how I can obtain the URL of the response (or any other idea).
UPDATE
Let's suppose the session has expired.
1 - The client (Angular), after pressing a button, makes a GET request to the server.
2 - The server (concretely FormsAuthetication), detects that the session has expired, and sends a 302 code and the URL of the login page.
3 - The client sees it and follows it (there's no way to prevent the browser from following a redirection), and then makes another GET request to the server asking for the login page.
4 - Now the client is receiving the HTML of the login page, and throws an error, because it's waiting for data as JSON.
Well, what I want is, by comparing the URL of the initial request with the current URL and, if they are different and one of them happens to be the login page, redirect the client with window.location.href
to the login page, so he has no option other than login again if he wants to continue working.
UPDATE II
I know 302 redirections aren't possible to detect. So what I want is compare the URL of the 200 response of the login page with the initial one (the one that triggered the redirection to the login page).