Jwt.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. namespace Mall\Framework\Core;
  3. use \DomainException;
  4. use \InvalidArgumentException;
  5. use \UnexpectedValueException;
  6. use \DateTime;
  7. /**
  8. * JSON Web Token implementation, based on this spec:
  9. * https://tools.ietf.org/html/rfc7519
  10. *
  11. * PHP version 5
  12. *
  13. * @category Authentication
  14. * @package Authentication_JWT
  15. * @author Neuman Vong <neuman@twilio.com>
  16. * @author Anant Narayanan <anant@php.net>
  17. * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
  18. * @link https://github.com/firebase/php-jwt
  19. */
  20. class Jwt
  21. {
  22. /**
  23. * When checking nbf, iat or expiration times,
  24. * we want to provide some extra leeway time to
  25. * account for clock skew.
  26. */
  27. public static $leeway = 0;
  28. /**
  29. * Allow the current timestamp to be specified.
  30. * Useful for fixing a value within unit testing.
  31. *
  32. * Will default to PHP time() value if null.
  33. */
  34. public static $timestamp = null;
  35. public static $supported_algs = array(
  36. 'HS256' => array('hash_hmac', 'SHA256'),
  37. 'HS512' => array('hash_hmac', 'SHA512'),
  38. 'HS384' => array('hash_hmac', 'SHA384'),
  39. 'RS256' => array('openssl', 'SHA256'),
  40. 'RS384' => array('openssl', 'SHA384'),
  41. 'RS512' => array('openssl', 'SHA512'),
  42. );
  43. /**
  44. * Decodes a JWT string into a PHP object.
  45. *
  46. * @param string $jwt The JWT
  47. * @param string|array $key The key, or map of keys.
  48. * If the algorithm used is asymmetric, this is the public key
  49. * @param array $allowed_algs List of supported verification algorithms
  50. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  51. *
  52. * @return object The JWT's payload as a PHP object
  53. *
  54. * @throws UnexpectedValueException Provided JWT was invalid
  55. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  56. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  57. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  58. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  59. *
  60. * @uses jsonDecode
  61. * @uses urlsafeB64Decode
  62. */
  63. public static function decode($jwt, $key, $allowed_algs = array())
  64. {
  65. $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
  66. if (empty($key)) {
  67. throw new InvalidArgumentException('Key may not be empty');
  68. }
  69. if (!is_array($allowed_algs)) {
  70. throw new InvalidArgumentException('Algorithm not allowed');
  71. }
  72. $tks = explode('.', $jwt);
  73. if (count($tks) != 3) {
  74. throw new UnexpectedValueException('Wrong number of segments');
  75. }
  76. list($headb64, $bodyb64, $cryptob64) = $tks;
  77. if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
  78. throw new UnexpectedValueException('Invalid header encoding');
  79. }
  80. if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
  81. throw new UnexpectedValueException('Invalid claims encoding');
  82. }
  83. if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
  84. throw new UnexpectedValueException('Invalid signature encoding');
  85. }
  86. if (empty($header->alg)) {
  87. throw new UnexpectedValueException('Empty algorithm');
  88. }
  89. if (empty(static::$supported_algs[$header->alg])) {
  90. throw new UnexpectedValueException('Algorithm not supported');
  91. }
  92. if (!in_array($header->alg, $allowed_algs)) {
  93. throw new UnexpectedValueException('Algorithm not allowed');
  94. }
  95. if (is_array($key) || $key instanceof \ArrayAccess) {
  96. if (isset($header->kid)) {
  97. if (!isset($key[$header->kid])) {
  98. throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
  99. }
  100. $key = $key[$header->kid];
  101. } else {
  102. throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
  103. }
  104. }
  105. // Check the signature
  106. if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
  107. throw new UnexpectedValueException('Signature verification failed');
  108. }
  109. // Check if the nbf if it is defined. This is the time that the
  110. // token can actually be used. If it's not yet that time, abort.
  111. if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
  112. throw new UnexpectedValueException(
  113. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
  114. );
  115. }
  116. // Check that this token has been created before 'now'. This prevents
  117. // using tokens that have been created for later use (and haven't
  118. // correctly used the nbf claim).
  119. if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
  120. throw new UnexpectedValueException(
  121. 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
  122. );
  123. }
  124. // Check if this token has expired.
  125. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
  126. throw new UnexpectedValueException('Expired token');
  127. }
  128. return $payload;
  129. }
  130. /**
  131. * Converts and signs a PHP object or array into a JWT string.
  132. *
  133. * @param object|array $payload PHP object or array
  134. * @param string $key The secret key.
  135. * If the algorithm used is asymmetric, this is the private key
  136. * @param string $alg The signing algorithm.
  137. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  138. * @param mixed $keyId
  139. * @param array $head An array with header elements to attach
  140. *
  141. * @return string A signed JWT
  142. *
  143. * @uses jsonEncode
  144. * @uses urlsafeB64Encode
  145. */
  146. public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
  147. {
  148. $header = array('typ' => 'JWT', 'alg' => $alg);
  149. if ($keyId !== null) {
  150. $header['kid'] = $keyId;
  151. }
  152. if ( isset($head) && is_array($head) ) {
  153. $header = array_merge($head, $header);
  154. }
  155. $segments = array();
  156. $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
  157. $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
  158. $signing_input = implode('.', $segments);
  159. $signature = static::sign($signing_input, $key, $alg);
  160. $segments[] = static::urlsafeB64Encode($signature);
  161. return implode('.', $segments);
  162. }
  163. /**
  164. * Sign a string with a given key and algorithm.
  165. *
  166. * @param string $msg The message to sign
  167. * @param string|resource $key The secret key
  168. * @param string $alg The signing algorithm.
  169. * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
  170. *
  171. * @return string An encrypted message
  172. *
  173. * @throws DomainException Unsupported algorithm was specified
  174. */
  175. public static function sign($msg, $key, $alg = 'HS256')
  176. {
  177. if (empty(static::$supported_algs[$alg])) {
  178. throw new DomainException('Algorithm not supported');
  179. }
  180. list($function, $algorithm) = static::$supported_algs[$alg];
  181. switch($function) {
  182. case 'hash_hmac':
  183. return hash_hmac($algorithm, $msg, $key, true);
  184. case 'openssl':
  185. $signature = '';
  186. $success = openssl_sign($msg, $signature, $key, $algorithm);
  187. if (!$success) {
  188. throw new DomainException("OpenSSL unable to sign data");
  189. } else {
  190. return $signature;
  191. }
  192. }
  193. }
  194. /**
  195. * Verify a signature with the message, key and method. Not all methods
  196. * are symmetric, so we must have a separate verify and sign method.
  197. *
  198. * @param string $msg The original message (header and body)
  199. * @param string $signature The original signature
  200. * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key
  201. * @param string $alg The algorithm
  202. *
  203. * @return bool
  204. *
  205. * @throws DomainException Invalid Algorithm or OpenSSL failure
  206. */
  207. private static function verify($msg, $signature, $key, $alg)
  208. {
  209. if (empty(static::$supported_algs[$alg])) {
  210. throw new DomainException('Algorithm not supported');
  211. }
  212. list($function, $algorithm) = static::$supported_algs[$alg];
  213. switch($function) {
  214. case 'openssl':
  215. $success = openssl_verify($msg, $signature, $key, $algorithm);
  216. if ($success === 1) {
  217. return true;
  218. } elseif ($success === 0) {
  219. return false;
  220. }
  221. // returns 1 on success, 0 on failure, -1 on error.
  222. throw new DomainException(
  223. 'OpenSSL error: ' . openssl_error_string()
  224. );
  225. case 'hash_hmac':
  226. default:
  227. $hash = hash_hmac($algorithm, $msg, $key, true);
  228. if (function_exists('hash_equals')) {
  229. return hash_equals($signature, $hash);
  230. }
  231. $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
  232. $status = 0;
  233. for ($i = 0; $i < $len; $i++) {
  234. $status |= (ord($signature[$i]) ^ ord($hash[$i]));
  235. }
  236. $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
  237. return ($status === 0);
  238. }
  239. }
  240. /**
  241. * Decode a JSON string into a PHP object.
  242. *
  243. * @param string $input JSON string
  244. *
  245. * @return object Object representation of JSON string
  246. *
  247. * @throws DomainException Provided string was invalid JSON
  248. */
  249. public static function jsonDecode($input)
  250. {
  251. if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  252. /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
  253. * to specify that large ints (like Steam Transaction IDs) should be treated as
  254. * strings, rather than the PHP default behaviour of converting them to floats.
  255. */
  256. $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  257. } else {
  258. /** Not all servers will support that, however, so for older versions we must
  259. * manually detect large ints in the JSON string and quote them (thus converting
  260. *them to strings) before decoding, hence the preg_replace() call.
  261. */
  262. $max_int_length = strlen((string) PHP_INT_MAX) - 1;
  263. $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
  264. $obj = json_decode($json_without_bigints);
  265. }
  266. if (function_exists('json_last_error') && $errno = json_last_error()) {
  267. static::handleJsonError($errno);
  268. } elseif ($obj === null && $input !== 'null') {
  269. throw new DomainException('Null result with non-null input');
  270. }
  271. return $obj;
  272. }
  273. /**
  274. * Encode a PHP object into a JSON string.
  275. *
  276. * @param object|array $input A PHP object or array
  277. *
  278. * @return string JSON representation of the PHP object or array
  279. *
  280. * @throws DomainException Provided object could not be encoded to valid JSON
  281. */
  282. public static function jsonEncode($input)
  283. {
  284. $json = json_encode($input);
  285. if (function_exists('json_last_error') && $errno = json_last_error()) {
  286. static::handleJsonError($errno);
  287. } elseif ($json === 'null' && $input !== null) {
  288. throw new DomainException('Null result with non-null input');
  289. }
  290. return $json;
  291. }
  292. /**
  293. * Decode a string with URL-safe Base64.
  294. *
  295. * @param string $input A Base64 encoded string
  296. *
  297. * @return string A decoded string
  298. */
  299. public static function urlsafeB64Decode($input)
  300. {
  301. $remainder = strlen($input) % 4;
  302. if ($remainder) {
  303. $padlen = 4 - $remainder;
  304. $input .= str_repeat('=', $padlen);
  305. }
  306. return base64_decode(strtr($input, '-_', '+/'));
  307. }
  308. /**
  309. * Encode a string with URL-safe Base64.
  310. *
  311. * @param string $input The string you want encoded
  312. *
  313. * @return string The base64 encode of what you passed in
  314. */
  315. public static function urlsafeB64Encode($input)
  316. {
  317. return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  318. }
  319. /**
  320. * Helper method to create a JSON error.
  321. *
  322. * @param int $errno An error number from json_last_error()
  323. *
  324. * @return void
  325. */
  326. private static function handleJsonError($errno)
  327. {
  328. $messages = array(
  329. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  330. JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
  331. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  332. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  333. JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
  334. );
  335. throw new DomainException(
  336. isset($messages[$errno])
  337. ? $messages[$errno]
  338. : 'Unknown JSON error: ' . $errno
  339. );
  340. }
  341. /**
  342. * Get the number of bytes in cryptographic strings.
  343. *
  344. * @param string
  345. *
  346. * @return int
  347. */
  348. private static function safeStrlen($str)
  349. {
  350. if (function_exists('mb_strlen')) {
  351. return mb_strlen($str, '8bit');
  352. }
  353. return strlen($str);
  354. }
  355. }