Skip to content

Commit

Permalink
feat: adds audience validation when validating a jwt (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
ctran88 authored Dec 10, 2024
1 parent 9317085 commit 1700bce
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 16 deletions.
15 changes: 4 additions & 11 deletions custom/lib/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct(private string $appId, private Configuration $config
$httpClient,
$httpFactory,
$cacheItemPool,
null,
60 * 60 * 24, // expires in 24 hours
true
);
}
Expand All @@ -56,19 +56,12 @@ public function validateJwt(string $jwt): string
throw new InvalidArgumentException('JWT is required');
}

$jwtSegments = explode('.', $jwt);
if (count($jwtSegments) !== 3) {
throw new InvalidArgumentException('Invalid JWT format');
}

$decodedHeader = JWT::urlsafeB64Decode($jwtSegments[0]);
$header = json_decode($decodedHeader);
$decodedToken = JWT::decode($jwt, $this->jwks);

if (!$header->kid) {
throw new InvalidArgumentException('Missing kid in token');
if (!in_array($this->appId, $decodedToken->aud)) {
throw new UnexpectedValueException('JWT audience does not match');
}

$decodedToken = JWT::decode($jwt, $this->jwks);
$userId = $decodedToken->sub;

if (!$userId) {
Expand Down
6 changes: 3 additions & 3 deletions custom/test/AuthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Passage\Test;

use Dotenv\Dotenv;
use InvalidArgumentException;
use UnexpectedValueException;
use PHPUnit\Framework\TestCase;
use Passage\Client\Passage;

Expand Down Expand Up @@ -38,8 +38,8 @@ public function testValidateJwtValidToken()

public function testValidateJwtInvalidTokenStructure()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid JWT format');
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Wrong number of segments');
$this->passage->auth->validateJwt('incorrect.token');
}
}
4 changes: 2 additions & 2 deletions custom/test/PassageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ public function testPassageVersionHeader()

public function testConstructorWithAppId()
{
$passage = new Passage('123456', '987654');
$passage = new Passage($this->appId, $this->apiKey);

// Assert that the object was created successfully
$this->assertInstanceOf(Passage::class, $passage);

// Assert that app_id and api_key properties are correctly set
$this->assertEquals('123456', $passage->getAppId());
$this->assertEquals($this->appId, $passage->getAppId());
}

public function testGetApp()
Expand Down

0 comments on commit 1700bce

Please sign in to comment.