在前后端完全分離的情況下,Vue項目中實現token驗證大致思路如下:
1、第一次登錄的時候,前端調后端的登陸接口,發送用戶名和密碼
2、后端收到請求,驗證用戶名和密碼,驗證成功,就給前端返回一個token
3、前端拿到token,將token存儲到localStorage和vuex中,並跳轉路由頁面
4、前端每次跳轉路由,就判斷 localStroage 中有無 token ,沒有就跳轉到登錄頁面,有則跳轉到對應路由頁面
5、每次調后端接口,都要在請求頭中加token
6、后端判斷請求頭中有無token,有token,就拿到token並驗證token,驗證成功就返回數據,驗證失敗(例如:token過期)就返回401,請求頭中沒有token也返回401
7、如果前端拿到狀態碼為401,就清除token信息並跳轉到登錄頁面
一、調登錄接口成功,在回調函數中將token存儲到localStorage和vuex中
<template>
<div>
<input type="text" v-model="loginForm.username" placeholder="用戶名"/>
<input type="text" v-model="loginForm.password" placeholder="密碼"/>
<button @click="login">登錄</button>
</div>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
data () {
return {
loginForm: {
username: '',
password: ''
}
};
},
methods: {
...mapMutations(['changeLogin']),
login () {
let _this = this;
if (this.loginForm.username === '' || this.loginForm.password === '') {
alert('賬號或密碼不能為空');
} 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;
// 將用戶token保存到vuex中
_this.changeLogin({ Authorization: _this.userToken });
_this.$router.push('/home');
alert('登陸成功');
}).catch(error => {
alert('賬號或密碼錯誤');
console.log(error);
});
}
}
}
};
</script>
store文件夾下的index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
// 存儲token
Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : ''
},
mutations: {
// 修改token,並將token存入localStorage
changeLogin (state, user) {
state.Authorization = user.Authorization;
localStorage.setItem('Authorization', user.Authorization);
}
}
});
export default store;
二、路由導航守衛
router文件夾下的index.js
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
}
]
});
// 導航守衛
// 使用 router.beforeEach 注冊一個全局前置守衛,判斷用戶是否登陸
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;
三、請求頭加token
// 添加請求攔截器,在請求頭中加token
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Authorization')) {
config.headers.Authorization = localStorage.getItem('Authorization');
}
return config;
},
error => {
return Promise.reject(error);
});
四、如果前端拿到狀態碼為401,就清除token信息並跳轉到登錄頁面
localStorage.removeItem('Authorization');
this.$router.push('/login')