Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle claims conversion #171

Merged
merged 6 commits into from
Feb 23, 2017
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
7 changes: 4 additions & 3 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Lcobucci\JWT;

use DateTimeImmutable;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Token\Plain;

Expand All @@ -26,7 +27,7 @@ public function permittedFor(string $audience): Builder;
/**
* Configures the expiration time
*/
public function expiresAt(int $expiration): Builder;
public function expiresAt(DateTimeImmutable $expiration): Builder;

/**
* Configures the token id
Expand All @@ -36,7 +37,7 @@ public function identifiedBy(string $id): Builder;
/**
* Configures the time that the token was issued
*/
public function issuedAt(int $issuedAt): Builder;
public function issuedAt(DateTimeImmutable $issuedAt): Builder;

/**
* Configures the issuer
Expand All @@ -46,7 +47,7 @@ public function issuedBy(string $issuer): Builder;
/**
* Configures the time before which the token cannot be accepted
*/
public function canOnlyBeUsedAfter(int $notBefore): Builder;
public function canOnlyBeUsedAfter(DateTimeImmutable $notBefore): Builder;

/**
* Configures the subject
Expand Down
37 changes: 33 additions & 4 deletions src/Token/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Lcobucci\JWT\Token;

use DateTimeImmutable;
use Lcobucci\Jose\Parsing;
use Lcobucci\JWT\Builder as BuilderInterface;
use Lcobucci\JWT\Signer;
Expand Down Expand Up @@ -68,7 +69,7 @@ public function permittedFor(string $audience): BuilderInterface
/**
* {@inheritdoc}
*/
public function expiresAt(int $expiration): BuilderInterface
public function expiresAt(DateTimeImmutable $expiration): BuilderInterface
{
return $this->setClaim(RegisteredClaims::EXPIRATION_TIME, $expiration);
}
Expand All @@ -84,7 +85,7 @@ public function identifiedBy(string $id): BuilderInterface
/**
* {@inheritdoc}
*/
public function issuedAt(int $issuedAt): BuilderInterface
public function issuedAt(DateTimeImmutable $issuedAt): BuilderInterface
{
return $this->setClaim(RegisteredClaims::ISSUED_AT, $issuedAt);
}
Expand All @@ -100,7 +101,7 @@ public function issuedBy(string $issuer): BuilderInterface
/**
* {@inheritdoc}
*/
public function canOnlyBeUsedAfter(int $notBefore): BuilderInterface
public function canOnlyBeUsedAfter(DateTimeImmutable $notBefore): BuilderInterface
{
return $this->setClaim(RegisteredClaims::NOT_BEFORE, $notBefore);
}
Expand Down Expand Up @@ -158,7 +159,7 @@ public function getToken(Signer $signer, Key $key): Plain
$headers['alg'] = $signer->getAlgorithmId();

$encodedHeaders = $this->encode($headers);
$encodedClaims = $this->encode($this->claims);
$encodedClaims = $this->encode($this->formatClaims($this->claims));

$signature = $signer->sign($encodedHeaders . '.' . $encodedClaims, $key);
$encodedSignature = $this->encoder->base64UrlEncode($signature);
Expand All @@ -169,4 +170,32 @@ public function getToken(Signer $signer, Key $key): Plain
new Signature($signature, $encodedSignature)
);
}

private function formatClaims(array $claims): array
{
if (isset($claims[RegisteredClaims::AUDIENCE][0]) && !isset($claims[RegisteredClaims::AUDIENCE][1])) {
$claims[RegisteredClaims::AUDIENCE] = $claims[RegisteredClaims::AUDIENCE][0];
}

foreach (array_intersect(RegisteredClaims::DATE_CLAIMS, array_keys($claims)) as $claim) {
$claims[$claim] = $this->convertDate($claims[$claim]);
}

return $claims;
}

/**
* @return int|string
*/
private function convertDate(DateTimeImmutable $date)
{
$seconds = $date->format('U');
$microseconds = $date->format('u');

if ((int) $microseconds === 0) {
return (int) $seconds;
}

return $seconds . '.' . $microseconds;
}
}
22 changes: 21 additions & 1 deletion src/Token/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Lcobucci\JWT\Token;

use DateTimeImmutable;
use InvalidArgumentException;
use Lcobucci\Jose\Parsing;
use Lcobucci\JWT\Parser as ParserInterface;
Expand Down Expand Up @@ -90,7 +91,26 @@ private function parseHeader(string $data): array
*/
private function parseClaims(string $data): array
{
return (array) $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data));
$claims = (array) $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data));

if (isset($claims[RegisteredClaims::AUDIENCE])) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that casting null to (array) yields an empty array. I don't know if that's valid for $claims, but worth considering

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't want to set if it doesn't exist in the original token

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense

$claims[RegisteredClaims::AUDIENCE] = (array) $claims[RegisteredClaims::AUDIENCE];
}

foreach (array_intersect(RegisteredClaims::DATE_CLAIMS, array_keys($claims)) as $claim) {
$claims[$claim] = $this->convertDate((string) $claims[$claim]);
}

