问题
I receive idToken
and I am also getting the expiration time expTime
in timestamp format eg: 1605803717
which basically expires in 1 day. I want to log the user out and redirect the user to login page if idToken
expires. I have implemented a HTTPInterceptor as below:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
this.token = JSON.parse(localStorage.getItem("getToken"));
if (this.tokenExpired(this.token)) {
Auth.signOut().then((res) => {
this.authState === "signedout";
this.router.navigate(["/login"]);
});
} else {
return;
}
}
private tokenExpired(token: number) {
const expiry = token;
return Math.floor(new Date().getTime() / 1000) >= expiry;
}
My question is to know if this implementation will work automatically I mean, will this interceptor automatically be triggered when idToken
expires or do I need to setup some kind of trigger? How does HTTPInterceptors work? Will it be able to catch time expiration and logout user or I have to implement something else to catch idToken
expiration?
回答1:
One way i have implemented it is to catch the Unauthorized error with code 401. And handle the error by in our case was to update the token using refreshToken but ofc you can logout and redirect if you wish so
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err) => {
// Unauthorized
if (err && err.status === 401) {
// Logout User
// Redirect
// etc.
} else {
// This will forward other errors since
// this interceptor code is invoked on every http request
return next.handle(req);
}
}),
);
}
来源:https://stackoverflow.com/questions/64897407/logout-user-and-redirect-user-to-login-on-token-expiration-angular-8