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