diff --git a/CHANGELOG.md b/CHANGELOG.md index ba3f7bb7..f875adf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 You can find and compare releases at the GitHub release page. ## [Unreleased] +- SetSecret regenerates config with new secret in the Lcobucci provider ### Added - Support for lcobucci/jwt^5.0 (and dropped support for ^4.0) diff --git a/src/Providers/JWT/Lcobucci.php b/src/Providers/JWT/Lcobucci.php index 1da2e2a1..4d9b6439 100644 --- a/src/Providers/JWT/Lcobucci.php +++ b/src/Providers/JWT/Lcobucci.php @@ -74,7 +74,18 @@ public function __construct( $config = null ) { parent::__construct($secret, $algo, $keys); + $this->generateConfig($config); + } + /** + * Generate the config. + * + * @param Configuration $config optional, to pass an existing configuration to be used + * + * @return void + */ + private function generateConfig($config = null) + { $this->signer = $this->getSigner(); if (!is_null($config)) { @@ -91,6 +102,21 @@ public function __construct( } } + /** + * Set the secret used to sign the token and regenerate the config using the secret. + * + * @param string $secret + * + * @return $this + */ + public function setSecret($secret) + { + $this->secret = $secret; + $this->generateConfig(); + + return $this; + } + /** * Gets the {@see $config} attribute. * diff --git a/tests/Providers/JWT/LcobucciTest.php b/tests/Providers/JWT/LcobucciTest.php index b960ee92..b4eb69d6 100644 --- a/tests/Providers/JWT/LcobucciTest.php +++ b/tests/Providers/JWT/LcobucciTest.php @@ -189,6 +189,26 @@ public function testItShouldThrowAExceptionWhenTheAlgorithmPassedIsInvalid() $this->getProvider('secret', 'AlgorithmWrong')->decode('foo.bar.baz'); } + public function testItShouldThrowAExceptionWhenTheSecretHasBeenUpdatedAndAnOldTokenIsUsed() + { + $orignal_secret = 'OF8SQY475aF8uiRuWunK9ZO6VdZDBemk'; + $new_secret = 'vsd1z800ApIihL6HVNyhbGLRyBLD74sZ'; + + $payload = ['sub' => '1', 'exp' => $this->testNowTimestamp + 3600, 'iat' => $this->testNowTimestamp, 'iss' => '/foo']; + + $provider = new Lcobucci($orignal_secret, 'HS256', []); + $token = $provider->encode($payload); + + $this->assertSame($payload, $provider->decode($token)); + + $provider->setSecret($new_secret); + + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Token Signature could not be verified.'); + + $provider->decode($token); + } + public function testItShouldReturnThePublicKey() { $provider = $this->getProvider(