return $claims;
}

private function convertDate(string $value): DateTimeImmutable
{
if (strpos($value, '.') === false) {
return new DateTimeImmutable('@' . $value);
}

return DateTimeImmutable::createFromFormat('U.u', $value);
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/Token/Plain.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function payload(): string
*/
public function isPermittedFor(string $audience): bool
{
return in_array($audience, (array) $this->claims->get(RegisteredClaims::AUDIENCE), true);
return in_array($audience, $this->claims->get(RegisteredClaims::AUDIENCE, []), true);
}

/**
Expand Down Expand Up @@ -120,15 +120,15 @@ public function hasBeenIssuedBy(string ...$issuers): bool
*/
public function hasBeenIssuedBefore(DateTimeInterface $now): bool
{
return $now->getTimestamp() >= $this->claims->get(RegisteredClaims::ISSUED_AT);
return $now >= $this->claims->get(RegisteredClaims::ISSUED_AT);
}

/**
* {@inheritdoc}
*/
public function isMinimumTimeBefore(DateTimeInterface $now): bool
{
return $now->getTimestamp() >= $this->claims->get(RegisteredClaims::NOT_BEFORE);
return $now >= $this->claims->get(RegisteredClaims::NOT_BEFORE);
}

/**
Expand All @@ -140,7 +140,7 @@ public function isExpired(DateTimeInterface $now): bool
return false;
}

return $now->getTimestamp() > $this->claims->get(RegisteredClaims::EXPIRATION_TIME);
return $now > $this->claims->get(RegisteredClaims::EXPIRATION_TIME);
}

/**
Expand Down
6 changes: 6 additions & 0 deletions src/Token/RegisteredClaims.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ interface RegisteredClaims
self::SUBJECT
];

const DATE_CLAIMS = [
self::ISSUED_AT,
self::NOT_BEFORE,
self::EXPIRATION_TIME
];

/**
* Identifies the recipients that the JWT is intended for
*
Expand Down
9 changes: 6 additions & 3 deletions test/functional/UnsignedTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Lcobucci\JWT\FunctionalTests;

use DateTimeImmutable;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\Validation\Constraint;
Expand Down Expand Up @@ -55,17 +56,19 @@ public function builderCanGenerateAToken(): Token
$user = ['name' => 'testing', 'email' => 'testing@abc.com'];
$builder = $this->config->createBuilder();

$expiration = new DateTimeImmutable('@' . (self::CURRENT_TIME + 3000));

$token = $builder->identifiedBy('1')
->permittedFor('http://client.abc.com')
->issuedBy('http://api.abc.com')
->expiresAt(self::CURRENT_TIME + 3000)
->expiresAt($expiration)
->withClaim('user', $user)
->getToken($this->config->getSigner(), $this->config->getSigningKey());

self::assertAttributeEquals(new Token\Signature('', ''), 'signature', $token);
self::assertEquals(['http://client.abc.com'], $token->claims()->get(Token\RegisteredClaims::AUDIENCE));
self::assertEquals('http://api.abc.com', $token->claims()->get(Token\RegisteredClaims::ISSUER));
self::assertEquals(self::CURRENT_TIME + 3000, $token->claims()->get(Token\RegisteredClaims::EXPIRATION_TIME));
self::assertSame($expiration, $token->claims()->get(Token\RegisteredClaims::EXPIRATION_TIME));
self::assertEquals($user, $token->claims()->get('user'));

return $token;
Expand Down Expand Up @@ -118,7 +121,7 @@ public function tokenValidationShouldPassWhenEverythingIsFine(Token $generated):
new IdentifiedBy('1'),
new PermittedFor('http://client.abc.com'),
new IssuedBy('http://issuer.abc.com', 'http://api.abc.com'),
new ValidAt(new \DateTimeImmutable('@' . self::CURRENT_TIME))
new ValidAt(new DateTimeImmutable('@' . self::CURRENT_TIME))
];

self::assertTrue($this->config->getValidator()->validate($generated, ...$constraints));
Expand Down
46 changes: 34 additions & 12 deletions test/unit/Token/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Lcobucci\JWT\Token;

use DateTimeImmutable;
use Lcobucci\Jose\Parsing\Encoder;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
Expand Down Expand Up @@ -122,11 +123,13 @@ public function permittedForMustKeepAFluentInterface(): void
*/
public function expiresAtMustChangeTheExpClaim(): void
{
$now = new DateTimeImmutable();

$builder = $this->createBuilder();
$builder->expiresAt(2);
$builder->expiresAt($now);

self::assertAttributeEquals(['alg' => 'none', 'typ' => 'JWT'], 'headers', $builder);
self::assertAttributeEquals([RegisteredClaims::EXPIRATION_TIME => 2], 'claims', $builder);
self::assertAttributeEquals([RegisteredClaims::EXPIRATION_TIME => $now], 'claims', $builder);
}

/**
Expand All @@ -141,7 +144,7 @@ public function expiresAtMustKeepAFluentInterface(): void
{
$builder = $this->createBuilder();

self::assertSame($builder, $builder->expiresAt(2));
self::assertSame($builder, $builder->expiresAt(new DateTimeImmutable()));
}

/**
Expand Down Expand Up @@ -186,11 +189,13 @@ public function withIdMustKeepAFluentInterface(): void
*/
public function issuedAtMustChangeTheIatClaim(): void
{
$now = new DateTimeImmutable();

$builder = $this->createBuilder();
$builder->issuedAt(2);
$builder->issuedAt($now);

self::assertAttributeEquals(['alg' => 'none', 'typ' => 'JWT'], 'headers', $builder);
self::assertAttributeEquals([RegisteredClaims::ISSUED_AT => 2], 'claims', $builder);
self::assertAttributeEquals([RegisteredClaims::ISSUED_AT => $now], 'claims', $builder);
}

/**
Expand All @@ -205,7 +210,7 @@ public function issuedAtMustKeepAFluentInterface(): void
{
$builder = $this->createBuilder();

self::assertSame($builder, $builder->issuedAt(2));
self::assertSame($builder, $builder->issuedAt(new DateTimeImmutable()));
}

/**
Expand Down Expand Up @@ -250,11 +255,13 @@ public function issuedByMustKeepAFluentInterface(): void
*/
public function canOnlyBeUsedAfterMustChangeTheNbfClaim(): void
{
$now = new DateTimeImmutable();

$builder = $this->createBuilder();
$builder->canOnlyBeUsedAfter(2);
$builder->canOnlyBeUsedAfter($now);

self::assertAttributeEquals(['alg' => 'none', 'typ' => 'JWT'], 'headers', $builder);
self::assertAttributeEquals([RegisteredClaims::NOT_BEFORE => 2], 'claims', $builder);
self::assertAttributeEquals([RegisteredClaims::NOT_BEFORE => $now], 'claims', $builder);
}

/**
Expand All @@ -269,7 +276,7 @@ public function canOnlyBeUsedAfterMustKeepAFluentInterface(): void
{
$builder = $this->createBuilder();

self::assertSame($builder, $builder->canOnlyBeUsedAfter(2));
self::assertSame($builder, $builder->canOnlyBeUsedAfter(new DateTimeImmutable()));
}

/**
Expand Down Expand Up @@ -390,34 +397,49 @@ public function withHeaderMustKeepAFluentInterface(): void
* @uses \Lcobucci\JWT\Token\Builder::__construct
* @uses \Lcobucci\JWT\Token\Builder::withClaim
* @uses \Lcobucci\JWT\Token\Builder::setClaim
* @uses \Lcobucci\JWT\Token\Builder::issuedAt
* @uses \Lcobucci\JWT\Token\Builder::expiresAt
* @uses \Lcobucci\JWT\Signer\Key
* @uses \Lcobucci\JWT\Token\Plain
* @uses \Lcobucci\JWT\Token\Signature
* @uses \Lcobucci\JWT\Token\DataSet
*
* @covers \Lcobucci\JWT\Token\Builder::getToken
* @covers \Lcobucci\JWT\Token\Builder::encode
* @covers \Lcobucci\JWT\Token\Builder::formatClaims
* @covers \Lcobucci\JWT\Token\Builder::convertDate
*/
public function getTokenMustReturnANewTokenWithCurrentConfiguration(): void
{
$this->signer->method('sign')->willReturn('testing');

$issuedAt = new DateTimeImmutable('@1487285080');
$expiration = DateTimeImmutable::createFromFormat('U.u', '1487285080.123456');
$headers = ['typ' => 'JWT', 'alg' => 'RS256'];
$claims = ['iat' => 1487285080, 'exp' => '1487285080.123456', 'aud' => 'test', 'test' => 123];

$this->encoder->expects($this->exactly(2))
->method('jsonEncode')
->withConsecutive([['typ'=> 'JWT', 'alg' => 'RS256']], [['test' => 123]])
->withConsecutive([self::identicalTo($headers)], [self::identicalTo($claims)])
->willReturnOnConsecutiveCalls('1', '2');

$this->encoder->expects($this->exactly(3))
->method('base64UrlEncode')
->withConsecutive(['1'], ['2'], ['testing'])
->willReturnOnConsecutiveCalls('1', '2', '3');

$builder = $this->createBuilder()->withClaim('test', 123);
$token = $builder->getToken($this->signer, new Key('123'));
$token = $this->createBuilder()
->issuedAt($issuedAt)
->expiresAt($expiration)
->permittedFor('test')
->withClaim('test', 123)
->getToken($this->signer, new Key('123'));

self::assertSame('JWT', $token->headers()->get('typ'));
self::assertSame('RS256', $token->headers()->get('alg'));
self::assertSame(123, $token->claims()->get('test'));
self::assertSame($issuedAt, $token->claims()->get('iat'));
self::assertSame($expiration, $token->claims()->get('exp'));
self::assertNotNull($token->signature());
}
}
Loading