使用 github 的 firebasejwt
– 使用 composer 安裝此擴展
– 代碼示例
<?php /** * [InterCommon-接口公用] * @Author RainCyan * @DateTime 2019-08-12T16:38:08+0800 */ namespace apphladmincontroller; use thinkController; use FirebaseJWTJWT; class InterCommonController extends Controller { private $key = "123456789"; //客戶端獲取TOKEN public function _getJwtToken(){ try { $string = input("string"); if (empty($string)) { throw new Exception("請傳入需要加密string", -105); } $jwt = $this->_setJwtToken($string); ????????????throw?new?Exception($jwt,?200); ????????}?catch?(Exception?$e)?{ ????????????return?json(array("code"=>$e->getCode(),?"msg"=>$e->getMessage())); ????????} ????} ????//簽發token ????private?function?_setJwtToken($string=""){ ????????$key?=?$this->key; ????????$time?=?time(); ????????$token?=?array( ????????????"iss"?=>?"http://ml.cn", ????????????"aud"?=>?"http://ml.cn", ????????????'iat'?=>?$time,?//簽發時間 ????????????'nbf'?=>?$time?+?10,?//在什么時間之后該jwt才可用 ????????????'exp'?=>?$time?+?10,?//過期時間 ????????????"string"?=>?$string ????????); ????????$jwt?=?JWT::encode($token,?$key); ????????return?$jwt; ????} ????//解析token ????protected?function?_readJwtToken($jwt){ ????????$key?=?$this->key; ????????try?{ ????????????JWT::$leeway?=?60;//當前時間減去60,把時間留點余地 ????????????$decoded?=?JWT::decode($jwt,?$key,?['HS256']);?//HS256方式,這里要和簽發的時候對應 ????????????$arr?=?(array)$decoded; ????????????return?json_msg(200,?"success",?$arr); ????????}?catch(FirebaseJWTSignatureInvalidException?$e)?{??//簽名不正確 ????????????return?json_msg(-101,?$e->getMessage()); ????????}catch(FirebaseJWTBeforeValidException?$e)?{??//?簽名在某個時間點之后才能用 ????????????return?json_msg(-102,?$e->getMessage()); ????????}catch(FirebaseJWTExpiredException?$e)?{??//?token過期 ????????????return?json_msg(-103,?$e->getMessage()); ????????}catch(Exception?$e)?{??//其他錯誤 ????????????return?json_msg(-104,?$e->getMessage()); ????????} ????} ????//測試解析 ????public?function?_writeJwtToken($token){ ????????halt($this->_readJwtToken($token)); ????} } ?>
本文來自thinkphp框架技術文章欄目:firebasejwt
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END