1,composer 安装 jwt, composer require lcobucci/jwt : 3.3.0
2,JWT 类的简单封装
---------------------------------------------------------------------------------------------------------------------------
namespace Home\Controller; use Lcobucci\JWT\Parser; use Lcobucci\JWT\ValidationData; class JwtController { private $issue = "http://example.com"; private $audience = "http://example.com"; private $identified = "#$%^&*%$#1"; private $key = "&*(%$#^*&%777788"; // 后端定义 private $uid = null; private $token = null; private static $instance = null; private $decodeToken = null; private function __construct() { } private function __clone() { // TODO: Implement __clone() method. } public static function getInstance() { if (empty(self::$instance)) { self::$instance = new self(); } return self::$instance; } public function setUid($uid) { $this->uid = $uid; return $this; } public function getUid() { return $this->uid; } public function getToken() { return (string)$this->token; } public function setToken($token) { $this->token = $token; return $this; } /** * 生成token(是个对象) * @return $this */ public function encode() { $time = time(); $sign = new \Lcobucci\JWT\Signer\Hmac\Sha256(); $this->token = (new \Lcobucci\JWT\Builder()) ->setHeader("alg", "HS256") ->issuedBy($this->issue) ->setAudience($this->audience) ->identifiedBy($this->identified) ->issuedAt($time) ->canOnlyBeUsedAfter($time + 60)// 多少秒之后才能使用这个token(可省略) ->expiresAt($time + 3600)// 过期时间 ->with("uid", $this->uid) ->sign($sign, $this->key) ->getToken(); return $this; } /** * 解析token * @return \Lcobucci\JWT\Token|null */ public function decode() { if (!$this->decodeToken) { $this->decodeToken = (new Parser())->parse($this->token); // 返回个对象 $this->uid = $this->decodeToken->getClaim("uid"); //print 1 用户ID } return $this->decodeToken; } /** * 验证token是否被篡改 * @return bool */ public function verify() { $sign = new \Lcobucci\JWT\Signer\Hmac\Sha256(); $result = $this->decode()->verify($sign, $this->key); return $result; } /** * 校验数据 * @return bool */ public function validate() { $time = time(); $data = new ValidationData(); $data->setAudience($this->audience); $data->setIssuer($this->issue); $data->setCurrentTime($time + 61); // 因为之前设置了60秒前不能使用 return $this->decode()->validate($data); } }
----------------------------------------------------------------------------------------------------------------------
3,服务端简单调用及校验
namespace Home\Controller; use Think\Controller; class LoginController extends Controller { public function index() { $uid = 1; // 用户ID $token = JwtController::getInstance()->setUid($uid)->encode()->getToken(); var_dump($token); // 生成token ,返回给客户端 } public function check() { $token = I("token"); // 客户端传过来的token $result = JwtController::getInstance()->setToken($token); $res1 = $result->verify(); $res2 = $result->validate(); if ($res1 && $res2) { // 校验通过 $uid = $result->getUid(); // 得到用户的UID } } }