In Vue 3, Navigation Guard is used to intercept changes in routing and can be checked before the user accesses the page. When combining Axios token authentication mechanism, we can check the user's authentication status when routing jumps through the navigation guard to ensure that the user has a valid token for authentication.
1. Install the necessary dependencies
First, make sure you have installedaxios
, this is the library we use to initiate HTTP requests.
npm install axios
2. Create an axios instance
We usually create a token authentication logic that encapsulatesaxios
Instance, easy to manage all requests.
// src/utils/ import axios from 'axios'; const instance = ({ baseURL: '', // Set basic API address timeout: 5000, // Set request timeout}); // Request an interceptor(config => { const token = ('token'); // Get token from localStorage if (token) { ['Authorization'] = `Bearer ${token}`; // Add token in the request header } return config; }, error => { return (error); }); // Response Interceptor(response => { return response; }, error => { if ( === 401) { // If the response returns 401, it means that it is not authorized and you can jump to the login page = '/login'; } return (error); }); export default instance;
3. Use navigation guards in
Next, inThe navigation guard configured for routing is checked to check the user authentication status before each route jump.
// src/router/ import { createRouter, createWebHistory } from 'vue-router'; import axios from '../utils/axios'; // Import axios instanceimport Home from '../views/'; import Login from '../views/'; const routes = [ { path: '/', name: 'Home', component: Home, meta: { requiresAuth: true }, // Pages that require authentication }, { path: '/login', name: 'Login', component: Login, }, ]; const router = createRouter({ history: createWebHistory(.BASE_URL), routes, }); // Global front guard(async (to, from, next) => { const token = ('token'); if () { if (!token) { // If the target route requires authentication and does not have token, jump to the login page return next({ name: 'Login' }); } try { // If there is a token, verify that the token is valid const response = await ('/verify-token'); // Assuming that the backend provides an interface to verify the token if ( === 200) { next(); // token is valid, allowing continued access } } catch (error) { // The token is invalid or the request fails, jump to the login page ('token'); // Clear invalid token next({ name: 'Login' }); } } else { next(); // Pages that do not require authentication can be accessed directly } }); export default router;
4. Handle login and logout logic
When the user logs in, we get the token and store it inlocalStorage
Center; when logging out, we need to clear the token.
// src/views/ <template> <div> <h1>Login</h1> <form @="handleLogin"> <input v-model="username" placeholder="Username" /> <input v-model="password" type="password" placeholder="Password" /> <button type="submit">Login</button> </form> </div> </template> <script> import axios from '../utils/axios'; export default { data() { return { username: '', password: '', }; }, methods: { async handleLogin() { try { const response = await ('/login', { username: , password: , }); const token = ; ('token', token); // Save token this.$('/'); // After logging in successfully, jump to the homepage } catch (error) { ('Login failed:', error); } }, }, }; </script>
// src/views/ <template> <div> <h1>Welcome Home</h1> <button @click="handleLogout">Logout</button> </div> </template> <script> export default { methods: { handleLogout() { ('token'); // Clear token this.$('/login'); // Jump to login page }, }, }; </script>
5. Use scenarios
This token authentication mechanism can be applied to any page that requires user login. For example, when a user accesses a page that requires authentication (such as the home page), the navigation guard will first trigger the navigation guard to verify whether the token is valid in the guard. If there is no valid token, the user will be redirected to the login page.
Scene summary:
-
front page (
/
): A token is required to verify the user's identity. Navigation Guard checks whether the token exists and is valid. -
Login page (
/login
): After the user enters the user name and password, sends a request to the backend, obtains and stores the token. - Global logout: When the user logs out, clear the token and jump to the login page.
6. Summary
Through the above steps, we have achieved:
- use
axios
Configuration and authentication of token request header. - Use Navigation Guard Intercept Authentication Logic in Vue 3 routing.
- Save the token when logging in and check whether the token is valid when the user visits the page that needs authentication.
This authentication mechanism can effectively ensure that users must pass the authentication when accessing sensitive pages, without directly skipping the authentication process.
This is the article about the navigation guards in Vue3 combined with Axios to implement the token authentication mechanism. For more related content of Vue3 token authentication mechanism, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!