• 技术文章 >php框架 >ThinkPHP

    ThinkPHP5 使用 JWT 进行加密

    藏色散人藏色散人2019-08-19 14:18:06转载3215

    使用 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));
        }
    }
    ?>

    本文来自ThinkPHP框架技术文章栏目://m.sbmmt.com/phpkj/thinkphp/

    以上就是ThinkPHP5 使用 JWT 进行加密的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:learnku,如有侵犯,请联系admin@php.cn删除
    专题推荐:ThinkPHP5
    上一篇:thinkphp i方法 下一篇:tp5.0 的模型类型转换问题
    大前端线上培训班

    相关文章推荐

    • thinkphp5是什么• thinkphp5和3.2的区别• thinkphp5源码怎么安装• thinkphp5和3的区别

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网