多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 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(); } } ~~~