SoFunction
Updated on 2025-03-08

Token renewal mechanism in SpringBoot+Vue

In this example, we will use Spring Boot as the backend framework and Vue as the frontend framework to demonstrate how to achieve renewal of long and short tokens in full-stack applications.

1. Spring Boot backend

1.1 Generation of long tokens

In Spring Boot, we first create a service to generate a JWT Token. usejjwtLibrary, make sure toAdd the following dependencies to the file:

<dependency>
    <groupId></groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

Then, createJwtTokenServiceServe:

import ;
import ;
import ;
import ;

@Service
public class JwtTokenService {

    private String secretKey = "your_secret_key";

    public String generateLongToken(String username) {
        long expiration = 7 * 24 * 60 * 60 * 1000; // 7 days
        return ()
                .setSubject(username)
                .setExpiration(new Date(() + expiration))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    // ...Other methods ...}

1.2 Generation of short tokens

Add a method to generate a short token:

public String generateShortToken(String username) {
    long expiration = 15 * 60 * 1000; // 15 minutes
    return ()
            .setSubject(username)
            .setExpiration(new Date(() + expiration))
            .signWith(SignatureAlgorithm.HS256, secretKey)
            .compact();
}

1.3 Token renewal

Create a method for renewing a token:

public String renewToken(String oldToken) {
    // parse old token to get username    String username = ()
            .setSigningKey(secretKey)
            .parseClaimsJws(oldToken)
            .getBody()
            .getSubject();

    // Generate new short tokens    return generateShortToken(username);
}

2. Vue front end

In the Vue app, make sure to attach the token every time you request and update the token if needed.

2.1 Handling Token Expiration

In Vue applications, you can use an interceptor to check whether the token has expired, and if it expires, it will trigger the renewal process:

// Or other entry filesimport Vue from 'vue';
import axios from 'axios';

// Set up the axios interceptor(
  config =&gt; {
    // What to do before sending a request    const token = ('token');
    if (token) {
      // If a token exists, add it to the request header       = `Bearer ${token}`;
    }
    return config;
  },
  error =&gt; {
    // What to do about the request error    return (error);
  }
);

(
  response =&gt; {
    // What to do with the response data    return response;
  },
  error =&gt; {
    // What to do with response errors    const originalRequest = ;
    
    if ( === 401 &amp;&amp; !originalRequest._retry) {
      // If the response status is 401 (unauthorized) and has not been retryed      originalRequest._retry = true;
      
      // Send renewal request      return ('/api/renew-token')
        .then(response =&gt; {
          // Update locally stored tokens          updateLocalStorageToken();
          
          // Resend the original request          return axios(originalRequest);
        });
    }
    
    return (error);
  }
);

// Add axios to Vue's prototype so that it can be used directly in the component.$http = axios;

Through this interceptor, we can check whether the token expires every time we request it, and if it expires, the renewal process will be triggered. This implements the Token renewal mechanism in Vue front-end applications.

This is the article about the Token renewal mechanism in SpringBoot+Vue. For more related SpringBoot Vue Token renewal content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!