Skip to content

Commit

Permalink
Provide TokenGenerator for Testing
Browse files Browse the repository at this point in the history
  • Loading branch information
deleugpn committed Mar 4, 2022
1 parent 0946c5f commit d8efad3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 17 deletions.
51 changes: 51 additions & 0 deletions src/Testing/TokenGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php declare(strict_types=1);

namespace CustomerGauge\Cognito\Testing;

use Jose\Component\Core\JWKSet;
use Jose\Easy\Build;

final class TokenGenerator
{
private $jwk;

public $jti = 'token-id';

public $algorithm = 'RS256';

public $issuer = 'https://cognito-idp.local.amazonaws.com/phpunit-pool-id';

public $subject = 'testing';

public function __construct(JWKSet $jwk)
{
$this->jwk = $jwk;
}

public static function fromFile(string $path): self
{
$key =file_get_contents($path);

return new self(JWKSet::createFromJson($key));
}

public function sign(array $attributes): string
{
$time = time();

$builder = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti($this->jti, true)
->alg($this->algorithm)
->iss($this->issuer)
->sub($this->subject);

foreach ($attributes as $key => $value) {
$builder->claim($key, $value, true);
}

return $builder->sign($this->jwk->get(0));
}
}
20 changes: 3 additions & 17 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use CustomerGauge\Cognito\Contracts\UserFactory;
use CustomerGauge\Cognito\Issuer;
use CustomerGauge\Cognito\Testing\TokenGenerator;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Repository;
use Illuminate\Container\Container;
Expand Down Expand Up @@ -38,23 +39,8 @@ protected function setUp(): void

protected function jwtToken(array $claims): string
{
$jwk = JWKSet::createFromJson(file_get_contents(__DIR__ . '/Fixtures/jwt.key'));
$generator = TokenGenerator::fromFile(__DIR__ . '/Fixtures/jwt.key');

$time = time();

$builder = Build::jws()
->exp($time + 3600)
->iat($time)
->nbf($time)
->jti('token-id', true)
->alg('RS256')
->iss('https://cognito-idp.local.amazonaws.com/phpunit-pool-id')
->sub('testing');

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

return $builder->sign($jwk->get(0));
return $generator->sign($claims);
}
}

0 comments on commit d8efad3

Please sign in to comment.