简体   繁体   中英

How to redirect to logout when token expired in angular?

I have a angular 13 application. There I use JWT token for authentication purposes. Everything works fine. but the token expiration time I have given to the JWT token is 1 hour. I want to log the user out from the front end application once the token expired on the server-side.

I did this but it seems there is a problem and it didn't work for me:

export class authInterceptor implements HttpInterceptor {

  constructor(private userService: UserService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.userService.isAuthentificated()) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.userService.getToken()}`
        }
      });
    }
    return next.handle(request).pipe(
      tap(event => {
      }, error => {
        this.onSubscribeError(error);
      })
    );
  }

  private onSubscribeError(error: any): void {
    if (error.status === 401 || error.status === 403) {
      this.userService.logout();
    }
  }
}

can anyone tell me what I did wrong and help me correct it?

The link provided by E. Maggini is fine, technically, but the accepted answer for it, at least, is only relevant for letting the server decide if it's expired or not.

If you're not making calls to the server and getting your 401, your UI stays logged in until you do.

You need a mix of the two; one added to your interceptor to check for your 401 and log you out (to be sure) and the app itself checking the token.

Simplest is to just have an interval on the go checking for your token's expiry.

Assuming you have some kind of singleton AuthService with basic login/logout handling...

@Injectable()
export class AuthService {
    private jwt: string;
    private expiryTimer: any;

    public login(jwt: string): void {
        this.jwt = jwt;
        this.expiryTimer = setInterval(() => { this.checkExpiry(); }, 60000);
        this.router.navigate(['...']);
    }

    public logout(): void {
        this.jwt = undefined;
        if (this.expiryTimer) clearInterval(this.expiryTimer);
        this.router.navigate(['...']);
    }

    private checkExpiry(): void {
        if (this.jwtService.hasExpired(this.jwt)) this.logout();
    }
}

Assuming you have some jwt service or method or whatnot to check the expiry...

It'll look more complicated than that as, presumably, you'd actually be storing the token somewhere (local storage?) so that page refreshes are handled, etc. etc.

But the basics are there - don't overthink it, it's as simple as just checking the token every x (1m good enough?) and if it's expired, logout...

Your modified interceptor will use the same thing; get a 401? this.authService.logout(); . Done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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