Skip to content
This repository has been archived by the owner on Jan 15, 2024. It is now read-only.

Fix issue where audience claims were unable to validate when its an a… #18

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions src/Authenticator/JwtKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,14 @@ public function validateClaims(array $claims)
if (isset($claims['iss']) && $claims['iss'] !== $this->issuer) {
throw new \InvalidArgumentException("Issuer mismatch");
}
if (isset($claims['aud']) &&
(
(is_array($this->audience) && !in_array($claims['aud'], $this->audience))
|| (!is_array($this->audience) && $claims['aud'] !== $this->audience)
)
) {
throw new \InvalidArgumentException("Audience mismatch");
if (isset($claims['aud'])) {
if (is_array($claims['aud'])) {
foreach ($claims['aud'] as $claim) {
$this->validateAudience($claim);
}
} else {
$this->validateAudience($claims['aud']);
}
}
}

Expand All @@ -202,6 +203,18 @@ public function getSignatureValidator()
return new HmacValidator();
}

/**
* @param $audience
*/
private function validateAudience($audience)
{
if ((is_array($this->audience) && !in_array($audience, $this->audience))
|| (!is_array($this->audience) && $audience !== $this->audience)
) {
throw new \InvalidArgumentException("Audience mismatch");
}
}

/**
* Prevent accidental persistence of secret
*/
Expand Down
18 changes: 18 additions & 0 deletions src/Tests/Authenticator/JwtKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ public function willValidateIfAudienceIsConfiguredAndMatchedAny()
$key->validateClaims(['sub' => 'john', 'aud' => 'reader']);
}

/**
* @test
*/
public function willValidateIfAudienceClaimIsArrayAndMatchesAll()
{
$key = new JwtKey(['secret' => 'Buy the book', 'audience' => ['author', 'editor', 'reader']]);
$key->validateClaims(['sub' => 'john', 'aud' => ['author', 'reader']]);
}

/**
* @test
*/
Expand Down Expand Up @@ -225,6 +234,15 @@ public function validationWillFailWhenAudienceDoesNotMatch()
$key->validateClaims(['sub' => 'john', 'aud' => 'the neighbours']);
}

/**
* @test
* @expectedException \InvalidArgumentException
*/
public function validationWillFailWhenSingleAudienceClaimFromArrayDoesNotMatch()
{
$key = new JwtKey(['secret' => 'Buy the book', 'audience' => 'me']);
$key->validateClaims(['sub' => 'john', 'aud' => ['the neighbours', 'me']]);
}

/**
* @test
Expand Down