首先在我的laravel项目中Vendor文件夹下 引入 第三方jwt类包
以下贴一下 我的代码简单流程,
1):JWT加密
protected $key; public function __construct() { $this->key = env('MINI_SHOP_TOKEN'); }
public function encryption() { $time = time(); $exp_time = time()+1800;//正式30天 测试30分钟 $payload = array( "iss" => "http://www.baidu.com", "aud" => "http://www.baidu.com", "iat" => $time,//签发时间 "nbf" => $time,//生效时间,在此之前是无效的 "exp" => $exp_time,//有效期 "uid" => 56 ); $token = JWT::encode($payload,$this->key); // WxShopToken::toFirstOrCreate(['uid'=>56,'u_token'=>$token,'exp_time'=>$exp_time]); return $token; }
此可在登录的时候进行JWT加密,将用户信息 进行加密,返还给前端人员。后端也可根据此token解密 出对应用户信息
2)JWT解密
public function decryption($token) { $token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC93d3cudmUtbGluay5jb20iLCJhdWQiOiJodHRwOlwvXC93d3cudmUtbGluay5jb20iLCJpYXQiOjE2MDIyMjI1NTYsIm5iZiI6MTYwMjIyMjU1NiwiZXhwIjoxNjAyMjI0MzU2LCJ1aWQiOjU2fQ.4uuyCeIr-SwVjHCs-Ev5vU5vSoL0sJfJxU6a2YutJ7Q"; //此次是传一个测试token以供解密 $decoded = JWT::decode($token, $this->key, array('HS256')); $decoded = (array) $decoded; return isset($decoded['uid']) ? $decoded['uid'] : 0; }