基于vue 實(shí)現(xiàn)token驗(yàn)證的實(shí)例代碼
vue-koa2-token
基于vue的 做了token驗(yàn)證
前端部分(對axios設(shè)置Authorization)
import axios from 'axios' import store from '../store' import router from '../router' //設(shè)置全局axios默認(rèn)值 axios.defaults.timeout = 6000; //6000的超時驗(yàn)證 axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'; //創(chuàng)建一個axios實(shí)例 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 => { //默認(rèn)除了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) 我們封裝了一個中間件 在需要驗(yàn)證token的路由,加上這個中間件
router.get('/dosh',checkToken,User.dosh) const jwt = require('jsonwebtoken');
1、使用jsonwebtoken 創(chuàng)建token
const 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、對于前端的請求,校驗(yàn)接口
//檢查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' } } };
代碼托管github 歡迎star
https://github.com/yxl720/vue-koa2-token
總結(jié)
以上所述是小編給大家介紹的基于vue 實(shí)現(xiàn)token驗(yàn)證的實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
解決vue+element 鍵盤回車事件導(dǎo)致頁面刷新的問題
今天小編就為大家分享一篇解決vue+element 鍵盤回車事件導(dǎo)致頁面刷新的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08HTML頁面中使用Vue示例進(jìn)階(快速學(xué)會上手Vue)
Vue是用于構(gòu)建用戶界面的漸進(jìn)式JavaScript框架。特色:構(gòu)建用戶界面—數(shù)據(jù)變成界面;漸進(jìn)式—Vue可以自底向上逐層的應(yīng)用。VUE有兩種使用方式,一種實(shí)在html中直接使用vue做開發(fā),一種是企業(yè)級的單頁面應(yīng)用。2023-02-02ElementUI中<el-form>標(biāo)簽中ref、:model、:rules的作用淺析
Element官方文檔中寫到,model是表單數(shù)據(jù)對象,rules是表單驗(yàn)證規(guī)則,下面這篇文章主要給大家介紹了關(guān)于ElementUI中<el-form>標(biāo)簽中ref、:model、:rules作用的相關(guān)資料,需要的朋友可以參考下2023-01-01vue實(shí)現(xiàn)表單數(shù)據(jù)的增刪改功能
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)表單數(shù)據(jù)的增刪改功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03vue2 拖動排序 vuedraggable組件的實(shí)現(xiàn)
這篇文章主要介紹了vue2 拖動排序 vuedraggable組件的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08