How to handle JWT token expiration and auto-refresh in a Spring Boot + Angular application?

Discussão em 'Angular' iniciado por Diman, Julho 9, 2025.

  1. Diman

    Diman Guest

    I'm building a full-stack web application using Spring Boot (backend) and Angular (frontend) with JWT-based authentication.

    Everything works fine for login and accessing protected routes. However, I'm struggling to implement a proper solution for handling expired JWT tokens and refreshing them automatically without forcing the user to log in again.

    What I’ve tried: I implemented a refresh token endpoint in Spring Boot.

    I'm storing the access token and refresh token in localStorage.

    I attempted to intercept 401 responses in Angular using an HttpInterceptor and call the refresh token API, but it's inconsistent and sometimes triggers multiple refresh calls in parallel.

    What I want to achieve: Automatically detect when the access token is expired.

    Use the refresh token to get a new access token only once, even if multiple requests are fired during expiration.

    Retry the original request after refreshing the token.

    Tools/Versions: Spring Boot 3.x

    Angular 16+

    JWT with HS256

    Using HttpInterceptor in Angular

    My Question: What is the best practice for handling JWT expiration and refresh tokens in a Spring Boot + Angular application, especially avoiding race conditions or multiple simultaneous refresh calls?

    What I Tried: Created a /refresh-token endpoint in my Spring Boot backend that accepts the refresh token and returns a new access token.

    In Angular, I used an HttpInterceptor to catch 401 Unauthorized errors.

    When a 401 is detected, I:

    Send a request to the refresh endpoint using the stored refresh token.

    If successful, update the access token in localStorage.

    Retry the original failed request.

    Continue reading...

Compartilhe esta Página