前后端分離實現(xiàn)JWT Token登錄驗證和狀態(tài)保持,Vue代碼

參考自文章

springboot+vue實現(xiàn)token驗證

Springboot+Vue前后端分離實現(xiàn)token登錄驗證和狀態(tài)保存

阮一峰——JSON Web Token 入門教程


1. 后端Springboot

2. 前端Vue

目錄結(jié)構(gòu)

image

2.1 登錄頁的login方法:獲取token并存儲在localStorage中(view/login.vue)

login() { 

    // 從用戶輸入中獲取name和password,從user.js中引入封裝的Login方法

      Login(this.users.name,this.users.password).then(res => {

          console.log(res)

          // 請求失敗

          if(!res.data){

            alert("用戶名或密碼錯誤");

            return

          }

          const token = res.data.token;

          const user = res.data.user;

          /*存儲到ls*/

          localStorage.setItem('eleToken',token);

          /*解析token中的信息*/

          const decoded = jwt(token);

          /*存儲至vuex*/

          this.$store.dispatch("setLogin",!this.isEmpty(decoded))  //decoded空,函數(shù)返回真,取反假

          this.$store.dispatch("setUser",user)

          /*跳轉(zhuǎn)*/

          this.$router.push('/home');

        })

        .catch(err => {

          console.log(err)

        });

    },

    isEmpty(value){

      return(

          value ===undefined || value ===null ||

          (typeof  value === "object" && Object.keys(value).length ===0) ||

          (typeof value ==="string" && value.trim().length ===0)

      );

    },

2.2 路由守衛(wèi)判斷是否存在token,存在時正常訪問,不存在時要求登錄(router/index.js)

/*路由守衛(wèi)   根據(jù)登錄獲得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")   /*真跳轉(zhuǎn)  假登錄*/

  }

})

2.3 axios請求攔截和響應(yīng)攔截(network/request.js)

import axios from 'axios'

import { Loading } from 'element-ui';   /*elementUI的loading*/

import { Message } from 'element-ui';   /*elementUI消息提醒*/

import router from '../router/index';

let loading;

function startLoading () {

  loading = Loading.service({    /*在需要調(diào)用時:*/

    lock: true,

    text: '拼命加載中...',

    background: 'rgba(0,0,0,0,7)'

  });

}

function endLoading () {

  loading.close();

}

export function request(config){

  const instance = axios.create({

    baseURL:'http://localhost:8888/day07/',

    timeout:5000

  })

  //請求攔截

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

    //加載動畫

    //startLoading();

    /*判斷token存在   登錄攔截*/

    if(localStorage.eleToken){

      /*設(shè)置統(tǒng)一的header*/

      config.headers.Authorization  = localStorage.eleToken;

    }

    return config;

  },error => {

    return Promise.reject(error);

  });

  //響應(yīng)攔截

  axios.interceptors.response.use(Response => {

      //結(jié)束加載動畫

      //endLoading();

      return Response;

    },error => {

    //錯誤提醒

    //endLoading();

    Message.error(error.response.data);

    /*獲取錯誤狀態(tài)碼*/

    const  { status } =error.response;

    if(status == 401){

      Message.error("token失效,重新登錄");

      /*清楚token*/

      localStorage.removeItem('eleToken');

      /*跳轉(zhuǎn)登錄*/

      router.push('/login')

    }

    return Promise.reject(error);

  })

  // 發(fā)送真正網(wǎng)絡(luò)請求并返回

  return instance(config)

}

2.4 頁面刷新時重新判斷token是否存在或過期,并將需要數(shù)據(jù)保存到vuex中(App.vue)

<script>

import jwt from 'jwt-decode';

import {findOneUserById} from './network/user'

export default {

  name:'App',

  created(){   /*在根組件進行判斷,否則刷新就沒了*/

    this.initData()

  },

  methods: {

    // 有token時初始化數(shù)據(jù)

    initData(){

      if (localStorage.eleToken){

        const decoded = jwt(localStorage.eleToken);

        let _this = this;

        // 需完善,其它組件初始化獲取vuex中的user數(shù)據(jù)時,若請求未完成user為undefined

        findOneUserById(decoded.aud).then(res => {

          console.log(res)

          // token已過期

          if(res.data.code == 401){

            /*存儲至vuex*/

            localStorage.removeItem('eleToken')

            _this.$store.dispatch("setLogin",false)

          }else{

            _this.$store.dispatch("setUser",res.data)

            /*存儲至vuex*/

            _this.$store.dispatch("setLogin",!this.isEmpty(decoded))

          }

        }).catch(err=>{

          console.log(err)

        })

      }

    },

    isEmpty(value){

        return(

            value ===undefined || value ===null ||

            (typeof  value === "object" && Object.keys(value).length ===0) ||

            (typeof value ==="string" && value.trim().length ===0)

        );

    }

  }

}

</script>

2.5 vuex中保存登錄狀態(tài)和登錄用戶信息(store/index.js)

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const types ={

  SET_LOGIN: 'SET_LOGIN',

  SET_USER: 'SET_USER',

};

export default new Vuex.Store({

  state: {

    isLogin:false,

    user:{}

  },

  mutations: {

    [types.SET_LOGIN](state,isLogin){      /*設(shè)置是否授權(quán)*/

      if(isLogin) state.isLogin = isLogin;

      else state.isLogin = false;

    },

    /*類型,參數(shù)*/

    [types.SET_USER](state,user){

      if (user) state.user = user;

      else state.user = {};

    },

  },

  actions: {

    setLogin:( {commit},isLogin) =>{

      commit(types.SET_LOGIN,isLogin);

    },

    setUser:({commit},user) =>{

      commit(types.SET_USER,user);

    }

  },

  modules: {

  }

})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容