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')
  }
})

  

 以上都是此次博客中全部的内容,若是喜欢,能够关注一下!!!

相关文章
相关标签/搜索