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