ThinkPHP5框架中使用JWT的方法示例
huangyuxin_ 人气:1本文实例讲述了ThinkPHP5框架中使用JWT的方法。分享给大家供大家参考,具体如下:
JWT下载地址:https://jwt.io
可以直接去github上下载,也可以使用composer
使用composer的话要确保你的电脑上安装了composer,进入项目根目录下载即了,自动会放在vendor目录下
创建文件
我是放在common目录下
使用教程
github都有的
贴源码
JWTAuth.php
<?php namespace app\common\Auth; use \Lcobucci\JWT\Builder; use \Lcobucci\JWT\Signer\Hmac\Sha256; use \Lcobucci\JWT\Parser; use \Lcobucci\JWT\ValidationData; /** * 单例模式 */ class JWTAuth { private static $instance; /** * JWT TOKEN * @var [type] */ private $token; /** * 颁发 * @var string */ private $iss = 'api.test.com'; /** * 接收 * @var string */ private $aud = 'app.com'; private $uid; private $secrect="#$%#$%*&^(*(*("; private $decodeToken; public static function getInstance() { if(is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } private function __contruct(){ } private function __clone(){ } public function encode(){ $time = time(); $this->token = (new builder())->setHeader('alg','HS256') ->setIssuer($this->iss) ->setAudience($this->aud) ->setIssuedAt($time) //生效时间 ->setExpiration($time + 20)//过期时间 ->set('uid',$this->uid) ->sign(new Sha256(), $this->secrect)//加密算法 ->getToken(); return $this; } public function getToken(){ return (string)$this->token; } public function setToken($token){ $this->token = $token; return $this; } /** * 用户信息uid * @param [type] $uid [description] */ public function setUid($uid){ $this->uid = $uid; return $this; } public function jsonDecode(){ $token = $this->token; $this->decodeToken = (new Parser())->parse((string) $token); // echo $this->decodeToken->getClaim('uid'); return $this->decodeToken; } /** * 验证令牌是否有效 * @return [type] [description] */ public function validate(){ $data = new ValidationData(); $data->setIssuer($this->iss); $data->setAudience($this->aud); return $this->jsonDecode()->validate($data); } /** * 签名来验证令牌在生成后是否未被修改 * @return [type] [description] */ public function verify(){ $result = $this->jsonDecode()->verify(new Sha256(), $this->secrect); return $result; } }
user.php 用来测试
<?php namespace app\index\controller; use app\common\Auth\JWTAuth; class User{ public function login(){ $jwtAuth = JWTAuth::getInstance(); $token = $jwtAuth->setUid(1)->encode()->getToken(); echo $token; // var_dump(success_json_data(['token'=>$token])); } public function check_login(){ $jwtAuth = JWTAuth::getInstance(); $jwtAuth->setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGkudGVzdC5jb20iLCJhdWQiOiJhcHAuY29tIiwiaWF0IjoxNTU2MDk1MDI5LCJleHAiOjE1NTYwOTUwNDksInVpZCI6MX0.oi4rLbQFNZUJsW4fVHWiOQxfEmomuvldAV-gFKl2V74'); if($jwtAuth->validate() && $jwtAuth->verify()){ echo '验证成功'; }else{ echo '登录过期'; } } }
最后
jwt本身的话是不带token刷新方法,所以一旦token过期,客户端就要重新登录。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。
加载全部内容