ThinkPHP5 使用 JWT 進行加密

ThinkPHP5 使用 JWT 進行加密

使用 githubfirebasejwt

– 使用 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"=&gt;$e-&gt;getCode(),?"msg"=&gt;$e-&gt;getMessage())); ????????} ????} ????//簽發token ????private?function?_setJwtToken($string=""){ ????????$key?=?$this-&gt;key; ????????$time?=?time(); ????????$token?=?array( ????????????"iss"?=&gt;?"http://ml.cn", ????????????"aud"?=&gt;?"http://ml.cn", ????????????'iat'?=&gt;?$time,?//簽發時間 ????????????'nbf'?=&gt;?$time?+?10,?//在什么時間之后該jwt才可用 ????????????'exp'?=&gt;?$time?+?10,?//過期時間 ????????????"string"?=&gt;?$string ????????); ????????$jwt?=?JWT::encode($token,?$key); ????????return?$jwt; ????} ????//解析token ????protected?function?_readJwtToken($jwt){ ????????$key?=?$this-&gt;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-&gt;getMessage()); ????????}catch(FirebaseJWTBeforeValidException?$e)?{??//?簽名在某個時間點之后才能用 ????????????return?json_msg(-102,?$e-&gt;getMessage()); ????????}catch(FirebaseJWTExpiredException?$e)?{??//?token過期 ????????????return?json_msg(-103,?$e-&gt;getMessage()); ????????}catch(Exception?$e)?{??//其他錯誤 ????????????return?json_msg(-104,?$e-&gt;getMessage()); ????????} ????} ????//測試解析 ????public?function?_writeJwtToken($token){ ????????halt($this-&gt;_readJwtToken($token)); ????} } ?&gt;

本文來自thinkphp框架技術文章欄目:firebasejwt

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享