2

I am using jwt tokens to authenticate users in my angular(client) and spring boot (server) application. I want user to logout automatically out of application when token expires. I have used concept of interceptors to check if token expires and show user a pop up saying "your session has expired" and log out of application like below:

export class TokenInterceptor implements HttpInterceptor {

constructor(private token: TokenStorageService, private router: Router) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    {
        if (this.isTokenExpired()) {
            console.log("token is expired.");
            this.showSessionExpiredPopUp();
        }
        else {
            console.log("token is not expired.");
        }
        return next.handle(req);
    }
}

isTokenExpired() {
        const helper = new JwtHelperService();
        if (helper.isTokenExpired(this.token.getToken())) {
            return true;
        }
        return false;
    }

showSessionExpiredPopUp() {
        Swal.fire({
            html: 'Your session expired!',
        }).then((result) => {
            this.token.signout();
            window.location.href = '';
        });
    }

This is working okay leaving one problem which is related to popup.I am getting this session expired pop up when doing login request too as interceptor intercept while sending login request to server. Is there a way to not show this popup when doing login? And what is the best way to handle this auto logout scenario in angular?

Aaron
  • 99
  • 1
  • 13
  • If your issue is that the popup is showing, I usually do something like this, where I tell certain urls that the interceptor should ignore: https://stackoverflow.com/a/55522787/7741865 Other answers are viable there too. So just the same idea, don't check the token status if you are logging in. – AT82 Jun 04 '21 at 17:46

2 Answers2

1

You can update the interceptor and token expired method as follows, here we are removing the token once it is expired and adding a null check while validating:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.isTokenExpired()) {
        console.log("token is expired.");
        // here remove the auth token
        this.showSessionExpiredPopUp();
    } else {
        console.log("token is not expired.");
    }
    return next.handle(req);
}

isTokenExpired() {
    const helper = new JwtHelperService();
    return this.token.getToken() && helper.isTokenExpired(this.token.getToken());
}
deepakchethan
  • 5,240
  • 1
  • 23
  • 33
0

When you detect that token has expired, remove it completly. Then you will be able to distinguish scenario when token is expired and no token is present at all.

Alternatively, you can just skip the chech for your login endoint in the interceptor so it will check for expiration on every request except login request.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99