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

feat: 3.x migrate to "lcobucci/jwt" v5 #1157

Open
wants to merge 3 commits into
base: 3.x
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ jobs:
with:
php-version: "${{ matrix.php }}"
tools: "composer:v2,flex"
extensions: sodium

- name: "Set Composer stability"
if: "matrix.symfony == '6.3.*@dev'"
Expand Down
46 changes: 16 additions & 30 deletions Services/JWSProvider/LcobucciJWSProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@

namespace Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProvider;

use Lcobucci\Clock\Clock;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Ecdsa;
use Lcobucci\JWT\Signer\Hmac;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Hmac\Sha384;
Expand All @@ -21,11 +17,13 @@
use Lcobucci\JWT\Token\RegisteredClaims;
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\Constraint\ValidAt;
use Lcobucci\JWT\Validation\ValidAt;
use Lcobucci\JWT\Validation\Validator;
use Lexik\Bundle\JWTAuthenticationBundle\Services\KeyLoader\KeyLoaderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Signature\CreatedJWS;
use Lexik\Bundle\JWTAuthenticationBundle\Signature\LoadedJWS;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\ClockInterface;

/**
* @final
Expand All @@ -36,7 +34,7 @@ class LcobucciJWSProvider implements JWSProviderInterface
{
private KeyLoaderInterface $keyLoader;

private Clock $clock;
private ClockInterface $clock;

private Signer $signer;

Expand All @@ -49,10 +47,10 @@ class LcobucciJWSProvider implements JWSProviderInterface
/**
* @throws \InvalidArgumentException If the given crypto engine is not supported
*/
public function __construct(KeyLoaderInterface $keyLoader, string $signatureAlgorithm, ?int $ttl, ?int $clockSkew, bool $allowNoExpiration = false, Clock $clock = null)
public function __construct(KeyLoaderInterface $keyLoader, string $signatureAlgorithm, ?int $ttl, ?int $clockSkew, bool $allowNoExpiration = false, ClockInterface $clock = null)
Copy link

Choose a reason for hiding this comment

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

You should also update the service definition to inject the clock service defined by FrameworkBundle when it is available (using on-invalid="null" to handle cases where the service is disabled) to use the clock configured in the container.

{
if (null === $clock) {
$clock = SystemClock::fromUTC();
$clock = new Clock();
}

$this->keyLoader = $keyLoader;
Expand All @@ -66,36 +64,32 @@ public function __construct(KeyLoaderInterface $keyLoader, string $signatureAlgo
/**
* {@inheritdoc}
*/
public function create(array $payload, array $header = [])
public function create(array $payload, array $header = []): CreatedJWS
{
if (class_exists(JWTBuilder::class)) {
$jws = new JWTBuilder(new JoseEncoder(), ChainedFormatter::default());
} else {
$jws = new Builder();
}
$jws = new JWTBuilder(new JoseEncoder(), ChainedFormatter::default());

foreach ($header as $k => $v) {
$jws->withHeader($k, $v);
$jws = $jws->withHeader($k, $v);
}

$now = time();
$now = $this->clock->now()->getTimestamp();

$issuedAt = $payload['iat'] ?? $now;
unset($payload['iat']);

$jws->issuedAt(!$issuedAt instanceof \DateTimeImmutable ? new \DateTimeImmutable("@{$issuedAt}") : $issuedAt);
$jws = $jws->issuedAt(!$issuedAt instanceof \DateTimeImmutable ? new \DateTimeImmutable("@{$issuedAt}") : $issuedAt);

if (null !== $this->ttl || isset($payload['exp'])) {
$exp = $payload['exp'] ?? $now + $this->ttl;
unset($payload['exp']);

if ($exp) {
$jws->expiresAt($exp instanceof \DateTimeImmutable ? $exp : (new \DateTimeImmutable("@$exp")));
$jws = $jws->expiresAt($exp instanceof \DateTimeImmutable ? $exp : (new \DateTimeImmutable("@$exp")));
}
}

if (isset($payload['sub'])) {
$jws->relatedTo($payload['sub']);
$jws = $jws->relatedTo($payload['sub']);
unset($payload['sub']);
}

Expand All @@ -104,7 +98,7 @@ public function create(array $payload, array $header = [])
}

foreach ($payload as $name => $value) {
$jws->withClaim($name, $value);
$jws = $jws->withClaim($name, $value);
}

$e = $token = null;
Expand All @@ -119,13 +113,9 @@ public function create(array $payload, array $header = [])
/**
* {@inheritdoc}
*/
public function load($token)
public function load($token): LoadedJWS
{
if (class_exists(JWTParser::class)) {
$jws = (new JWTParser(new JoseEncoder()))->parse($token);
} else {
$jws = (new Parser())->parse($token);
}
$jws = (new JWTParser(new JoseEncoder()))->parse($token);

$payload = [];

Expand Down Expand Up @@ -165,10 +155,6 @@ private function getSignerForAlgorithm($signatureAlgorithm): Signer

$signerClass = $signerMap[$signatureAlgorithm];

if (is_subclass_of($signerClass, Ecdsa::class) && method_exists($signerClass, 'create')) {
return $signerClass::create();
}

return new $signerClass();
}

Expand Down
10 changes: 3 additions & 7 deletions Tests/Functional/GetTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional;

use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Token\Parser as JWTParser;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
Expand Down Expand Up @@ -70,14 +69,11 @@ public function testGetTokenWithCustomClaim()
$this->assertArrayHasKey('custom', $payload, 'The payload should contains a "custom" claim.');
$this->assertSame('dummy', $payload['custom'], 'The "custom" claim should be equal to "dummy".');

if (class_exists(JWTParser::class)) {
$parser = new JWTParser(new JoseEncoder());
} else {
$parser = new Parser();
}
$parser = new JWTParser(new JoseEncoder());

$jws = $parser->parse($token);

$this->assertArrayHasKey('foo', method_exists($jws, 'headers') ? $jws->headers()->all() : $jws->getHeaders(), 'The payload should contains a custom "foo" header.');
$this->assertArrayHasKey('foo', $jws->headers()->all(), 'The payload should contains a custom "foo" header.');
}

public function testGetTokenFromInvalidCredentials()
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"require": {
"php": ">=8.1",
"ext-openssl": "*",
"lcobucci/jwt": "^3.4|^4.0",
"lcobucci/jwt": "^5.0",
"symfony/config": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/deprecation-contracts": "^2.4|^3.0",
Expand All @@ -53,6 +53,7 @@
"require-dev": {
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "^5.4|^6.0",
"symfony/clock": "^6.3",
Copy link

Choose a reason for hiding this comment

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

as you instantiate a Symfony Clock when no clock is provided, this is not really an optional dependency.

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for the feedback.

I am not sure if this should be tied to "symfony/clock" or if it is possible to just add the requirement that it needs a repo that implements "psr/clock" and let the user decide, which one to chose. require psr/clock-implementation?
https://packagist.org/?query=clock

The linked PR from @Dean151 makes the dependency optional.

Copy link

Choose a reason for hiding this comment

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

Well, your implementation is the one making it non-optional.

However, as this package is a Symfony bundle, I would not be too concerned about being bring a dependency on the Symfony component.

"symfony/console": "^5.4|^6.0",
"symfony/dom-crawler": "^5.4|^6.0",
"symfony/filesystem": "^5.4|^6.0",
Expand Down
Loading