Vue2.0-token權限處理

token一種身份的驗證,在大多數網站中,登陸的時候都會攜帶token,去訪問其餘頁面,token就想當於一種令牌。能夠判斷用戶是否登陸狀態。本次頁面是經過Element-ui搭建的登陸界面javascript

當用戶登陸的時候,向後端發起請求的時候,後端會返回給我一個token,前端能夠進行校驗,進行處理token前端

當前端拿到後端返回的token,能夠經過localStorage存儲到本地,而後經過jwt-decode對token進行解析,jwt-decode是一種對token的解析包,經過npm install jwt-decodevue

設置好存儲方式後,當用戶再次登陸的時候,在瀏覽器段能夠看點用戶存儲的token。java

當頁面不少地方須要用到token的時候,用戶必須攜帶token才能訪問其餘頁面,能夠經過請求攔截和響應攔截設置,而且在響應攔截的時候處理token是否過期,過時時間是經過後端設置的,前端須要判斷token的狀態碼是否過期就行ios

import axios from 'axios'
import { Loading ,Message} from 'element-ui'  //引入了element-ui框架庫
import router from './router/index.js'
let loading;

function startLoading() {
	loading =Loading.service({
		lock: true,
        text: '加載中...',
        background: 'rgba(0, 0, 0, 0.7)'
	});
}

function endLoading() {
	loading.close()
}

// 請求攔截

axios.interceptors.request.use(config => {

    startLoading()
    //設置請求頭
    if(localStorage.eleToken) {
    	config.headers.Authorization = localStorage.eleToken
    }

    return config
  }, error => {
    return Promise.reject(error)
  })


// 響應攔截
axios.interceptors.response.use(response => {
    endLoading()
    return response
}, error => {
	Message.error(error.response.data)
	endLoading();

	//獲取狀態碼
	const {status} = error.response;

	if(status === 401) {
		Message.error("token失效,請從新登陸");
		//清除token
		localStorage.removeItem('eleToken');
		//從新登陸
		router.push('/login')
	}

    return Promise.reject(error)
})

export default axios;

存儲vuexvuex

若是頁面過多,不想數據來回傳遞,這時候就能夠用到vuex來存儲數據了,這樣每一個頁面均可以經過store獲取用戶信息了。當用戶拿到token令牌的時候,會獲得用戶的信息,npm

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const type = {
	SET_AUTHORIZATION:"set_authorization",
	SET_USER:"set_user"
}

const state = {
	isAuthorization:false,
	user:{}
}

const getters = {  //獲取state狀態
 isAuthorization: state => state.isAuthorization,
 user: user => state.user
}

const mutations= {
	[type.SET_AUTHORIZATION](state,isAuthorization){
		if(isAuthorization){
			state.isAuthorization = isAuthorization
		} else {
			isAuthorization = false
		}
	},
	
	[type.SET_USER](state,user) {
		if(user) {
			state.user = user
		} else {
			user={}
		}
	}
}
const actions = {
	setAuthorization:({commit},isAuthorization) => {
		commit(type.SET_AUTHORIZATION,isAuthorization)
	},
	setsuer:({commit},user) => {
		commit(type.SET_USER,user)
	}
}

export const store = new Vuex.Store({
	state,
	getters,
	mutations,
	actions
})

  經過以上vuex設置,咱們能夠吧獲得的token和用戶的一些信息存儲到vuex中,方便其餘頁面進行調用element-ui

submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/api/users/login',this.loginUser).then(res => {
            
            const {token} = res.data;
            //存儲token
            localStorage.setItem('eleToken',token)
            //解析token
            const decode = jwt_decode(token)
            console.log(res)
             // 存儲到vuex
            this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
            this.$store.dispatch("setsuer",decode)

            // this.$router.push('/index')
          })
        }
      })
    },
//封裝的驗證方法 isEmpty(value) { return ( value === undefined || value === null || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0) ); }

 雖然token和用戶信息存儲到vuex中了,當咱們刷新瀏覽器的時候,存儲的vuex數據都沒有了,axios

  

這時候。咱們須要在跟組件app.vue組件進行判斷,token是否存在本地,存在就存放到vuex中後端

export default {
  name: 'App',
  created(){
    if(localStorage.setItem) {
      const decode = jwt_decode(localStorage.eleToken)

      // 存儲到vuex
      this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
      this.$store.dispatch("setsuer",decode)
    }
  },
  methods:{
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === "object" && Object.keys(value).length === 0) ||
        (typeof value === "string" && value.trim().length === 0)
      );
    }
  }
}

 路由守衛

路由跳轉前作一些驗證,好比登陸驗證,購物車,是網站中的廣泛需求,在用戶沒有登陸的狀態下,是沒法訪問其餘頁面的,這是時候咱們就能夠經過beforeEach來判斷用戶是否登陸,(原理不須要細講,官方文檔有,直接上代碼),仍是直接經過token去驗證是否登陸或者沒有登陸狀態

router.beforeEach((to,from,next) => {
  const isLogin = localStorage.eleToken ? true : false
  if(to.path === '/login' || to.path === 'register') {
    next()
  } else {
    isLogin ? next() : next('/login')
  }
})

  

 以上都是此次博客中全部的內容,若是喜歡,能夠關注一下!!!

相關文章
相關標籤/搜索