由於自己開發的項目中用到了 JWT 技術,前端采用了 Vue.js
框架,后端采用了 CodeIgniter
框架,故作此文幫助使用相同技術棧的朋友們。
具體思路如下:
把后端生成的 JWT token 存入 localStorage,然后前端切換路由(刷新頁面)的時候,通過 Ajax 請求的時候帶上這個 token,提交給后端判斷當前的 token 是否有效,后端返回結果。
JWT 用處很多,可以用於后台權限的限制、接口安全性校驗。
https://segmentfault.com/a/1190000010444825
https://blog.sakuradon.com/index.php/archives/349/
https://jwt-auth.readthedocs.io/en/develop/quick-start/
https://medium.com/employbl/build-authentication-into-your-laravel-api-with-json-web-tokens-jwt-cd223ace8d1a
https://jwt.io/introduction/
http://www.luohun.org/index.php/archives/27//www/wn-kiki-admin-server/app/User.php
/**
* 關閉 遞增
*/
public $incrementing = false;
/**
* 關閉 創建時間 與 更新時間的自動維護
*/
public $timestamps = false;
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
路由:
Route::group(['namespace' => 'Home','middleware' => ['api','response']],function (){
//商品列表+詳情
Route::resource('/goodslist','GoodsController');
//商品分類
Route::resource('/class','ClassController');
//需要登陸才能查看的接口
Route::group(['middleware' => ['jwt.auth']],function (){
//購物車
Route::resource('/cart','CartController');
});
});
0x03 創建token
需要引入的:
use App\user;
use JWTAuth;
//查詢一條數據,並輸出token
$user = User::first();
$token = JWTAuth::fromUser($user);
0x04 獲取token
public function index(Response $response)
{
//獲取用戶信息
$user = JWTAuth::toUser(Input::get('token'));
//獲取購物車信息
$cart = self::$cartService->getCart($user->id);
//判斷是否有值
if (empty($cart) || ($cart->count() <= 0)){
return $response->setStatusCode(404);
}
return $cart;
}
http://www.sunfengxiang.com/1097.html
Json Web Token(JWT)簡介
https://learnku.com/articles/10885/full-use-of-jwt