In front-end projects, tokens are usually used for user authentication and permission management. Whether based on JWT (JSON Web Token) or other types of tokens, they tend to have an expiration time. When the token expires, the user's operations are affected, so we need a non-aware (or "silent") way to refresh the token to ensure that the user's operations in the session are not interrupted.
This article will introduce how to implement invisible refresh of tokens in Vue projects, including the principles of token refresh, the application of interceptors, and how to deal with token expiration.
1. Token refresh background
Generally, there are two types of tokens:
- Access Token: Used to verify user identity every time you request, usually with a short validity period.
- Refresh Token: Used to refresh the access token. When the access token expires, you can use the refresh token to obtain a new access token.
In practical applications, the validity period of the access token is relatively short, mainly for security. When the access token expires, we do not want to force the user to log in again, but instead obtain a new access token by refreshing the token, thereby achieving a senseless refresh.
2. Insensitivity token refresh implementation principle
Invisible refresh refers to automatically refreshing and re-initiating a request when the token expires when it is not perceived by the user. This process usually consists of the following steps:
- Check the validity of the access token every time a request is initiated.
- If the access token expires, pause the current request and use the refresh token to obtain the new access token.
- Re-initiate a previously suspended request with a new access token.
- Update the token information in the app.
3. Implement token-free refresh in Vue project
In Vue projects, we usually use Axios to handle HTTP requests. In order to achieve senseless refresh, we can use Axios' interceptor to intercept requests and responses, detect whether the token expires, and automatically refresh if needed.
1. Configure the Axios interceptor
First, we need to set up Axios' request and response interceptor:
import axios from 'axios'; import store from '@/store'; // Suppose we save the token in Vuex import router from '@/router';const apiClient = ({ baseURL: .VUE_APP_API_BASE_URL, timeout: 10000 }); // Request an interceptor, carry token( config => { const accessToken = ['auth/accessToken']; if (accessToken) { ['Authorization'] = `Bearer ${accessToken}`; } return config; }, error => { return (error); } ); // Response to the interceptor to check whether the token expires ( response => { return response; }, async error => { const originalRequest = ; const refreshToken = ['auth/refreshToken']; // Check whether it is an authentication error (such as 401)if ( === 401 && !originalRequest._retry && refreshToken) { originalRequest._retry = true; // Try to get a new access token using refresh tokentry { const response = await ('/auth/refresh', { token: refreshToken }); const newAccessToken = ; // Update the token in the storage ('auth/SET_ACCESS_TOKEN', newAccessToken);// Re-initiate a previously failed request['Authorization'] = `Bearer ${newAccessToken}`; return apiClient(originalRequest); } catch (refreshError) { // Refresh failed, jump to the login page('auth/LOGOUT'); ('/login'); } } return (error); } ); export default apiClient;
2. Key points analysis
Request Interceptor: Before each request is sent, check
accessToken
Whether it exists and add it to the request headerAuthorization
In the field, make sure that the backend can recognize the user's identity.Response Interceptor: If the response status code is
401
, indicating that the access token is invalid or expired. At this time, you will try to userefreshToken
Request a new oneaccessToken
. After success, updatestore
InaccessToken
and re-initiate the previously failed request.
3. Vuex Management Token
To better manage tokens, we can use Vuex to store and update token information.
// store/modules/ const state = { accessToken: ('accessToken') || '', refreshToken: ('refreshToken') || '' }; const getters = { accessToken: state => , refreshToken: state => }; const mutations = { SET_ACCESS_TOKEN(state, token) { = token; ('accessToken', token); }, SET_REFRESH_TOKEN(state, token) { = token; ('refreshToken', token); }, LOGOUT(state) { = ''; = ''; ('accessToken'); ('refreshToken'); } }; export default { state, getters, mutations };
In Vuex, we uselocalStorage
Come to persistaccessToken
andrefreshToken
, so that the token will not be lost even if the user refreshes the page.
4. Automatic refresh and user experience
Token Insensitivity Refresh greatly improves the user experience, because users do not need to log in again when the Token expires. But the following points need to be paid attention to:
- Security: The validity period of the refresh token should be longer than the access token and can only be used once to prevent abuse.
- Timely refresh: You can set a timer on the front end to automatically refresh before the token expires, rather than waiting until the request 401 error is not refreshed.
- User Operation: When the refresh token is also expired, the user needs to be guided to log in again.
5. Summary
Implementing invisible token refresh in Vue projects can ensure that users will not be forced to log out or interrupt operations when the token expires. Through the combination of Axios interceptor and Vuex, we can implement automated token management and refresh processes. This not only improves security, but also provides users with a smoother user experience.
This is the end of this article about the example of implementing the Responsible Token Refresh in the Vue project. For more related Responsible Token Refresh content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!