基于vue的token认证机制(完整版)

这两天边学习vue边写了一个基于vue的token认证机制,以前是用的Angular js,现在改成vue,感觉写起来更容易理解,编码也更方便了。不多说,以下为截图加代码:(注意要自己去安装axios、vuex),我用的element-UI做的排版,这个可以根据实际需求自己去选择,也可以使用Bootstrap或者layyer-ui什么的。

五步即可完成,注意黑体字为主要内容!

1.目录结构

基于vue的token认证机制(完整版)_第1张图片

2. login.vue登录界面代码:




3.router/index.js代码(路由)

import Vue from 'vue'
import Router from 'vue-router'
import login from '@/components/login'
import logout from '@/components/logout'
import Face from '@/components/content/face';
import Speak from '@/components/content/speak';
import Video from '@/components/content/video';
import register from '@/components/register';
import Home from '@/components/home';
Vue.use(Router)

export default new Router({
  routes: [
    //登录
    {
      path: '/',
      name: 'login',
      component: login
    },
    //注册
    {
      path:'/register',
      name: register,
      component: register
    },
   //主界面
    {
      path: '/home',
      name: 'home',
      meta: {
        requireAuth: true,  // 添加该字段,表示进入这个路由是需要登录的
      },
      component: Home,
      children:[
        {
          path:'/face',
          name:'face',
          component:Face
        },
        {
          path:'/speak',
          name:'speak',
          component:Speak
        },
        {
          path:'/video',
          name:'video',
          component:Video
        }
      ]
    },
    //退出
    {
      path: '/logout',
      name: 'logout',
      component: logout
    }

  ],

});

4.store/index.js(将从后端请求过来的token存储到本地)

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

export default new Vuex.Store({

  state: {
    // 存储token
    Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : ''
  },
/* actions: {
   changeLogin(ctx,Authorization){
     ctx.commit('changeLogin',Authorization);
   }
 },*/
  mutations: {
    // 修改token,并将token存入localStorage
    changeLogin (state,user) {
     state.Authorization = user.Authorization;
     console.log("store/index.js---到这里了!");
      localStorage.setItem('Authorization', user.Authorization);
    }
  }
});


5.mian.js(判断异步请求是否需要加入token到header里)

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en'
import VideoPlayer from 'vue-video-player'
import axios from 'axios'
import store from './store'
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
Vue.config.productionTip = false
Vue.config.debug = true
Vue.use(ElementUI, {locale})
Vue.use(VideoPlayer)
Vue.prototype.$axios = axios

new Vue({
  el: '#app',
  router,
  store,
  components: {App},
  render: h => h(App),
  template: ''
})
//异步请求前在header里加入token
axios.interceptors.request.use(
  config => {
    if(config.url==='/jwt/login'||config.url==='/jwt'){  //如果是登录和注册操作,则不需要携带header里面的token
    }else{
      if (localStorage.getItem('Authorization')) {
        config.headers.Authorizatior = localStorage.getItem('Authorization');
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });
//异步请求后,判断token是否过期
axios.interceptors.response.use(
  response =>{
    return response;
  },
  error => {
    if(error.response){
      switch (error.response.status) {
        case 401:
          localStorage.removeItem('Authorization');
          this.$router.push('/');
      }
    }
  }
)
//异步请求前判断请求的连接是否需要token
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    next();
  } else {
    let token = localStorage.getItem('Authorization');
    console.log("我是浏览器本地缓存的token: "+token);
    if (token === 'null' || token === '') {
      next('/');
    } else {
      next();
    }
  }
});

最后附上截图:

基于vue的token认证机制(完整版)_第2张图片

基于vue的token认证机制(完整版)_第3张图片

基于vue的token认证机制(完整版)_第4张图片

你可能感兴趣的:(Vue)