**在前后端完全分离的情况下,Vue项目中实现token验证大致思路如下:
1、第一次登录的时候,前端调后端的登陆接口,发送用户名和密码
2、后端收到请求,验证用户名和密码,验证成功,就给前端返回一个token
3、前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面
4、前端每次跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面
5、每次调后端接口,都要在请求头中加token
6、后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401
**
一、 调登录接口成功,在回调函数中将token存储到localStorage和vuex中
- login.vue
<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']),
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if(this.ruleForm.name && this.ruleForm.pass && this.ruleForm.phone){
//后端验证
this.$axios.post('http://10.70.50.6:3000/adminuser/main/findone',{
password : this.ruleForm.pass,
phone : this.ruleForm.phone
}).then(res => {
console.log(res.data);
if(res.data.code === 1){
//唯一标识
this.userToken = 'Bearer ' + this.ruleForm.phone;
// 将用户token保存到vuex中
this.changeLogin({
Authorization: this.userToken });
this.$router.push('/main');
this.$message({
message: '登录成功',
type: 'success'
});
}else if(res.data.code === 2){
this.$message({
message: '密码错误',
type: 'error'
});
}else if(res.data.code === 3){
this.$message({
message: '手机号错误,用户不存在',
type: 'error'
});
}else if(res.data.code === 4){
this.$message({
message: '登录异常',
type: 'error'
});
localStorage.removeItem('Authorization');
this.$router.push('/login');
}
// alert('请登录')
// localStorage.removeItem('Authorization');
// this.$router.push('/login');
}).catch(error => {
this.$message({
message: '提交表单出错',
type: 'error'
});
console.log(error);
});
}
})
},
}
};
</script>
- store文件夹下的index.js
export default new Vuex.Store({
state: {
//存储token
Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '',
uerName : '',
},
mutations: {
// 修改token,并将token存入localStorage
changeLogin (state, user) {
state.Authorization = user.Authorization;
console.log(state.Authorization);
localStorage.setItem('Authorization', user.Authorization);
}
},
actions: {
},
modules: {
}
})
二、路由导航守卫
router文件夹下的index.js
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 登录验证,导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
if (to.path === '/login') {
next();
} else {
let token = localStorage.getItem('Authorization');
console.log(token);
if(token === null || token === ''){
this.$message({
message: '请登录',
type: 'error'
});
next('/login');
console.log('非登录入口' + token);
}else{
// next('/login');
console.log('登录入口' + token);
next();
}
}
});
三、请求头加token
main.js文件
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Authorization')) {
config.headers.Authorization = localStorage.getItem('Authorization');
}
return config;
},
error => {
return Promise.reject(error);
});