Business Scenario Description
Suppose the user is filling out a complex form, and it takes a long time for the user to finish it due to the large amount of content on the form. At this point, if the Token has expired, the system will ask the user to log in again, which is obviously a very bad experience. To avoid this, we need to automatically refresh the Token when it is about to expire or has already expired, without affecting the operation the user is performing.
Technical realization ideas
I. Preparatory work
- Front-end framework selection: In this article, for example, combined with Vue Router and Axios to realize the Token senseless refresh mechanism.
- Back-end support: The backend needs to provide an interface to refresh the Token, returning a new Token when the old one is received.
II. Key technical points
- Interception of requests: Use the Axios interceptor to detect the state of each request and trigger the logic to refresh the Token if it is found to be expired.
- Refresh Token: Implement a method dedicated to refreshing a Token that is automatically called and updates the Token when the old one expires.
- request queue: Suspend other requests that require a Token during the Token refresh period, and resend those requests when the Token is successfully refreshed.
III. Specific realization steps
1. Configure the Axios interceptor
First, an Axios interceptor is configured to detect the state of requests and responses and trigger logic to refresh the Token when it expires.
import axios from 'axios'; import store from './store'; // Assuming Vuex is used to manage global state import router from './router'; let isRefreshing = false; let requests = []; ( config => { const token = ; if (token) { ['Authorization'] = 'Bearer ' + token; } return config; }, error => { return (error); } ); ( response => { return response; }, error => { const { config, response } = error; const originalRequest = config; if (response && === 401) { if (!isRefreshing) { isRefreshing = true; return refreshToken().then(newToken => { ('setToken', newToken); ['Authorization'] = 'Bearer ' + newToken; processQueue(null, newToken); return axios(originalRequest); }).catch(err => { processQueue(err, null); ('logout'); router.push('/login'); return (err); }).finally(() => { isRefreshing = false; }); } else { return new Promise((resolve, reject) => { requests.push((token) => { ['Authorization'] = 'Bearer ' + token; resolve(axios(originalRequest)); }); }); } } return (error); } ); function processQueue(error, token = null) { (promise => { if (error) { (error); } else { (token); } }); requests = []; }
2. Implementation of the method for refreshing the Token
Next, implement a method for refreshing the TokenrefreshToken
. This method calls the backend interface to get the new Token.
function refreshToken() { return new Promise((resolve, reject) => { ('/auth/refresh', { refreshToken: }).then(response => { if () { resolve(); } else { reject(); } }).catch(error => { reject(error); }); }); }
3. Update Vuex state management
Ensure that there is relevant state and methods in the Vuex to manage Token and user login state.
const store = new ({ state: { token: ('token') || '', refreshToken: ('refreshToken') || '', user: {} }, mutations: { setToken(state, token) { = token; ('token', token); }, setRefreshToken(state, refreshToken) { = refreshToken; ('refreshToken', refreshToken); }, logout(state) { = ''; = ''; = {}; ('token'); ('refreshToken'); } } });
4. Handling of login logic
Ensure that Token is stored and refreshed correctly when a user logs in.
function login(credentials) { return ('/auth/login', credentials).then(response => { ('setToken', ); ('setRefreshToken', ); }); }
In summary: When users are filling out complex forms, even if the Token expires, it will not interrupt their operation, thus providing a better user experience. This mechanism is not only applicable to form filling, but can also be widely used in any web application scenario that requires long interaction time.