🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# JWT插件 composer 安装 ~~~ composer require firebase/php-jwt ~~~ # 用法 ~~~ use \Firebase\JWT\JWT; $key = "example_key"; $token = array( //"iss" => "http://example.org", // "aud" => "http://example.com", "iat" => 1356999524,//可以是time()时间戳 "nbf" => 1357000000//可以是time()时间戳 ); $jwt = JWT::encode($token, $key); $decoded = JWT::decode($jwt, $key, array('HS256')); print_r($decoded); $decoded_array = (array) $decoded; JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); ~~~ ## 补充捕获异常 ~~~ try { $arr = $jwt::decode($token, $key, array('HS256')); } catch (\Exception $e) { // token验证失败 return json(['code' => 0, 'msg' => $e->getMessage()],400)->send(); }catch (ExpiredException $e){ // 过期 return json(['code' => 0, 'msg' => $e->getMessage()],400)->send(); } ~~~ ## 实例 ~~~ class Base extends Common { public function index(Request $request){ $data['username'] = $request->param('username'); //验证数据 //查询数据库 $info = SystemUser::where('id','=','1')->find(); //比对密码 //返回token $key = 'asdfhjkl'; $payload=[ 'iat'=>time(), 'nbf'=>time(), 'userinfo'=>[ 'uid'=>$info['id'], 'name'=>$info['username'], ] ]; $jwt = JWT::encode($payload,$key); $decoded = JWT::decode($jwt, $key, array('HS256')); return json(['code'=>'1','token'=>$decoded,'msg'=>'成功'])->send(); } } ~~~