vue項目中使用token的身份驗證的簡單實踐

工做原理

  1. 前端頁面進行登陸操做, 將用戶名與密碼發給服務器;
  2. 服務器進行效驗, 經過後生成token, 包含信息有密鑰, uid, 過時時間, 一些隨機算法等 ,而後返回給前端
  3. 前端將token保存在本地中, 建議使用localstorage進行保存. 下次對服務器發送請求時, 帶上本地存儲的token
  4. 服務器端,進行對token的驗證, 經過的話, 進行相應的增刪改查操做, 並將數據返回給前端
  5. 爲經過則返回錯誤碼, 提示保錯信息, 而後跳轉到登陸頁.

具體步驟

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

  1. 在登陸路由添加自定義mate字段, 來記錄該頁面是否須要身份驗證
//router.js
{
    path: "/index",
    name: "index",
    component: resolve => require(['./index.vue'], resolve),
    meta: { 
        requiresAuth: true 
    }
} 
複製代碼
  1. 設置路由攔截
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()
    }
})
複製代碼
  1. 設置攔截器
    這裏使用axios的攔截器,對全部請求進行攔截判斷。
    在後面的全部請求中都將攜帶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)   // 返回接口返回的錯誤信息
});
複製代碼
  1. 將token存儲在本地中
    可使用cookies/local/sessionStograge

三者的區別: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的特性進行存儲而非驗證.

關於XSS和XSRF的防範:ios

  • XSS 攻擊的原理是,攻擊者插入一段可執行的 JavaScripts 腳本,該腳本會讀出用戶瀏覽器的 cookies 並將它傳輸給攻擊者,攻擊者獲得用戶的 Cookies 後,便可冒充用戶。
  • 防範 XSS ,在寫入 cookies 時,將 HttpOnly 設置爲 true,客戶端 JavaScripts 就沒法讀取該 cookies 的值,就能夠有效防範 XSS 攻擊。
  • CSRF是一種劫持受信任用戶向服務器發送非預期請求的攻擊方式。
  • 防範 CSRF: 由於 Tokens 也是儲存在本地的 session storage 或者是客戶端的 cookies 中,也是會受到 XSS 攻擊。因此在使用 tokens 的時候,必需要考慮過時機制,否則攻擊者就能夠永久持有受害用戶賬號。

相關文章: XSS 和 CSRF簡述及預防措施算法

//login.vue
    methods: {
        login(){
            if (this.token) {
                //存儲在本地的localStograge中
                this.$store.commit(types.LOGIN, this.token)
                //跳轉至其餘頁面
                let redirect = decodeURIComponent(this.$route.query.redirect || '/');
                this.$router.push({
                    path: redirect
                })
            }
        }
    }
複製代碼

在vuex中:vue-router

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
        }
    }
});
複製代碼

在./types.js中:vuex

export const LOGIN = 'login';
export const LOGOUT = 'logout';
複製代碼

就介紹到這裏了。。。 axios

相關文章
相關標籤/搜索