@@ -29,6 +29,13 @@ class JWT
29
29
*/
30
30
public static $ leeway = 0 ;
31
31
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
+
32
39
public static $ supported_algs = array (
33
40
'HS256 ' => array ('hash_hmac ' , 'SHA256 ' ),
34
41
'HS512 ' => array ('hash_hmac ' , 'SHA512 ' ),
@@ -59,6 +66,8 @@ class JWT
59
66
*/
60
67
public static function decode ($ jwt , $ key , $ allowed_algs = array ())
61
68
{
69
+ $ timestamp = is_null (self ::$ timestamp ) ? time () : self ::$ timestamp ;
70
+
62
71
if (empty ($ key )) {
63
72
throw new InvalidArgumentException ('Key may not be empty ' );
64
73
}
@@ -99,7 +108,7 @@ public static function decode($jwt, $key, $allowed_algs = array())
99
108
100
109
// Check if the nbf if it is defined. This is the time that the
101
110
// 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 )) {
103
112
throw new BeforeValidException (
104
113
'Cannot handle token prior to ' . date (DateTime::ISO8601 , $ payload ->nbf )
105
114
);
@@ -108,14 +117,14 @@ public static function decode($jwt, $key, $allowed_algs = array())
108
117
// Check that this token has been created before 'now'. This prevents
109
118
// using tokens that have been created for later use (and haven't
110
119
// 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 )) {
112
121
throw new BeforeValidException (
113
122
'Cannot handle token prior to ' . date (DateTime::ISO8601 , $ payload ->iat )
114
123
);
115
124
}
116
125
117
126
// 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 ) {
119
128
throw new ExpiredException ('Expired token ' );
120
129
}
121
130
0 commit comments