From 76be6e683ea58f73d68f10c0a832ae05aa66802f Mon Sep 17 00:00:00 2001 From: Deleu Date: Fri, 4 Mar 2022 14:08:16 +0100 Subject: [PATCH] Provide TokenGenerator for Testing --- src/Testing/TokenGenerator.php | 51 ++++++++++++++++++++++++++++++++++ tests/TestCase.php | 20 ++----------- 2 files changed, 54 insertions(+), 17 deletions(-) create mode 100644 src/Testing/TokenGenerator.php diff --git a/src/Testing/TokenGenerator.php b/src/Testing/TokenGenerator.php new file mode 100644 index 0000000..502d89b --- /dev/null +++ b/src/Testing/TokenGenerator.php @@ -0,0 +1,51 @@ +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)); + } +} \ No newline at end of file diff --git a/tests/TestCase.php b/tests/TestCase.php index c659e06..701837d 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -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; @@ -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); } }