1, When the front and back ends are completely separated, the idea of implementing token verification in Vue project is as follows:
- When logging in for the first time, the front end calls the login interface of the back end, and sends the user name and password
- The back end receives the request, verifies the user name and password, and returns a token to the front end if the verification is successful
- The front end gets the token, stores it in localStorage and vuex, and jumps to the routing page
- Each time the front-end skips the route, it will judge whether there is a token in the localload, if not, it will jump to the login page, if so, it will jump to the corresponding route page
- Every time the backend interface is called, token should be added to the request header
- The back end judges whether there is a token in the request header. If there is a token, it gets the token and verifies it. If the verification succeeds, it returns data. If the verification fails (for example, if the token expires), it returns 401. If there is no token in the request header, it returns 401
- If the front end gets the status code 401, it will clear the token information and jump to the login page
2, The sample file is as follows:
- The login interface is called successfully, and the token is stored in localStorage and vuex in the callback function
//File login.vue <template> <div> <input type="text" v-model="loginForm.username" placeholder="user name"/> <input type="text" v-model="loginForm.password" placeholder="Password"/> <button @click="login">Sign in</button> </div> </template> <script> import { mapMutations } from 'vuex'; export default { data () { return { loginForm: { username: '', password: '' }, userToken: '' }; }, methods: { ...mapMutations(['changeLogin']), login () { let _this = this; if (this.loginForm.username === '' || this.loginForm.password === '') { alert('Account or password cannot be empty'); } else { this.axios({ method: 'post', url: '/user/login', data: _this.loginForm }).then(res => { console.log(res.data); _this.userToken = 'Bearer ' + res.data.data.body.token; // Save user token to vuex _this.changeLogin({ Authorization: _this.userToken }); _this.$router.push('/home'); alert('Login succeeded'); }).catch(error => { alert('Wrong account or password'); console.log(error); }); } } } }; </script> //index.js under the store folder import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { // Store token Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '' }, mutations: { // Modify the token and store it in localStorage changeLogin (state, user) { state.Authorization = user.Authorization; localStorage.setItem('Authorization', user.Authorization); } } }); export default store;
- Route navigation guard
//index.js under router folder import Vue from 'vue'; import Router from 'vue-router'; import login from '@/components/login'; import home from '@/components/home'; Vue.use(Router); const router = new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: login }, { path: '/home', name: 'home', component: home } ] }); // Navigation guard // Use router.beforeEach to register a global front guard to determine whether the user logs in router.beforeEach((to, from, next) => { if (to.path === '/login') { next(); } else { let token = localStorage.getItem('Authorization'); if (token === null || token === '') { next('/login'); } else { next(); } } }); export default router;
- Request header with token
// Add request interceptor and token in request header axios.interceptors.request.use( config => { if (localStorage.getItem('Authorization')) { config.headers.Authorization = localStorage.getItem('Authorization'); } return config; }, error => { return Promise.reject(error); });
- If the front end gets the status code 401, it will clear the token information and jump to the login page
localStorage.removeItem('Authorization'); this.$router.push('/login');
Original link: https://blog.csdn.net/sleepwalker_1992/java/article/details/82974703