Vue中實現token驗證

先後端流程分析

  1. 前端頁面進行登陸操做,將用戶名和密碼發給服務器
  2. 服務器進行校驗,經過後生成token,包含信息有密匙、uid、過時時間等,而後返回給前端
  3. 前端將token保存在本地(建議在localStorage中)和state(vuex)中,下次對服務器請求時帶上,而後返回給前端
  4. 服務器端對接收到的token進行校驗。經過則進行相應的增刪改查操做,並將數據返回給前端;未經過則返回錯誤碼,提示錯誤信息,而後跳轉到登陸頁

具體實現

技術棧:vuex + axios + localStorage + vue-router前端

  • 登陸路由添加自定義meta字段,來記錄該頁面是否須要身份驗證
// router.js
{
    path: "/index",
    name: "index",
    component: resolve => require(['./index.vue'], resolve),
    meta: { 
        requiresAuth: true 
    }
}
  • 設置路由攔截
router.beforeEach((to, from, next) => {
    //  matched的數組中包含$route對象的檢查元字段
    //  arr.some() 表示判斷該數組是否有元素符合相應的條件, 返回布爾值
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // 判斷當前是否有登陸的權限
        if (!auth.loggedIn()) {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        } else {
            next()
        }
    } else {
        next() // 確保必定要調用 next()
    }
})
  • 設置請求/響應攔截
    在後面的全部請求中都將攜帶token進行。
    利用axios中的請求攔截器, 經過配置http response inteceptor, 當後端接口返回401 (未受權), 讓用戶從新執行登陸操做。
// http request 攔截器
axios.interceptors.request.use(
    config => {
        if (store.state.token) {  // 判斷是否存在token,若是存在的話,則每一個http header都加上token
            config.headers.Authorization = `token ${store.state.token}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 攔截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息並跳轉到登陸頁面
                    store.commit(types.LOGOUT);
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的錯誤信息
});
  • 登陸頁面:
//login.vue
methods: {
  login(){
      if (this.token) {
          // 存儲在本地的localStograge中,可使用cookies/local/sessionStograge
          this.$store.commit(types.LOGIN, this.token)
          // 跳轉至其餘頁面
          let redirect = decodeURIComponent(this.$route.query.redirect || '/');
          this.$router.push({
              path: redirect
          })
      }
  }
}
  • vuex設置
import Vuex from 'vuex';
import Vue from 'vue';
import * as types from './types'

Vue.use(Vuex);
export default new Vuex.Store({
    state: {
        user: {},
        token: null,
        title: ''
    },
    mutations: {
        // 登陸成功將, token保存在localStorage中
        [types.LOGIN]: (state, data) => {
            localStorage.token = data;
            state.token = data;
        },
        // 退出登陸將, token清空
        [types.LOGOUT]: (state) => {
            localStorage.removeItem('token');
            state.token = null
        }
    }
});

三者區別:vue

  • sessionStorage 不能跨頁面共享的,關閉窗口即被清除
  • localStorage 能夠同域共享,而且是持久化存儲的
  • 在 local / session storage 的 tokens,就不能從不一樣的域名中讀取,甚至是子域名也不行. 解決辦法使用Cookie.demo: 假設當用戶經過 app.yourdomain.com 上面的驗證時你生成一個 token 而且做爲一個 cookie 保存到 .yourdomain.com,而後,在 youromdain.com 中你能夠檢查這個 cookie 是否是已經存在了,而且若是存在的話就轉到 app.youromdain.com去。這個 token 將會對程序的子域名以及以後一般的流程都有效(直到這個 token 超過有效期) 只是利用cookie的特性進行存儲而非驗證.
相關文章
相關標籤/搜索