暫無描述

JWT.php 14KB

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