ThinkPHP5 使用 JWT 進行加密


使用 Github 的 firebase\JWT

- 使用 Composer 安裝此擴展

- 代碼示例

<?php

/**

 * [InterCommon-接口公用]

 * @Author   RainCyan

 * @DateTime 2019-08-12T16:38:08+0800

 */

namespace app\hladmin\controller;

use think\Controller;

use \Firebase\JWT\JWT;

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(\Firebase\JWT\SignatureInvalidException $e) {  //簽名不正確

            return json_msg(-101, $e->getMessage());

        }catch(\Firebase\JWT\BeforeValidException $e) {  // 簽名在某個時間點之后才能用

            return json_msg(-102, $e->getMessage());

        }catch(\Firebase\JWT\ExpiredException $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));

    }

}

?>

 

鏈接:https://pan.baidu.com/s/1v5gm7n0L7TGyejCmQrMh2g 提取碼:x2p5

免費分享,但是X度限制嚴重,如若鏈接失效點擊鏈接或搜索加群 群號518475424

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM