Logout User and Redirect User to Login on Token Expiration - Angular 8

我只是一个虾纸丫 提交于 2020-12-15 05:21:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!