简体   繁体   中英

How to auto logout of application when jwt access token expires using angular?

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?

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.

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

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