在前后端完全分离的情况下,Vue项目中实现token验证大致思路如下:
1、用户输入账号密码,前端调后端的登陆接口,发送用户名和密码,
2、后端收到请求,验证用户名和密码,验证通过后(即登录成功),后端返回token给前端;
3、前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面;
4、前端每次跳转路由,都要判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面( 通过router.beforeEach((to, from, next)=>{.....}))
5、每次调后端接口,都要在请求头中加上token;
6、后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回编码401(编码由前台和后台约定好),请求头中没有token也返回编码401;
7、如果前端拿到状态码为401,则清除token信息并跳转到登录页面,并弹框提示用户当前缺少token或者token已失效,请重新登录;
一、调登录接口成功,在回调函数中将token存储到localStorage和vuex中
login.vue
<template>
<div>
<input type="text" v-model="ruleForm.userName" placeholder="用户名"/>
<input type="text" v-model="ruleForm.password" placeholder="密码"/>
<button @click="login">登录</button>
</div>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
name: '',
data() {
return {
ruleForm: {
userName: '',
password: '',
},
};
},
methods:{
// 登录
login() {
if (!this.ruleForm.userName) {
this.ShowToast('账号不能为空');
return;
}
if (!this.ruleForm.password) {
this.ShowToast('密码不能为空');
return;
}
this.showLoading();
getUserLogin({
username: this.ruleForm.userName,
password:this.ruleForm.password
}).then((res) => {
this.HideLoading();
this.$store.commit('set_Authorization', res.data.token);// token
// 跳转登录
this.$router.push({
name: 'home'
});
}).catch((err) => {
this.HideLoading();
this.ShowToast('账号或密码错误,登录失败');
console.log(err);
});
},
}
}
</script>
store文件夹下的index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '', // 存储token
},
mutations: {
// 修改token,并将token存入localStorage
set_Authorization(state, data) {
state.Authorization = data; // 在这里data就是token,从登录页传过来的
localStorage.setItem('Authorization', data);
},
},
actions: {}
});
二、路由导航守卫
main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
document.addEventListener('deviceready', () => {
const vm = new Vue({
router,
store,
render: h => h(App),
}).$mount('#app');
router.beforeEach((to, from, next) => {
if (to.path === '/') {
next();
} else {
const token = localStorage.getItem('Authorization'); // 获取token
// token不存在
if (token === null || token === '') {
next('/');
vm.ShowToast('认证信息丢失,请重新登录');
} else {
next();
}
}
});
}, false);
三、请求头加token,如果前端拿到状态码为401,就清除token信息并跳转到登录页面
import Axios from 'axios';
Axios.defaults.baseURL = 'http://67.10.90.150:8092/'; // 基础url
Axios.defaults.timeout = 60000; // 请求超时
Axios.defaults.withCredentials = true; // 允许跨域携带cookie信息
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 添加请求拦截器
Axios.interceptors.request.use(
(config) => {
if (localStorage.getItem('Authorization')) {
config.headers.Authentication = localStorage.getItem(
'Authorization'
);
}
return config;
},
error => Promise.reject(error)
);
// 添加响应拦截器一
Axios.interceptors.response.use(({ data }) => data,
(error) => {
if (error.response.status === 401 && error.response.data) {
this.ShowToast('登录过期' || error.message);
this.$router.push({ name: '/login' });
localStorage.removeItem('Authorization');
}
return Promise.reject(error);
});
});
// 添加响应拦截器二
Axios.interceptors.response.use(({ data }) => data,
(error) => {
if(error && error.response){
switch(error.response.status){
case 400:
error.message = '请求错误';
break;
case 401:
error.message = '未授权,请登录';
localStorage.removeItem('Authorization');
this.$router.push({ name: '/login' });
break;
case 403:
error.message = '拒绝访问';
break;
case 404:
error.message = '`请求地址出错:${error.response.config.url}`';
break;
case 408:
error.message = '请求超时';
break;
case 500:
error.message = '服务器内部错误';
break;
case 501:
error.message = '服务未实现';
break;
case 502:
error.message = '网关错误';
break;
case 503:
error.message = '服务不可用';
break;
case 504:
error.message = '网关超时';
break;
case 505:
error.message = 'HTTP版本不受支持';
break;
case ECONNABORTED:
error.message = '请求超时';
break;
default:
break;
}
}else {
error.message = '数据请求超时';
}
this.ShowToast(error.message);
return Promise.reject(error);
});
});