处理 Angular 中 Api 的过期令牌 4

Handling Expired Token From Api in Angular 4

我需要帮助处理我的 angular 应用程序中的过期令牌。我的 api 已过期但我的问题是当我忘记注销我的 angular 应用程序时,一段时间后,我仍然可以访问主页但没有数据。有什么我可以做的吗?有图书馆可以处理这个吗?或者有什么我可以安装的吗?更好,如果我什么都不会安装。下面是我的验证码?我可以添加任何可以处理过期的东西吗?如果过期我将无法访问主页。

auth.service.ts

 export class AuthService {
  private loggedIn = false;

  constructor(private httpClient: HttpClient) {
  }

  signinUser(email: string, password: string) {  
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json');

    return this.httpClient
    .post(
      'http://sample.com/login', 
       JSON.stringify({ email, password }), 
       { headers: headers }
    )
    .map(
        (response: any) => {
          localStorage.setItem('auth_token', response.token);
          this.loggedIn = true;
          return response;
        });
   }

    isLoggedIn() {
      if (localStorage.getItem('auth_token')) {
        return this.loggedIn = true;
      }
    }

   logout() {
     localStorage.removeItem('auth_token');
     this.loggedIn = false;
    }
}

authguard.ts

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this.authService.isLoggedIn()) {
      // logged in so return true
      return true;
    }

    else {
      // not logged in so redirect to login page with the return url
      this.router.navigate(['signin'])
      return false;
      }
  }
}

我认为您可以尝试两种解决方案。

第一个你可以在浏览器关闭时调用你注销功能,例如:

  @HostListener('window:unload', ['$event'])
  handleUnload(event) {
    this.auth.logout();
  }

https://developer.mozilla.org/de/docs/Web/Events/unload

 @HostListener('window:beforeunload', ['$event'])
      public handleBeforeUnload(event) {
        this.auth.logout();
      }

https://developer.mozilla.org/de/docs/Web/Events/beforeunload

这种方式总是在浏览器关闭时自动调用您的this.auth.logout();

其次你可以像angular2-jwt it can help you to detect if token has expired

一样安装库
jwtHelper: JwtHelper = new JwtHelper();

useJwtHelper() {
  var token = localStorage.getItem('token');

  console.log(
    this.jwtHelper.decodeToken(token),
    this.jwtHelper.getTokenExpirationDate(token),
    this.jwtHelper.isTokenExpired(token)
  );
}

您可以使用 http 拦截器来做到这一点。

intercept(req: HttpRequest<any>, next: HttpHandler) {
  if(!localStorage.getItem('token'))
    return next.handle(req);

  // set headers
  req = req.clone({
    setHeaders: {
      'token': localStorage.getItem('token')
    }
  })

  return next.handle(req).do((event: HttpEvent<any>) => {
    if(event instanceof HttpResponse){
      // if the token is valid
    }
  }, (err: any) => {
    // if the token has expired.
    if(err instanceof HttpErrorResponse){
      if(err.status === 401){
        // this is where you can do anything like navigating
        this.router.navigateByUrl('/login');
      }
    }
  });
}

Here's the full solution