Skip to content

Commit

Permalink
Create jwt with custom claims (#11)
Browse files Browse the repository at this point in the history
* Create jwt with custom claims
* Fix typo
  • Loading branch information
pulzarraider authored Jul 25, 2023
1 parent 2762416 commit 280bb99
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/Util/JwtUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,33 @@ public function __construct(
/**
* Can be used for creating a valid JWT. Useful especially for test environment.
*
* @param array<string, mixed> $claims
*
* @throws MissingConfigurationException
*/
public function create(string $authId, DateTimeImmutable $expiresAt = null): Plain
public function create(string $authId, DateTimeImmutable $expiresAt = null, array $claims = []): Plain
{
$privateCert = $this->jwtConfiguration->getPrivateCert();

if (empty($privateCert)) {
throw MissingConfigurationException::createForPrivateCertPath();
}

return (new Builder(new JoseEncoder(), ChainedFormatter::withUnixTimestampDates()))
$builder = (new Builder(new JoseEncoder(), ChainedFormatter::withUnixTimestampDates()))
->permittedFor($this->jwtConfiguration->getAudience())
->issuedAt(new DateTimeImmutable())
->canOnlyBeUsedAfter(new DateTimeImmutable())
->expiresAt($expiresAt ?: new DateTimeImmutable(sprintf('+%d seconds', $this->jwtConfiguration->getLifetime())))
->relatedTo($authId)
->getToken(
$this->jwtConfiguration->getAlgorithm()->signer(),
InMemory::plainText($privateCert)
);
->relatedTo($authId);

foreach ($claims as $key => $value) {
$builder->withClaim($key, $value);
}

return $builder->getToken(
$this->jwtConfiguration->getAlgorithm()->signer(),
InMemory::plainText($privateCert)
);
}

public function validate(Token\Plain $token): bool
Expand Down
18 changes: 18 additions & 0 deletions tests/Util/JwtUtilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,22 @@ public function testCreate(): void
);
$this->assertSame(['anz'], $jwt->claims()->get(RegisteredClaims::AUDIENCE));
}

/**
* @throws MissingConfigurationException
*/
public function testCreateWithClaims(): void
{
$expireAt = new DateTimeImmutable(sprintf('+%d seconds', $this->jwtConfiguration->getLifetime()));
$jwt = $this->jwtUtil->create('123', $expireAt, ['foo' => 'bar', 'qux' => 'quux']);
$this->assertInstanceOf(Plain::class, $jwt);
$this->assertSame('123', $jwt->claims()->get(RegisteredClaims::SUBJECT));
$this->assertSame('bar', $jwt->claims()->get('foo'));
$this->assertSame('quux', $jwt->claims()->get('qux'));
$this->assertSame(
$expireAt->getTimestamp(),
$jwt->claims()->get(RegisteredClaims::EXPIRATION_TIME)->getTimestamp()
);
$this->assertSame(['anz'], $jwt->claims()->get(RegisteredClaims::AUDIENCE));
}
}

0 comments on commit 280bb99

Please sign in to comment.