先後端分離之JWT(JSON Web Token)的使用

前言

因爲本身開發的項目中用到了 JWT 技術,前端採用了 Vue.js 框架,後端採用了 CodeIgniter 框架,故做此文幫助使用相同技術棧的朋友們。javascript

具體思路以下:
把後端生成的 JWT token 存入 localStorage,而後前端切換路由(刷新頁面)的時候,經過 Ajax 請求的時候帶上這個 token,提交給後端判斷當前的 token 是否有效,後端返回結果。php

JWT 用處不少,能夠用於後臺權限的限制、接口安全性校驗。html

使用教程

前端 Vue.js

vue-router

登陸時,將後端返回的 token 存入 localStorage前端

使用 Vue-Router 判斷是否存在 token,不存在跳轉至登陸vue

// JWT 用戶權限校驗,判斷 TOKEN 是否在 localStorage 當中
router.beforeEach(({name}, from, next) => {
  // 獲取 JWT Token
  if (localStorage.getItem('JWT_TOKEN')) {
    // 若是用戶在login頁面
    if (name === 'login') {
      next('/');
    } else {
      next();
    }
  } else {
    if (name === 'login') {
      next();
    } else {
      next({name: 'login'});
    }
  }
});

axios

axios 全局配置攔截器
每次向後端請求攜帶 頭信息java

src/main.js 當中加上如下代碼:ios

// http request 攔截器
axios.interceptors.request.use(
  config => {
    if (localStorage.JWT_TOKEN) {  // 判斷是否存在token,若是存在的話,則每一個http header都加上token
      config.headers.Authorization = `token ${localStorage.JWT_TOKEN}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 攔截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      console.log('axios:' + error.response.status);
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息並跳轉到登陸頁面
          store.commit('LOG_OUT');
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          });
      }
    }
    return Promise.reject(error.response.data);   // 返回接口返回的錯誤信息
  });

Vue.prototype.$http = axios;

後端 CodeIgniter

後端 Controller 接收請求頭信息,驗證 token 有效性,無效返回 401 狀態碼git

$header = $this->input->get_request_header('Authorization', TRUE); // 獲取請求頭 Authorization
    list($token) = sscanf($header, 'token %s'); // 提取 token
    if ($header != '' && jwt_helper::validate($token)) {
        $userid = jwt_helper::decode($header)->userId; // 解碼token 提取 userId 字段
        // do something
    } else {
        show_error("Permission denied", 401, "Please check your token."); // 401錯誤
    }
這裏提供了本身使用的封裝好的 JWT Helper 類 和 JWT 的庫 使用方法和文件能夠訪問 Github
倉庫: https://github.com/52admln/JW...

安全性

可參考文章:http://www.cnblogs.com/xiekel... 當中的基於JWT的Token認證的安全問題github

相關文章
相關標籤/搜索