Handling Expired Token From Api in Angular 4

后端 未结 2 439
迷失自我
迷失自我 2021-02-02 16:38

I need help in handling expired token in my angular application. My api has the expired time but my problem is when i forgot to log out of my angular application, after some tim

2条回答
  •  -上瘾入骨i
    2021-02-02 16:58

    I think there is two solution you can play with.

    The first one you can just call you logout function when browser getting closed like:

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

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

    OR

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

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

    This way alway when browser getting closed your this.auth.logout(); will be called automatically.

    Second you can install library like 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)
      );
    }
    

提交回复
热议问题