首頁技術(shù)文章正文

基于vue 實現(xiàn)token驗證的實例代碼

更新時間:2018-09-18 來源:黑馬程序員技術(shù)社區(qū) 瀏覽量:

這篇文章主要介紹了基于vue 實現(xiàn)token驗證的實例代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下

基于vue的 做了token驗證

前端部分(對axios設(shè)置Authorization)代碼如下:


import axios from 'axios'
import store from '../store'
import router from '../router'
//設(shè)置全局axios默認值
axios.defaults.timeout = 6000; //6000的超時驗證
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
//創(chuàng)建一個axios實例
const instance = axios.create();
instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.interceptors.request.use = instance.interceptors.request.use;
//request攔截器
instance.interceptors.request.use(
  config => {
    //每次發(fā)送請求之前檢測都vuex存有token,那么都要放在請求頭發(fā)送給服務(wù)器
    if(store.state.token){
      config.headers.Authorization = `token ${store.state.token}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
//respone攔截器
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => { //默認除了2XX之外的都是錯誤的,就會走這里
    if(error.response){
      switch(error.response.status){
        case 401:
          store.dispatch('UserLogout'); //可能是token過期,清除它
          router.replace({ //跳轉(zhuǎn)到登錄頁面
            path: 'login',
            query: { redirect: router.currentRoute.fullPath } // 將跳轉(zhuǎn)的路由path作為參數(shù),登錄成功后跳轉(zhuǎn)到該路由
          });
      }
    }
    return Promise.reject(error.response);
  }
);
export default instance;


然后在路由文件中


//注冊全局鉤子用來攔截導(dǎo)航
router.beforeEach((to, from, next) => {
//獲取store里面的token
let token = store.state.token;
//判斷要去的路由有沒有requiresAuth
if(to.meta.requiresAuth){
  if(token){
   next();
  }else{
   next({
    path: '/login',
    query: { redirect: to.fullPath } // 將剛剛要去的路由path(卻無權(quán)限)作為參數(shù),方便登錄成功后直接跳轉(zhuǎn)到該路由
   });
  }
}else{
  next();//如果無需token,那么隨它去吧
}
});

后端(node) 我們封裝了一個中間件 在需要驗證token的路由,加上這個中間件

router.get('/dosh',checkToken,User.dosh)
const jwt = require('jsonwebtoken');

1、使用jsonwebtoken 創(chuàng)建tokenconst jwt = require('jsonwebtoken');
//登錄時:核對用戶名和密碼成功后,應(yīng)用將用戶的id(圖中的user_id)作為JWT Payload的一個屬性
module.exports = function(user_id){
  const token = jwt.sign({
    user_id: user_id
  }, 'sinner77', {
    expiresIn: '3600s' //過期時間設(shè)置為60妙。那么decode這個token的時候得到的過期時間為 : 創(chuàng)建token的時間 + 設(shè)置的值
  });
  return token;
};
2、對于前端的請求,校驗接口
//檢查token是否過期
module.exports = async ( ctx, next ) => {
  if(ctx.request.header['authorization']){
    let token = ctx.request.header['authorization'].split(' ')[1];
    //解碼token
    let decoded = jwt.decode(token, 'sinner77');
    //console.log(decoded);的輸出 :{ user_id: '123123123', iat: 1494405235, exp: 1494405235 }
    if(token && decoded.exp <= new Date()/1000){
      ctx.status = 401;
      ctx.body = {
        message: 'token過期'
      };
    }else{
      //如果權(quán)限沒問題,那么交個下一個控制器處理
      return next();
    }
  }else{
    ctx.status = 401;
    ctx.body = {
      message: '沒有token'
    }
  }
};

總結(jié)

以上所述就是給大家介紹的基于vue 實現(xiàn)token驗證的實例代碼,希望對大家有所幫助


本文版權(quán)歸黑馬程序員JavaEE學(xué)院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明作者出處。謝謝!

作者:黑馬程序員前端與移動開發(fā)培訓(xùn)學(xué)院
首發(fā):http://web.itheima.com/?v2 

分享到:
在線咨詢 我要報名
和我們在線交談!