Skip to content

Commit 0b01cd0

Browse files
author
Brendan Abbott
committed
Add checking of nbf claim
1 parent b18c305 commit 0b01cd0

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

Authentication/JWT.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,22 @@ public static function decode($jwt, $key = null, $verify = true)
6161
throw new DomainException('"kid" empty, unable to lookup correct key');
6262
}
6363
}
64+
65+
// Check the signature
6466
if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
6567
throw new UnexpectedValueException('Signature verification failed');
6668
}
69+
6770
// Check token expiry time if defined.
6871
if (isset($payload->exp) && time() >= $payload->exp) {
69-
throw new UnexpectedValueException('Expired Token');
72+
throw new UnexpectedValueException('Expired token');
73+
}
74+
75+
// Check if the nbf if it is defined.
76+
if (isset($payload->nbf) && $payload->nbf > time()) {
77+
throw new UnexpectedValueException(
78+
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
79+
);
7080
}
7181
}
7282
return $payload;

tests/JWTTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,16 @@ public function testExpiredToken()
4545
JWT::decode($encoded);
4646
}
4747

48+
public function testTooEarlyToken()
49+
{
50+
$this->setExpectedException('UnexpectedValueException');
51+
$payload = array(
52+
"message" => "abc",
53+
"nbf" => time() + 20); // time in the past
54+
$encoded = JWT::encode($payload, 'my_key');
55+
JWT::decode($encoded);
56+
}
57+
4858
public function testValidToken()
4959
{
5060
$payload = array(
@@ -55,6 +65,17 @@ public function testValidToken()
5565
$this->assertEquals($decoded->message, 'abc');
5666
}
5767

68+
public function testValidTokenWithNbf()
69+
{
70+
$payload = array(
71+
"message" => "abc",
72+
"exp" => time() + 20, // time in the future
73+
"nbf" => time() - 20);
74+
$encoded = JWT::encode($payload, 'my_key');
75+
$decoded = JWT::decode($encoded, 'my_key');
76+
$this->assertEquals($decoded->message, 'abc');
77+
}
78+
5879
public function testInvalidToken()
5980
{
6081
$payload = array(

0 commit comments

Comments
 (0)