Skip to content

Commit bb6d53b

Browse files
Allow timestamp to be specified rather than relying on PHP time() function
1 parent c35d52b commit bb6d53b

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/JWT.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ class JWT
2929
*/
3030
public static $leeway = 0;
3131

32+
/**
33+
* Allow the current timestamp to be specified.
34+
* Useful for fixing a value within unit testing.
35+
* Will default to PHP time() value if null.
36+
*/
37+
public static $timestamp = null;
38+
3239
public static $supported_algs = array(
3340
'HS256' => array('hash_hmac', 'SHA256'),
3441
'HS512' => array('hash_hmac', 'SHA512'),
@@ -59,6 +66,8 @@ class JWT
5966
*/
6067
public static function decode($jwt, $key, $allowed_algs = array())
6168
{
69+
$timestamp = is_null(self::$timestamp) ? time() : self::$timestamp;
70+
6271
if (empty($key)) {
6372
throw new InvalidArgumentException('Key may not be empty');
6473
}
@@ -99,7 +108,7 @@ public static function decode($jwt, $key, $allowed_algs = array())
99108

100109
// Check if the nbf if it is defined. This is the time that the
101110
// token can actually be used. If it's not yet that time, abort.
102-
if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) {
111+
if (isset($payload->nbf) && $payload->nbf > ($timestamp + self::$leeway)) {
103112
throw new BeforeValidException(
104113
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
105114
);
@@ -108,14 +117,14 @@ public static function decode($jwt, $key, $allowed_algs = array())
108117
// Check that this token has been created before 'now'. This prevents
109118
// using tokens that have been created for later use (and haven't
110119
// correctly used the nbf claim).
111-
if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) {
120+
if (isset($payload->iat) && $payload->iat > ($timestamp + self::$leeway)) {
112121
throw new BeforeValidException(
113122
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
114123
);
115124
}
116125

117126
// Check if this token has expired.
118-
if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) {
127+
if (isset($payload->exp) && ($timestamp - self::$leeway) >= $payload->exp) {
119128
throw new ExpiredException('Expired token');
120129
}
121130

0 commit comments

Comments
 (0)