简体   繁体   English

注销用户并重定向用户以在令牌到期时登录 - Angular 8

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

I receive idToken and I am also getting the expiration time expTime in timestamp format eg: 1605803717 which basically expires in 1 day.我收到idToken并且我还得到时间戳格式的过期时间expTime例如: 1605803717基本上在 1 天内过期。 I want to log the user out and redirect the user to login page if idToken expires.如果idToken过期,我想注销用户并将用户重定向到登录页面。 I have implemented a HTTPInterceptor as below:我已经实现了一个 HTTPInterceptor 如下:

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?我的问题是要知道这个实现是否会自动工作,我的意思是,当idToken过期时,这个拦截器会自动触发还是我需要设置某种触发器? How does HTTPInterceptors work? HTTP拦截器是如何工作的? Will it be able to catch time expiration and logout user or I have to implement something else to catch idToken expiration?它是否能够捕获时间到期并注销用户,或者我必须实现其他功能来捕获idToken到期?

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我实现它的一种方法是使用代码 401 捕获未经授权的错误。在我们的例子中处理错误是使用 refreshToken 更新令牌,但是如果你愿意,你可以注销和重定向


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);
        }
      }),
    );
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM