JWTManager.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of qbhy/simple-jwt.
  5. *
  6. * @link https://github.com/qbhy/simple-jwt
  7. * @document https://github.com/qbhy/simple-jwt/blob/master/README.md
  8. * @contact qbhy0715@qq.com
  9. * @license https://github.com/qbhy/simple-jwt/blob/master/LICENSE
  10. */
  11. namespace Qbhy\SimpleJwt;
  12. use Doctrine\Common\Cache\Cache;
  13. use Doctrine\Common\Cache\FilesystemCache;
  14. use Qbhy\SimpleJwt\Encoders\Base64UrlSafeEncoder;
  15. use Qbhy\SimpleJwt\EncryptAdapters\PasswordHashEncrypter;
  16. use Qbhy\SimpleJwt\Exceptions\InvalidTokenException;
  17. use Qbhy\SimpleJwt\Exceptions\SignatureException;
  18. use Qbhy\SimpleJwt\Exceptions\TokenBlacklistException;
  19. use Qbhy\SimpleJwt\Exceptions\TokenExpiredException;
  20. use Qbhy\SimpleJwt\Exceptions\TokenNotActiveException;
  21. use Qbhy\SimpleJwt\Exceptions\TokenRefreshExpiredException;
  22. use Qbhy\SimpleJwt\Interfaces\Encoder;
  23. use Qbhy\SimpleJwt\Interfaces\Encrypter;
  24. class JWTManager
  25. {
  26. protected $ttl;
  27. /** @var int token 过期多久后可以被刷新,单位分钟 minutes */
  28. protected $refreshTtl;
  29. /** @var AbstractEncrypter */
  30. protected $encrypter;
  31. /** @var Encoder */
  32. protected $encoder;
  33. /** @var Cache */
  34. protected $cache;
  35. /**
  36. * @var array
  37. */
  38. protected $drivers;
  39. /**
  40. * @var string
  41. */
  42. protected $secret;
  43. /**
  44. * @var string
  45. */
  46. protected $prefix;
  47. /**
  48. * JWTManager constructor.
  49. */
  50. public function __construct(array $config)
  51. {
  52. $this->verifyConfig($config);
  53. $this->secret = $config['secret'];
  54. $this->drivers = $config['drivers'] ?? [];
  55. $this->prefix = $config['prefix'] ?? 'default';
  56. $this->resolveEncrypter($config['default'] ?? PasswordHashEncrypter::class);
  57. $this->encoder = $config['encoder'] ?? new Base64UrlSafeEncoder();
  58. $this->cache = $config['cache'] ?? new FilesystemCache(sys_get_temp_dir());
  59. $this->ttl = $config['ttl'] ?? 60 * 60;
  60. $this->refreshTtl = $config['refresh_ttl'] ?? 60 * 60 * 24 * 7; // 单位秒,默认一周内可以刷新
  61. }
  62. public function getTtl(): int
  63. {
  64. return $this->ttl;
  65. }
  66. public function getCache(): Cache
  67. {
  68. if ($this->cache instanceof Cache) {
  69. return $this->cache;
  70. }
  71. return $this->cache = is_callable($this->cache) ? call_user_func_array($this->cache, [$this]) : new FilesystemCache(sys_get_temp_dir());
  72. }
  73. /**
  74. * 单位:分钟
  75. * @return $this
  76. */
  77. public function setTtl(int $ttl): JWTManager
  78. {
  79. $this->ttl = $ttl;
  80. return $this;
  81. }
  82. public function getRefreshTtl(): int
  83. {
  84. return $this->refreshTtl;
  85. }
  86. /**
  87. * 单位:分钟
  88. * @return $this
  89. */
  90. public function setRefreshTtl(int $ttl): JWTManager
  91. {
  92. $this->refreshTtl = $ttl;
  93. return $this;
  94. }
  95. public function getEncrypter(): Encrypter
  96. {
  97. return $this->encrypter;
  98. }
  99. public function getEncoder(): Encoder
  100. {
  101. return $this->encoder;
  102. }
  103. /**
  104. * 创建一个 jwt.
  105. */
  106. public function make(array $payload, array $headers = []): JWT
  107. {
  108. $payload = array_merge($this->initPayload(), $payload);
  109. $jti = hash('md5', base64_encode(json_encode([$payload, $headers])) . $this->getEncrypter()->getSecret());
  110. $payload['jti'] = $jti;
  111. return new JWT($this, $headers, $payload);
  112. }
  113. /**
  114. * 一些基础参数.
  115. */
  116. public function initPayload(): array
  117. {
  118. $timestamp = time();
  119. return [
  120. 'sub' => '1',
  121. 'iss' => 'http://' . ($_SERVER['SERVER_NAME'] ?? '') . ':' . ($_SERVER['SERVER_PORT'] ?? '') . ($_SERVER['REQUEST_URI'] ?? ''),
  122. 'exp' => $timestamp + $this->getTtl(),
  123. 'iat' => $timestamp,
  124. 'nbf' => $timestamp,
  125. ];
  126. }
  127. /**
  128. * 解析一个jwt.
  129. * @throws Exceptions\InvalidTokenException
  130. * @throws Exceptions\SignatureException
  131. * @throws Exceptions\TokenExpiredException
  132. */
  133. public function parse(string $token): JWT
  134. {
  135. $jwt = $this->justParse($token);
  136. $timestamp = time();
  137. $payload = $jwt->getPayload();
  138. if ($this->hasBlacklist($jwt)) {
  139. throw (new TokenBlacklistException('The token is already on the blacklist'))->setJwt($jwt);
  140. }
  141. if (isset($payload['exp']) && $payload['exp'] <= $timestamp) {
  142. throw (new TokenExpiredException('Token expired'))->setJwt($jwt);
  143. }
  144. if (isset($payload['nbf']) && $payload['nbf'] > $timestamp) {
  145. throw (new TokenNotActiveException('Token not active'))->setJwt($jwt);
  146. }
  147. return $jwt;
  148. }
  149. /**
  150. * 单纯的解析一个jwt.
  151. * @throws Exceptions\InvalidTokenException
  152. * @throws Exceptions\SignatureException
  153. * @throws Exceptions\TokenExpiredException
  154. */
  155. public function justParse(string $token): JWT
  156. {
  157. $encoder = $this->getEncoder();
  158. $encrypter = $this->getEncrypter();
  159. $arr = explode('.', $token);
  160. if (count($arr) !== 3) {
  161. throw new InvalidTokenException('Invalid token');
  162. }
  163. $headers = @json_decode($encoder->decode($arr[0]), true);
  164. $payload = @json_decode($encoder->decode($arr[1]), true);
  165. $signatureString = "{$arr[0]}.{$arr[1]}";
  166. if (! is_array($headers) || ! is_array($payload)) {
  167. throw new InvalidTokenException('Invalid token');
  168. }
  169. if ($encrypter->check($signatureString, $encoder->decode($arr[2]))) {
  170. return new JWT($this, $headers, $payload);
  171. }
  172. throw new SignatureException('Invalid signature');
  173. }
  174. public function addBlacklist($jwt)
  175. {
  176. $now = time();
  177. $this->getCache()->save(
  178. $this->blacklistKey($jwt),
  179. $now,
  180. ($jwt instanceof JWT ? ($jwt->getPayload()['iat'] || $now) : $now) + $this->getRefreshTtl() // 存到该 token 超过 refresh 即可
  181. );
  182. }
  183. public function removeBlacklist($jwt)
  184. {
  185. return $this->getCache()->delete($this->blacklistKey($jwt));
  186. }
  187. public function hasBlacklist($jwt)
  188. {
  189. return $this->getCache()->contains($this->blacklistKey($jwt));
  190. }
  191. /**
  192. * @throws Exceptions\JWTException
  193. * @return JWT
  194. */
  195. public function refresh(JWT $jwt, bool $force = false)
  196. {
  197. $payload = $jwt->getPayload();
  198. if (! $force && isset($payload['iat'])) {
  199. $refreshExp = $payload['iat'] + $this->getRefreshTtl();
  200. if ($refreshExp <= time()) {
  201. throw (new TokenRefreshExpiredException('token expired, refresh is not supported'))->setJwt($jwt);
  202. }
  203. }
  204. unset($payload['exp'], $payload['iat'], $payload['nbf']);
  205. return $this->make($payload, $jwt->getHeaders());
  206. }
  207. public function useEncrypter(string $encrypter): JWTManager
  208. {
  209. $this->resolveEncrypter($encrypter);
  210. return $this;
  211. }
  212. /**
  213. * @param JWT|string $jwt
  214. * @return string
  215. */
  216. protected function blacklistKey($jwt)
  217. {
  218. $jti = $jwt instanceof JWT ? ($jwt->getPayload()['jti'] ?? md5($jwt->token())) : md5($jwt);
  219. return "jwt:blacklist:{$this->prefix}:{$jti}";
  220. }
  221. protected function verifyConfig(array $config)
  222. {
  223. if (! isset($config['secret'])) {
  224. throw new \InvalidArgumentException('Secret is required.');
  225. }
  226. }
  227. protected function resolveEncrypter($encrypter)
  228. {
  229. if ($encrypter instanceof Encrypter) {
  230. $this->encrypter = $encrypter;
  231. return;
  232. }
  233. if (class_exists($encrypter)) {
  234. $this->encrypter = new $encrypter($this->secret);
  235. return;
  236. }
  237. if (isset($this->drivers[$encrypter])) {
  238. $encrypter = $this->drivers[$encrypter];
  239. $this->encrypter = new $encrypter($this->secret);
  240. } else {
  241. $this->encrypter = new PasswordHashEncrypter($this->secret);
  242. }
  243. }
  244. }