3 namespace Firebase\JWT;
5 use \InvalidArgumentException;
6 use \UnexpectedValueException;
10 * JSON Web Token implementation, based on this spec:
11 * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
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
26 * When checking nbf, iat or expiration times,
27 * we want to provide some extra leeway time to
28 * account for clock skew.
30 public static $leeway = 0;
33 * Allow the current timestamp to be specified.
34 * Useful for fixing a value within unit testing.
36 * Will default to PHP time() value if null.
38 public static $timestamp = null;
40 public static $supported_algs = array(
41 'HS256' => array('hash_hmac', 'SHA256'),
42 'HS512' => array('hash_hmac', 'SHA512'),
43 'HS384' => array('hash_hmac', 'SHA384'),
44 'RS256' => array('openssl', 'SHA256'),
48 * Decodes a JWT string into a PHP object.
50 * @param string $jwt The JWT
51 * @param string|array $key The key, or map of keys.
52 * If the algorithm used is asymmetric, this is the public key
53 * @param array $allowed_algs List of supported verification algorithms
54 * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
56 * @return object The JWT's payload as a PHP object
58 * @throws UnexpectedValueException Provided JWT was invalid
59 * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
60 * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
61 * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
62 * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
65 * @uses urlsafeB64Decode
67 public static function decode($jwt, $key, $allowed_algs = array())
69 $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
72 throw new InvalidArgumentException('Key may not be empty');
74 if (!is_array($allowed_algs)) {
75 throw new InvalidArgumentException('Algorithm not allowed');
77 $tks = explode('.', $jwt);
78 if (count($tks) != 3) {
79 throw new UnexpectedValueException('Wrong number of segments');
81 list($headb64, $bodyb64, $cryptob64) = $tks;
82 if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
83 throw new UnexpectedValueException('Invalid header encoding');
85 if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
86 throw new UnexpectedValueException('Invalid claims encoding');
88 $sig = static::urlsafeB64Decode($cryptob64);
90 if (empty($header->alg)) {
91 throw new UnexpectedValueException('Empty algorithm');
93 if (empty(static::$supported_algs[$header->alg])) {
94 throw new UnexpectedValueException('Algorithm not supported');
96 if (!in_array($header->alg, $allowed_algs)) {
97 throw new UnexpectedValueException('Algorithm not allowed');
99 if (is_array($key) || $key instanceof \ArrayAccess) {
100 if (isset($header->kid)) {
101 $key = $key[$header->kid];
103 throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
107 // Check the signature
108 if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
109 throw new SignatureInvalidException('Signature verification failed');
112 // Check if the nbf if it is defined. This is the time that the
113 // token can actually be used. If it's not yet that time, abort.
114 if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
115 throw new BeforeValidException(
116 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
120 // Check that this token has been created before 'now'. This prevents
121 // using tokens that have been created for later use (and haven't
122 // correctly used the nbf claim).
123 if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
124 throw new BeforeValidException(
125 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
129 // Check if this token has expired.
130 if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
131 throw new ExpiredException('Expired token');
138 * Converts and signs a PHP object or array into a JWT string.
140 * @param object|array $payload PHP object or array
141 * @param string $key The secret key.
142 * If the algorithm used is asymmetric, this is the private key
143 * @param string $alg The signing algorithm.
144 * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
145 * @param mixed $keyId
146 * @param array $head An array with header elements to attach
148 * @return string A signed JWT
151 * @uses urlsafeB64Encode
153 public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
155 $header = array('typ' => 'JWT', 'alg' => $alg);
156 if ($keyId !== null) {
157 $header['kid'] = $keyId;
159 if ( isset($head) && is_array($head) ) {
160 $header = array_merge($head, $header);
163 $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
164 $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
165 $signing_input = implode('.', $segments);
167 $signature = static::sign($signing_input, $key, $alg);
168 $segments[] = static::urlsafeB64Encode($signature);
170 return implode('.', $segments);
174 * Sign a string with a given key and algorithm.
176 * @param string $msg The message to sign
177 * @param string|resource $key The secret key
178 * @param string $alg The signing algorithm.
179 * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
181 * @return string An encrypted message
183 * @throws DomainException Unsupported algorithm was specified
185 public static function sign($msg, $key, $alg = 'HS256')
187 if (empty(static::$supported_algs[$alg])) {
188 throw new DomainException('Algorithm not supported');
190 list($function, $algorithm) = static::$supported_algs[$alg];
193 return hash_hmac($algorithm, $msg, $key, true);
196 $success = openssl_sign($msg, $signature, $key, $algorithm);
198 throw new DomainException("OpenSSL unable to sign data");
206 * Verify a signature with the message, key and method. Not all methods
207 * are symmetric, so we must have a separate verify and sign method.
209 * @param string $msg The original message (header and body)
210 * @param string $signature The original signature
211 * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key
212 * @param string $alg The algorithm
216 * @throws DomainException Invalid Algorithm or OpenSSL failure
218 private static function verify($msg, $signature, $key, $alg)
220 if (empty(static::$supported_algs[$alg])) {
221 throw new DomainException('Algorithm not supported');
224 list($function, $algorithm) = static::$supported_algs[$alg];
227 $success = openssl_verify($msg, $signature, $key, $algorithm);
229 throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
235 $hash = hash_hmac($algorithm, $msg, $key, true);
236 if (function_exists('hash_equals')) {
237 return hash_equals($signature, $hash);
239 $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
242 for ($i = 0; $i < $len; $i++) {
243 $status |= (ord($signature[$i]) ^ ord($hash[$i]));
245 $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
247 return ($status === 0);
252 * Decode a JSON string into a PHP object.
254 * @param string $input JSON string
256 * @return object Object representation of JSON string
258 * @throws DomainException Provided string was invalid JSON
260 public static function jsonDecode($input)
262 if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
263 /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
264 * to specify that large ints (like Steam Transaction IDs) should be treated as
265 * strings, rather than the PHP default behaviour of converting them to floats.
267 $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
269 /** Not all servers will support that, however, so for older versions we must
270 * manually detect large ints in the JSON string and quote them (thus converting
271 *them to strings) before decoding, hence the preg_replace() call.
273 $max_int_length = strlen((string) PHP_INT_MAX) - 1;
274 $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
275 $obj = json_decode($json_without_bigints);
278 if (function_exists('json_last_error') && $errno = json_last_error()) {
279 static::handleJsonError($errno);
280 } elseif ($obj === null && $input !== 'null') {
281 throw new DomainException('Null result with non-null input');
287 * Encode a PHP object into a JSON string.
289 * @param object|array $input A PHP object or array
291 * @return string JSON representation of the PHP object or array
293 * @throws DomainException Provided object could not be encoded to valid JSON
295 public static function jsonEncode($input)
297 $json = json_encode($input);
298 if (function_exists('json_last_error') && $errno = json_last_error()) {
299 static::handleJsonError($errno);
300 } elseif ($json === 'null' && $input !== null) {
301 throw new DomainException('Null result with non-null input');
307 * Decode a string with URL-safe Base64.
309 * @param string $input A Base64 encoded string
311 * @return string A decoded string
313 public static function urlsafeB64Decode($input)
315 $remainder = strlen($input) % 4;
317 $padlen = 4 - $remainder;
318 $input .= str_repeat('=', $padlen);
320 return base64_decode(strtr($input, '-_', '+/'));
324 * Encode a string with URL-safe Base64.
326 * @param string $input The string you want encoded
328 * @return string The base64 encode of what you passed in
330 public static function urlsafeB64Encode($input)
332 return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
336 * Helper method to create a JSON error.
338 * @param int $errno An error number from json_last_error()
342 private static function handleJsonError($errno)
345 JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
346 JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
347 JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
349 throw new DomainException(
350 isset($messages[$errno])
352 : 'Unknown JSON error: ' . $errno
357 * Get the number of bytes in cryptographic strings.
363 private static function safeStrlen($str)
365 if (function_exists('mb_strlen')) {
366 return mb_strlen($str, '8bit');