summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJoseph McDermott <code@josephmcdermott.co.uk>2016-04-29 15:18:23 +0100
committerJoseph McDermott <code@josephmcdermott.co.uk>2016-04-29 15:18:23 +0100
commitbb6d53b94367d4e32bbcc0f7e90b658b37fdbdfd (patch)
tree4464a831e9afc6a1ff4009bc1db82f0f056858b2
parentc35d52bd53fafd4a92c72c8e0b8489ebfc1a4306 (diff)
downloadphp-jwt-bb6d53b94367d4e32bbcc0f7e90b658b37fdbdfd.zip
php-jwt-bb6d53b94367d4e32bbcc0f7e90b658b37fdbdfd.tar.gz
php-jwt-bb6d53b94367d4e32bbcc0f7e90b658b37fdbdfd.tar.bz2
Allow timestamp to be specified rather than relying on PHP time() function
-rw-r--r--src/JWT.php15
1 files changed, 12 insertions, 3 deletions
diff --git a/src/JWT.php b/src/JWT.php
index b3532df..6a12063 100644
--- a/src/JWT.php
+++ b/src/JWT.php
@@ -29,6 +29,13 @@ class JWT
*/
public static $leeway = 0;
+ /**
+ * Allow the current timestamp to be specified.
+ * Useful for fixing a value within unit testing.
+ * Will default to PHP time() value if null.
+ */
+ public static $timestamp = null;
+
public static $supported_algs = array(
'HS256' => array('hash_hmac', 'SHA256'),
'HS512' => array('hash_hmac', 'SHA512'),
@@ -59,6 +66,8 @@ class JWT
*/
public static function decode($jwt, $key, $allowed_algs = array())
{
+ $timestamp = is_null(self::$timestamp) ? time() : self::$timestamp;
+
if (empty($key)) {
throw new InvalidArgumentException('Key may not be empty');
}
@@ -99,7 +108,7 @@ class JWT
// Check if the nbf if it is defined. This is the time that the
// token can actually be used. If it's not yet that time, abort.
- if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) {
+ if (isset($payload->nbf) && $payload->nbf > ($timestamp + self::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
);
@@ -108,14 +117,14 @@ class JWT
// Check that this token has been created before 'now'. This prevents
// using tokens that have been created for later use (and haven't
// correctly used the nbf claim).
- if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) {
+ if (isset($payload->iat) && $payload->iat > ($timestamp + self::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);
}
// Check if this token has expired.
- if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) {
+ if (isset($payload->exp) && ($timestamp - self::$leeway) >= $payload->exp) {
throw new ExpiredException('Expired token');
}