From 96ac2470aca895d05d5ca60ea38bfc65fdc95a23 Mon Sep 17 00:00:00 2001 From: Robin Chalas Date: Sat, 19 Dec 2020 22:06:13 +0100 Subject: [PATCH 1/2] Remove support for lcobucci/jwt <3.4 & symfony/* <4.4 --- .github/workflows/ci.yml | 44 +------ DependencyInjection/Configuration.php | 4 +- Event/AuthenticationFailureEvent.php | 1 + Event/AuthenticationSuccessEvent.php | 1 + Event/Event.php | 18 --- Event/JWTAuthenticatedEvent.php | 1 + Event/JWTCreatedEvent.php | 1 + Event/JWTDecodedEvent.php | 4 +- Event/JWTEncodedEvent.php | 16 +-- Exception/InvalidPayloadException.php | 5 +- Exception/JWTFailureException.php | 20 +-- Exception/UserNotFoundException.php | 13 +- Helper/JWTSplitter.php | 13 +- README.md | 2 +- Resources/config/console.xml | 2 +- Response/JWTAuthenticationFailureResponse.php | 12 +- .../Authentication/Provider/JWTProvider.php | 9 +- Security/Firewall/JWTListener.php | 17 +-- Security/Guard/JWTTokenAuthenticator.php | 22 +--- .../AuthenticationFailureHandler.php | 9 +- .../AuthenticationSuccessHandler.php | 10 +- Security/Http/Cookie/JWTCookieProvider.php | 28 +---- Security/User/JWTUser.php | 3 +- Services/JWSProvider/LcobucciJWSProvider.php | 55 ++------ Services/JWTManager.php | 21 +--- Services/KeyLoader/AbstractKeyLoader.php | 18 +-- Signature/CreatedJWS.php | 37 ++---- Signature/LoadedJWS.php | 64 ++-------- .../Command/CheckConfigCommandTest.php | 4 +- .../Firewall/JWTListenerTest.php | 18 +-- .../Guard/JWTTokenAuthenticatorTest.php | 11 +- .../AuthenticationSuccessHandlerTest.php | 26 ++-- .../JWSProvider/AbstractJWSProviderTest.php | 8 -- Tests/Services/JWTManagerTest.php | 118 +++++------------- composer.json | 22 ++-- 35 files changed, 140 insertions(+), 517 deletions(-) delete mode 100644 Event/Event.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 18552167..2ace3ecb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,8 +5,8 @@ on: push: jobs: - php-56: - name: PHP 5.6 / Symfony 3.4 + php-71: + name: PHP 7.1 / Symfony 4.4 runs-on: ubuntu-latest steps: - name: "Checkout" @@ -17,48 +17,14 @@ jobs: - name: "Install PHP" uses: "shivammathur/setup-php@v2" with: - php-version: "5.6" + php-version: "7.1" - name: "Cache composer packages" uses: "actions/cache@v2" with: path: "~/.composer/cache" - key: "php-5.6-composer-locked-${{ hashFiles('composer.lock') }}" - restore-keys: "php-5.6-composer-locked-" - - - name: "Install Symfony 3.4" - run: "composer require symfony/symfony:3.4.* --no-update" - - - name: "Install Symfony PHPUnit Bridge 3.4" - run: "composer require symfony/phpunit-bridge:3.4.* --no-update" - - - name: "Install dependencies with composer" - run: "composer update --no-interaction --prefer-dist --prefer-stable" - - - name: "Run PHPUnit Tests" - env: - SYMFONY_PHPUNIT_VERSION: 5.7 - run: "composer test" - php-72: - name: PHP 7.2 / Symfony 4.4 - runs-on: ubuntu-latest - steps: - - name: "Checkout" - uses: "actions/checkout@v2" - with: - fetch-depth: 2 - - - name: "Install PHP" - uses: "shivammathur/setup-php@v2" - with: - php-version: "7.2" - - - name: "Cache composer packages" - uses: "actions/cache@v2" - with: - path: "~/.composer/cache" - key: "php-7.2-composer-locked-${{ hashFiles('composer.lock') }}" - restore-keys: "php-7.2-composer-locked-" + key: "php-7.1-composer-locked-${{ hashFiles('composer.lock') }}" + restore-keys: "php-7.1-composer-locked-" - name: "Install Symfony 4.4" run: "composer require symfony/symfony:4.4.* --no-update" diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 4096f851..25cd5966 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -20,9 +20,9 @@ class Configuration implements ConfigurationInterface public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('lexik_jwt_authentication'); - $rootNode = \method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('lexik_jwt_authentication'); - $rootNode + $treeBuilder + ->getRootNode() ->addDefaultsIfNotSet() ->children() ->scalarNode('private_key_path') diff --git a/Event/AuthenticationFailureEvent.php b/Event/AuthenticationFailureEvent.php index fdf96a46..324aa5d5 100644 --- a/Event/AuthenticationFailureEvent.php +++ b/Event/AuthenticationFailureEvent.php @@ -4,6 +4,7 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Symfony\Contracts\EventDispatcher\Event; /** * AuthenticationFailureEvent. diff --git a/Event/AuthenticationSuccessEvent.php b/Event/AuthenticationSuccessEvent.php index 5fb17a64..b8807020 100644 --- a/Event/AuthenticationSuccessEvent.php +++ b/Event/AuthenticationSuccessEvent.php @@ -4,6 +4,7 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Contracts\EventDispatcher\Event; /** * AuthenticationSuccessEvent. diff --git a/Event/Event.php b/Event/Event.php deleted file mode 100644 index c53fc123..00000000 --- a/Event/Event.php +++ /dev/null @@ -1,18 +0,0 @@ -jwtString = $jwtString; } - /** - * @return string - */ public function getJWTString() { return $this->jwtString; diff --git a/Exception/InvalidPayloadException.php b/Exception/InvalidPayloadException.php index 6293131f..c1db351d 100644 --- a/Exception/InvalidPayloadException.php +++ b/Exception/InvalidPayloadException.php @@ -11,15 +11,12 @@ */ class InvalidPayloadException extends AuthenticationException { - /** - * @var string - */ private $invalidKey; /** * @param string $invalidKey The key that cannot be found in the payload */ - public function __construct($invalidKey) + public function __construct(string $invalidKey) { $this->invalidKey = $invalidKey; } diff --git a/Exception/JWTFailureException.php b/Exception/JWTFailureException.php index c6ba4b0d..851944bb 100644 --- a/Exception/JWTFailureException.php +++ b/Exception/JWTFailureException.php @@ -9,22 +9,10 @@ */ class JWTFailureException extends \Exception { - /** - * @var string - */ private $reason; - - /** - * @var array|null - */ private $payload; - /** - * @param string $reason - * @param string $message - * @param \Exception|null $previous - */ - public function __construct($reason, $message, \Exception $previous = null, array $payload = null) + public function __construct(string $reason, string $message, \Throwable $previous = null, array $payload = null) { $this->reason = $reason; $this->payload = $payload; @@ -32,17 +20,11 @@ public function __construct($reason, $message, \Exception $previous = null, arra parent::__construct($message, 0, $previous); } - /** - * @return string - */ public function getReason() { return $this->reason; } - /** - * @return array|null - */ public function getPayload() { return $this->payload; diff --git a/Exception/UserNotFoundException.php b/Exception/UserNotFoundException.php index d42f5cfa..e98f50f3 100644 --- a/Exception/UserNotFoundException.php +++ b/Exception/UserNotFoundException.php @@ -11,21 +11,10 @@ */ class UserNotFoundException extends AuthenticationException { - /** - * @var string - */ private $userIdentityField; - - /** - * @var string - */ private $identity; - /** - * @param string $userIdentityField - * @param string $identity - */ - public function __construct($userIdentityField, $identity) + public function __construct(string $userIdentityField, string $identity) { $this->userIdentityField = $userIdentityField; $this->identity = $identity; diff --git a/Helper/JWTSplitter.php b/Helper/JWTSplitter.php index cd0be48a..5016e300 100644 --- a/Helper/JWTSplitter.php +++ b/Helper/JWTSplitter.php @@ -6,6 +6,8 @@ * JWTSplitter. * * @author Adam Lukacovic + * + * @final */ class JWTSplitter { @@ -24,12 +26,9 @@ class JWTSplitter */ private $signature; - /** - * @param string $jwt - */ - public function __construct($jwt) + public function __construct(string $jwt) { - list($this->header, $this->payload, $this->signature) = explode('.', $jwt); + [$this->header, $this->payload, $this->signature] = explode('.', $jwt); } /** @@ -38,8 +37,8 @@ public function __construct($jwt) */ public function getParts($parts = []) { - if (empty($parts)) { - return implode('.', get_object_vars($this)); + if (!$parts) { + return "$this->header.$this->payload.$this->signature"; } return implode('.', array_intersect_key(get_object_vars($this), array_flip($parts))); diff --git a/README.md b/README.md index 704de937..3cf55851 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ LexikJWTAuthenticationBundle This bundle provides JWT (Json Web Token) authentication for your Symfony API. -It is compatible and tested with PHP 5.6, 7.3, 7.4, 8.0 on Symfony 3.4, 4.x and 5.x. +It is compatible and tested with PHP 7.1+ on Symfony 3.4, 4.x and 5.x. Documentation ------------- diff --git a/Resources/config/console.xml b/Resources/config/console.xml index 083b263d..f81e6e4e 100644 --- a/Resources/config/console.xml +++ b/Resources/config/console.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - + %lexik_jwt_authentication.encoder.signature_algorithm% diff --git a/Response/JWTAuthenticationFailureResponse.php b/Response/JWTAuthenticationFailureResponse.php index 203192c8..d7817020 100644 --- a/Response/JWTAuthenticationFailureResponse.php +++ b/Response/JWTAuthenticationFailureResponse.php @@ -13,17 +13,7 @@ */ final class JWTAuthenticationFailureResponse extends JsonResponse { - /** - * The response message. - * - * @var string - */ - private $message; - - /** - * @param string $message A failure message passed in the response body - */ - public function __construct($message = 'Bad credentials', $statusCode = JsonResponse::HTTP_UNAUTHORIZED) + public function __construct(string $message = 'Bad credentials', string $statusCode = JsonResponse::HTTP_UNAUTHORIZED) { $this->message = $message; diff --git a/Security/Authentication/Provider/JWTProvider.php b/Security/Authentication/Provider/JWTProvider.php index 5c52a8c0..c64a71fb 100644 --- a/Security/Authentication/Provider/JWTProvider.php +++ b/Security/Authentication/Provider/JWTProvider.php @@ -8,8 +8,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTManagerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -91,11 +90,7 @@ public function authenticate(TokenInterface $token) $authToken->setRawToken($token->getCredentials()); $event = new JWTAuthenticatedEvent($payload, $authToken); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, Events::JWT_AUTHENTICATED); - } else { - $this->dispatcher->dispatch(Events::JWT_AUTHENTICATED, $event); - } + $this->dispatcher->dispatch($event, Events::JWT_AUTHENTICATED); return $authToken; } diff --git a/Security/Firewall/JWTListener.php b/Security/Firewall/JWTListener.php index 3732fad5..127a35a9 100644 --- a/Security/Firewall/JWTListener.php +++ b/Security/Firewall/JWTListener.php @@ -9,9 +9,8 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; @@ -82,12 +81,7 @@ public function __invoke($event) if (null === $requestToken) { $jwtNotFoundEvent = new JWTNotFoundEvent(); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($jwtNotFoundEvent, Events::JWT_NOT_FOUND); - } else { - $this->dispatcher->dispatch(Events::JWT_NOT_FOUND, $jwtNotFoundEvent); - } - + $this->dispatcher->dispatch($jwtNotFoundEvent, Events::JWT_NOT_FOUND); if ($response = $jwtNotFoundEvent->getResponse()) { $event->setResponse($response); @@ -112,12 +106,7 @@ public function __invoke($event) $response = new JWTAuthenticationFailureResponse($failed->getMessage()); $jwtInvalidEvent = new JWTInvalidEvent($failed, $response); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($jwtInvalidEvent, Events::JWT_INVALID); - } else { - $this->dispatcher->dispatch(Events::JWT_INVALID, $jwtInvalidEvent); - } - + $this->dispatcher->dispatch($jwtInvalidEvent, Events::JWT_INVALID); $event->setResponse($jwtInvalidEvent->getResponse()); } diff --git a/Security/Guard/JWTTokenAuthenticator.php b/Security/Guard/JWTTokenAuthenticator.php index 6191ec18..0ec4c080 100644 --- a/Security/Guard/JWTTokenAuthenticator.php +++ b/Security/Guard/JWTTokenAuthenticator.php @@ -20,8 +20,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\User\PayloadAwareUserProviderInterface; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; @@ -184,11 +183,8 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio $eventName = Events::JWT_INVALID; } - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, $eventName); - } else { - $this->dispatcher->dispatch($eventName, $event); - } + + $this->dispatcher->dispatch($event, $eventName); return $event->getResponse(); } @@ -211,11 +207,7 @@ public function start(Request $request, AuthenticationException $authException = $exception = new MissingTokenException('JWT Token not found', 0, $authException); $event = new JWTNotFoundEvent($exception, new JWTAuthenticationFailureResponse($exception->getMessageKey())); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, Events::JWT_NOT_FOUND); - } else { - $this->dispatcher->dispatch(Events::JWT_NOT_FOUND, $event); - } + $this->dispatcher->dispatch($event, Events::JWT_NOT_FOUND); return $event->getResponse(); } @@ -243,11 +235,7 @@ public function createAuthenticatedToken(UserInterface $user, $providerKey) $authToken = new JWTUserToken($user->getRoles(), $user, $preAuthToken->getCredentials(), $providerKey); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch(new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken), Events::JWT_AUTHENTICATED); - } else { - $this->dispatcher->dispatch(Events::JWT_AUTHENTICATED, new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken)); - } + $this->dispatcher->dispatch(new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken), Events::JWT_AUTHENTICATED); $this->preAuthenticationTokenStorage->setToken(null); diff --git a/Security/Http/Authentication/AuthenticationFailureHandler.php b/Security/Http/Authentication/AuthenticationFailureHandler.php index 3e51134c..09cc9680 100644 --- a/Security/Http/Authentication/AuthenticationFailureHandler.php +++ b/Security/Http/Authentication/AuthenticationFailureHandler.php @@ -5,8 +5,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; @@ -41,11 +40,7 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio new JWTAuthenticationFailureResponse($exception->getMessageKey()) ); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, Events::AUTHENTICATION_FAILURE); - } else { - $this->dispatcher->dispatch(Events::AUTHENTICATION_FAILURE, $event); - } + $this->dispatcher->dispatch($event, Events::AUTHENTICATION_FAILURE); return $event->getResponse(); } diff --git a/Security/Http/Authentication/AuthenticationSuccessHandler.php b/Security/Http/Authentication/AuthenticationSuccessHandler.php index 8d170a8d..a088e739 100644 --- a/Security/Http/Authentication/AuthenticationSuccessHandler.php +++ b/Security/Http/Authentication/AuthenticationSuccessHandler.php @@ -7,8 +7,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse; use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Cookie\JWTCookieProvider; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; @@ -61,12 +60,7 @@ public function handleAuthenticationSuccess(UserInterface $user, $jwt = null) $response = new JWTAuthenticationSuccessResponse($jwt, [], $jwtCookies); $event = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, Events::AUTHENTICATION_SUCCESS); - } else { - $this->dispatcher->dispatch(Events::AUTHENTICATION_SUCCESS, $event); - } - + $this->dispatcher->dispatch($event, Events::AUTHENTICATION_SUCCESS); $responseData = $event->getData(); if ($jwtCookies) { diff --git a/Security/Http/Cookie/JWTCookieProvider.php b/Security/Http/Cookie/JWTCookieProvider.php index 0358f6e7..5343eded 100644 --- a/Security/Http/Cookie/JWTCookieProvider.php +++ b/Security/Http/Cookie/JWTCookieProvider.php @@ -19,17 +19,7 @@ final class JWTCookieProvider private $defaultHttpOnly; private $defaultSplit; - /** - * @param string|null $defaultName - * @param int|null $defaultLifetime - * @param string $defaultPath - * @param string|null $defaultDomain - * @param string $defaultSameSite - * @param bool $defaultSecure - * @param bool $defaultHttpOnly - * @param array $defaultSplit - */ - public function __construct($defaultName = null, $defaultLifetime = 0, $defaultSameSite = Cookie::SAMESITE_LAX, $defaultPath = '/', $defaultDomain = null, $defaultSecure = true, $defaultHttpOnly = true, $defaultSplit = []) + public function __construct(?string $defaultName = null, ?int $defaultLifetime = 0, ?string $defaultSameSite = Cookie::SAMESITE_LAX, ?string $defaultPath = '/', ?string $defaultDomain = null, bool $defaultSecure = true, bool $defaultHttpOnly = true, array $defaultSplit = []) { $this->defaultName = $defaultName; $this->defaultLifetime = $defaultLifetime; @@ -44,22 +34,10 @@ public function __construct($defaultName = null, $defaultLifetime = 0, $defaultS /** * Creates a secure cookie containing the passed JWT. * - * For each argument (all args except $jwt), if it is omitted or set to null then the + * For each argument (all args except $jwt), if omitted or set to null then the * default value defined via the constructor will be used. - * - * @param string $jwt - * @param string|null $name - * @param int|string|\DateTimeInterface|null $expiresAt - * @param string|null $sameSite - * @param string|null $path - * @param string|null $domain - * @param bool|null $secure - * @param bool|null $httpOnly - * @param array $split - * - * @return Cookie */ - public function createCookie($jwt, $name = null, $expiresAt = null, $sameSite = null, $path = null, $domain = null, $secure = null, $httpOnly = null, $split = []) + public function createCookie(string $jwt, ?string $name = null, $expiresAt = null, ?string $sameSite = null, ?string $path = null, ?string $domain = null, ?bool $secure = null, ?bool $httpOnly = null, array $split = []): Cookie { if (!$name && !$this->defaultName) { throw new \LogicException(sprintf('The cookie name must be provided, either pass it as 2nd argument of %s or set a default name via the constructor.', __METHOD__)); diff --git a/Security/User/JWTUser.php b/Security/User/JWTUser.php index 8cfb8f88..da802a96 100644 --- a/Security/User/JWTUser.php +++ b/Security/User/JWTUser.php @@ -12,10 +12,9 @@ class JWTUser implements JWTUserInterface { private $username; - private $roles; - public function __construct($username, array $roles = []) + public function __construct(string $username, array $roles = []) { $this->username = $username; $this->roles = $roles; diff --git a/Services/JWSProvider/LcobucciJWSProvider.php b/Services/JWSProvider/LcobucciJWSProvider.php index c9b51f0d..a3908519 100644 --- a/Services/JWSProvider/LcobucciJWSProvider.php +++ b/Services/JWSProvider/LcobucciJWSProvider.php @@ -7,7 +7,6 @@ use Lcobucci\JWT\Encoding\JoseEncoder; use Lcobucci\JWT\Encoding\MicrosecondBasedDateConversion; use Lcobucci\JWT\Parser; -use Lcobucci\JWT\Signer\OpenSSL; use Lcobucci\JWT\Token\Parser as JWTParser; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer\Hmac; @@ -44,35 +43,24 @@ class LcobucciJWSProvider implements JWSProviderInterface private $signer; /** - * @var int + * @var int|null */ private $ttl; /** - * @var int + * @var int|null */ private $clockSkew; - /** - * @var bool - */ - private $legacyJWTApi; - /** * @var bool */ private $useDateObjects; /** - * @param KeyLoaderInterface $keyLoader - * @param string $cryptoEngine - * @param string $signatureAlgorithm - * @param int|null $ttl - * @param int $clockSkew - * * @throws \InvalidArgumentException If the given crypto engine is not supported */ - public function __construct(KeyLoaderInterface $keyLoader, $cryptoEngine, $signatureAlgorithm, $ttl, $clockSkew) + public function __construct(KeyLoaderInterface $keyLoader, string $cryptoEngine, string $signatureAlgorithm, ?int $ttl, ?int $clockSkew) { if ('openssl' !== $cryptoEngine) { throw new \InvalidArgumentException(sprintf('The %s provider supports only "openssl" as crypto engine.', __CLASS__)); @@ -90,7 +78,6 @@ public function __construct(KeyLoaderInterface $keyLoader, $cryptoEngine, $signa $this->signer = $this->getSignerForAlgorithm($signatureAlgorithm); $this->ttl = $ttl; $this->clockSkew = $clockSkew; - $this->legacyJWTApi = !class_exists(OpenSSL::class); // exists only on lcobucci/jwt 3.3+ $this->useDateObjects = method_exists(Token::class, 'payload') || class_exists(Plain::class); // exists only on lcobucci/jwt 3.4+ } @@ -106,30 +93,21 @@ public function create(array $payload, array $header = []) } foreach ($header as $k => $v) { - $jws->{$this->legacyJWTApi ? 'setHeader' : 'withHeader'}($k, $v); + $jws->withHeader($k, $v); } $now = time(); - - if ($this->legacyJWTApi) { - $jws->setIssuedAt($now); - } else { - $jws->issuedAt($this->useDateObjects ? new \DateTimeImmutable("@{$now}") : $now); - } + $jws->issuedAt($this->useDateObjects ? new \DateTimeImmutable("@{$now}") : $now); if (null !== $this->ttl || isset($payload['exp'])) { $exp = isset($payload['exp']) ? $payload['exp'] : $now + $this->ttl; unset($payload['exp']); - if ($this->legacyJWTApi) { - $jws->setExpiration($exp); - } else { - $jws->expiresAt($exp instanceof \DateTimeImmutable ? $exp : ($this->useDateObjects ? new \DateTimeImmutable("@$exp") : $exp)); - } + $jws->expiresAt($exp instanceof \DateTimeImmutable ? $exp : ($this->useDateObjects ? new \DateTimeImmutable("@$exp") : $exp)); } if (isset($payload['sub'])) { - $jws->{$this->legacyJWTApi ? 'setSubject' : 'relatedTo'}($payload['sub']); + $jws->relatedTo($payload['sub']); unset($payload['sub']); } @@ -138,15 +116,10 @@ public function create(array $payload, array $header = []) } foreach ($payload as $name => $value) { - if ($this->legacyJWTApi) { - $jws->set($name, $value); - } else { - $jws->{method_exists($jws,'with') ? 'with' : 'withClaim'}($name, $value); - } + $jws->withClaim($name, $value); } $e = $token = null; - try { $token = $this->getSignedToken($jws); } catch (\InvalidArgumentException $e) { @@ -168,7 +141,7 @@ public function load($token) $payload = []; - if ($this->legacyJWTApi || !$this->useDateObjects) { + if (!$this->useDateObjects) { foreach ($jws->getClaims() as $claim) { $payload[$claim->getName()] = $claim->getValue(); } @@ -185,7 +158,7 @@ public function load($token) $payload, $this->verify($jws), null !== $this->ttl, - $this->legacyJWTApi || !$this->useDateObjects ? $jws->getHeaders() : $jws->headers()->all(), + $this->useDateObjects ? $jws->headers()->all() : $jws->getHeaders(), $this->clockSkew ); @@ -225,12 +198,6 @@ private function getSignedToken(Builder $jws) $key = new Key($this->keyLoader->loadKey(RawKeyLoader::TYPE_PRIVATE), $this->signer instanceof Hmac ? '' : $this->keyLoader->getPassphrase()); } - if ($this->legacyJWTApi) { - $jws->sign($this->signer, $key); - - return $jws->getToken(); - } - $token = $jws->getToken($this->signer, $key); if (!$token instanceof Plain) { @@ -242,7 +209,7 @@ private function getSignedToken(Builder $jws) private function verify(Token $jwt) { - if ($this->legacyJWTApi || !$this->useDateObjects) { + if (!$this->useDateObjects) { if (!$jwt->validate(new ValidationData(time() + $this->clockSkew))) { return false; } diff --git a/Services/JWTManager.php b/Services/JWTManager.php index a57fc940..c5a58dc1 100644 --- a/Services/JWTManager.php +++ b/Services/JWTManager.php @@ -8,8 +8,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent; use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTEncodedEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; @@ -92,11 +91,7 @@ public function createFromPayload(UserInterface $user, array $payload) private function generateJwtStringAndDispatchEvents(UserInterface $user, array $payload) { $jwtCreatedEvent = new JWTCreatedEvent($payload, $user); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($jwtCreatedEvent, Events::JWT_CREATED); - } else { - $this->dispatcher->dispatch(Events::JWT_CREATED, $jwtCreatedEvent); - } + $this->dispatcher->dispatch($jwtCreatedEvent, Events::JWT_CREATED); if ($this->jwtEncoder instanceof HeaderAwareJWTEncoderInterface) { $jwtString = $this->jwtEncoder->encode($jwtCreatedEvent->getData(), $jwtCreatedEvent->getHeader()); @@ -106,11 +101,7 @@ private function generateJwtStringAndDispatchEvents(UserInterface $user, array $ $jwtEncodedEvent = new JWTEncodedEvent($jwtString); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($jwtEncodedEvent, Events::JWT_ENCODED); - } else { - $this->dispatcher->dispatch(Events::JWT_ENCODED, $jwtEncodedEvent); - } + $this->dispatcher->dispatch($jwtEncodedEvent, Events::JWT_ENCODED); return $jwtString; } @@ -125,11 +116,7 @@ public function decode(TokenInterface $token) } $event = new JWTDecodedEvent($payload); - if ($this->dispatcher instanceof ContractsEventDispatcherInterface) { - $this->dispatcher->dispatch($event, Events::JWT_DECODED); - } else { - $this->dispatcher->dispatch(Events::JWT_DECODED, $event); - } + $this->dispatcher->dispatch($event, Events::JWT_DECODED); if (!$event->isValid()) { return false; diff --git a/Services/KeyLoader/AbstractKeyLoader.php b/Services/KeyLoader/AbstractKeyLoader.php index 923da926..9c5b12c7 100644 --- a/Services/KeyLoader/AbstractKeyLoader.php +++ b/Services/KeyLoader/AbstractKeyLoader.php @@ -11,27 +11,11 @@ */ abstract class AbstractKeyLoader implements KeyLoaderInterface { - /** - * @var string - */ private $signingKey; - - /** - * @var string|null - */ private $publicKey; - - /** - * @var string|null - */ private $passphrase; - /** - * @param string|null $signingKey - * @param string|null $publicKey - * @param string|null $passphrase - */ - public function __construct($signingKey = null, $publicKey = null, $passphrase = null) + public function __construct(?string $signingKey = null, ?string $publicKey = null, ?string $passphrase = null) { $this->signingKey = $signingKey; $this->publicKey = $publicKey; diff --git a/Signature/CreatedJWS.php b/Signature/CreatedJWS.php index 7ddaaf7e..9a33bc87 100644 --- a/Signature/CreatedJWS.php +++ b/Signature/CreatedJWS.php @@ -9,45 +9,26 @@ */ final class CreatedJWS { - const SIGNED = 'signed'; - /** - * The JSON Web Token. - * - * @var string + * @deprecated since v2.11 */ - private $token; + const SIGNED = 'signed'; - /** - * @var string - */ - private $state; + private $token; + private $signed; - /** - * @param string $token - * @param bool $isSigned - */ - public function __construct($token, $isSigned) + public function __construct(string $token, bool $isSigned) { $this->token = $token; - - if (true === $isSigned) { - $this->state = self::SIGNED; - } + $this->signed = $isSigned; } - /** - * @return bool - */ - public function isSigned() + public function isSigned(): bool { - return self::SIGNED === $this->state; + return $this->signed; } - /** - * @return string - */ - public function getToken() + public function getToken(): string { return $this->token; } diff --git a/Signature/LoadedJWS.php b/Signature/LoadedJWS.php index 37c1e131..f77a2bc7 100644 --- a/Signature/LoadedJWS.php +++ b/Signature/LoadedJWS.php @@ -11,44 +11,16 @@ final class LoadedJWS { const VERIFIED = 'verified'; - const EXPIRED = 'expired'; - const INVALID = 'invalid'; - /** - * @var array - */ private $header; - - /** - * @var array - */ private $payload; - - /** - * @var string - */ private $state; - - /** - * @var int - */ private $clockSkew; - - /** - * @var bool - */ private $hasLifetime; - /** - * @param array $payload - * @param bool $isVerified - * @param bool $hasLifetime - * @param int $clockSkew - * @param array $header - */ - public function __construct(array $payload, $isVerified, $hasLifetime = true, array $header = [], $clockSkew = 0) + public function __construct(array $payload, bool $isVerified, bool $hasLifetime = true, array $header = [], int $clockSkew = 0) { $this->payload = $payload; $this->header = $header; @@ -63,59 +35,43 @@ public function __construct(array $payload, $isVerified, $hasLifetime = true, ar $this->checkExpiration(); } - /** - * @return array - */ - public function getHeader() + public function getHeader(): array { return $this->header; } - /** - * @return array - */ - public function getPayload() + public function getPayload(): array { return $this->payload; } - /** - * @return bool - */ - public function isVerified() + public function isVerified(): bool { return self::VERIFIED === $this->state; } - /** - * @return bool - */ - public function isExpired() + public function isExpired(): bool { $this->checkExpiration(); return self::EXPIRED === $this->state; } - /** - * @return bool - */ - public function isInvalid() + public function isInvalid(): bool { return self::INVALID === $this->state; } - /** - * Ensures that the signature is not expired. - */ - private function checkExpiration() + private function checkExpiration(): void { if (!$this->hasLifetime) { return; } if (!isset($this->payload['exp']) || !is_numeric($this->payload['exp'])) { - return $this->state = self::INVALID; + $this->state = self::INVALID; + + return; } if ($this->clockSkew <= time() - $this->payload['exp']) { diff --git a/Tests/Functional/Command/CheckConfigCommandTest.php b/Tests/Functional/Command/CheckConfigCommandTest.php index 8cda3e06..68cc7955 100644 --- a/Tests/Functional/Command/CheckConfigCommandTest.php +++ b/Tests/Functional/Command/CheckConfigCommandTest.php @@ -3,6 +3,7 @@ namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional\Command; use Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional\TestCase; +use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; /** @@ -18,7 +19,8 @@ class CheckConfigCommandTest extends TestCase public function testCheckOpenSSLCommand() { $kernel = $this->bootKernel(); - $tester = new CommandTester($kernel->getContainer()->get('lexik_jwt_authentication.check_config_command')); + $app = new Application($kernel); + $tester = new CommandTester($app->find('lexik:jwt:check-config')); $this->assertSame(0, $tester->execute([])); $this->{method_exists($this, 'assertStringContainsString') ? 'assertStringContainsString' : 'assertContains'}('The configuration seems correct.', $tester->getDisplay()); diff --git a/Tests/Security/Authentication/Firewall/JWTListenerTest.php b/Tests/Security/Authentication/Firewall/JWTListenerTest.php index 3a69fb63..f502b847 100644 --- a/Tests/Security/Authentication/Firewall/JWTListenerTest.php +++ b/Tests/Security/Authentication/Firewall/JWTListenerTest.php @@ -9,7 +9,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\Firewall\JWTListener; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Http\Firewall\ListenerInterface; /** @@ -98,14 +98,8 @@ public function getAuthenticationManagerMock() */ public function getTokenStorageMock() { - if (interface_exists('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')) { - $class = 'Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface'; - } else { - $class = 'Symfony\Component\Security\Core\SecurityContext'; - } - return $this - ->getMockBuilder($class) + ->getMockBuilder(TokenStorageInterface::class) ->disableOriginalConstructor() ->getMock(); } @@ -165,12 +159,6 @@ protected function getEventDispatcherMock() private function expectEvent($eventName, $eventType, $dispatcher) { - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher->expects($this->once())->method('dispatch')->with($this->isInstanceOf($eventType), $eventName); - - return; - } - - $dispatcher->expects($this->once())->method('dispatch')->with($eventName, $this->isInstanceOf($eventType)); + $dispatcher->expects($this->once())->method('dispatch')->with($this->isInstanceOf($eventType), $eventName); } } diff --git a/Tests/Security/Guard/JWTTokenAuthenticatorTest.php b/Tests/Security/Guard/JWTTokenAuthenticatorTest.php index afff8446..8410e315 100644 --- a/Tests/Security/Guard/JWTTokenAuthenticatorTest.php +++ b/Tests/Security/Guard/JWTTokenAuthenticatorTest.php @@ -20,10 +20,9 @@ use Lexik\Bundle\JWTAuthenticationBundle\Tests\Stubs\User as AdvancedUserStub; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; use PHPUnit\Framework\TestCase; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\UserProviderInterface; @@ -386,12 +385,6 @@ private function getTokenStorageMock() private function expectEvent($eventName, $event, $dispatcher) { - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher->expects($this->once())->method('dispatch')->with($event, $eventName); - - return; - } - - $dispatcher->expects($this->once())->method('dispatch')->with($eventName, $event); + $dispatcher->expects($this->once())->method('dispatch')->with($event, $eventName); } } diff --git a/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php b/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php index 593e6479..76116ea7 100644 --- a/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php +++ b/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php @@ -8,8 +8,6 @@ use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTManager; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\HttpFoundation\ResponseHeaderBag; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface; use Symfony\Component\HttpFoundation\JsonResponse; /** @@ -174,23 +172,13 @@ private function getDispatcher() ->disableOriginalConstructor() ->getMock(); - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher - ->expects($this->once()) - ->method('dispatch') - ->with( - $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent'), - $this->equalTo(Events::AUTHENTICATION_SUCCESS) - ); - } else { - $dispatcher - ->expects($this->once()) - ->method('dispatch') - ->with( - $this->equalTo(Events::AUTHENTICATION_SUCCESS), - $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent') - ); - } + $dispatcher + ->expects($this->once()) + ->method('dispatch') + ->with( + $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent'), + $this->equalTo(Events::AUTHENTICATION_SUCCESS) + ); return $dispatcher; } diff --git a/Tests/Services/JWSProvider/AbstractJWSProviderTest.php b/Tests/Services/JWSProvider/AbstractJWSProviderTest.php index 7f4e0ba5..08aba1c3 100644 --- a/Tests/Services/JWSProvider/AbstractJWSProviderTest.php +++ b/Tests/Services/JWSProvider/AbstractJWSProviderTest.php @@ -153,14 +153,6 @@ public function testInvalidsignatureAlgorithm() new static::$providerClass($this->getKeyLoaderMock(), 'openssl', 'wrongAlgorithm', 3600, 0); } - public function testInvalidTtl() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The TTL should be a numeric value'); - - new static::$providerClass($this->getKeyLoaderMock(), 'openssl', 'wrongAlgorithm', 'invalid_ttl', 0); - } - public function testCreateWithExtraStandardClaims() { $keyLoaderMock = $this->getKeyLoaderMock(); diff --git a/Tests/Services/JWTManagerTest.php b/Tests/Services/JWTManagerTest.php index d2b3176f..0092aeaf 100644 --- a/Tests/Services/JWTManagerTest.php +++ b/Tests/Services/JWTManagerTest.php @@ -1,6 +1,6 @@ getEventDispatcherMock(); - - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], - [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] - ); - } else { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->equalTo(Events::JWT_CREATED), $this->isInstanceOf(JWTCreatedEvent::class)], - [$this->equalTo(Events::JWT_ENCODED), $this->isInstanceOf(JWTEncodedEvent::class)] - ); - } + $dispatcher + ->expects($this->exactly(2)) + ->method('dispatch') + ->withConsecutive( + [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], + [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] + ); $encoder = $this->getJWTEncoderMock(); $encoder @@ -62,23 +51,13 @@ public function testCreateFromPayload() { $dispatcher = $this->getEventDispatcherMock(); - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], - [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] - ); - } else { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->equalTo(Events::JWT_CREATED), $this->isInstanceOf(JWTCreatedEvent::class)], - [$this->equalTo(Events::JWT_ENCODED), $this->isInstanceOf(JWTEncodedEvent::class)] - ); - } + $dispatcher + ->expects($this->exactly(2)) + ->method('dispatch') + ->withConsecutive( + [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], + [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] + ); $encoder = $this->getJWTEncoderMock(); $encoder @@ -97,24 +76,13 @@ public function testCreateFromPayload() public function testDecode() { $dispatcher = $this->getEventDispatcherMock(); - - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher - ->expects($this->once()) - ->method('dispatch') - ->with( - $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent'), - $this->equalTo(Events::JWT_DECODED) - ); - } else { - $dispatcher - ->expects($this->once()) - ->method('dispatch') - ->with( - $this->equalTo(Events::JWT_DECODED), - $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent') - ); - } + $dispatcher + ->expects($this->once()) + ->method('dispatch') + ->with( + $this->isInstanceOf('Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent'), + $this->equalTo(Events::JWT_DECODED) + ); $encoder = $this->getJWTEncoderMock(); $encoder @@ -132,24 +100,13 @@ public function testDecode() public function testIdentityField() { $dispatcher = $this->getEventDispatcherMock(); - - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], - [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] - ); - } else { - $dispatcher - ->expects($this->exactly(2)) - ->method('dispatch') - ->withConsecutive( - [$this->equalTo(Events::JWT_CREATED), $this->isInstanceOf(JWTCreatedEvent::class)], - [$this->equalTo(Events::JWT_ENCODED), $this->isInstanceOf(JWTEncodedEvent::class)] - ); - } + $dispatcher + ->expects($this->exactly(2)) + ->method('dispatch') + ->withConsecutive( + [$this->isInstanceOf(JWTCreatedEvent::class), $this->equalTo(Events::JWT_CREATED)], + [$this->isInstanceOf(JWTEncodedEvent::class), $this->equalTo(Events::JWT_ENCODED)] + ); $encoder = $this->getJWTEncoderMock(); $encoder @@ -197,19 +154,8 @@ protected function getJWTEncoderMock() protected function getEventDispatcherMock() { return $this - ->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface') + ->getMockBuilder(EventDispatcherInterface::class) ->disableOriginalConstructor() ->getMock(); } - - private function expectEvent($eventName, $eventClass, $dispatcher) - { - if ($dispatcher instanceof ContractsEventDispatcherInterface) { - $dispatcher->expects($this->once())->method('dispatch')->with($event, $eventName); - - return; - } - - $dispatcher->expects($this->once())->method('dispatch')->with($eventName, $this->isInstanceOf($eventClass)); - } } diff --git a/composer.json b/composer.json index 55fe8165..a70f8049 100644 --- a/composer.json +++ b/composer.json @@ -37,20 +37,20 @@ } ], "require": { - "php": ">=5.6", + "php": ">=7.1", "ext-openssl": "*", - "lcobucci/jwt": "^3.2|^4.0", - "namshi/jose": "^7.2", - "symfony/framework-bundle": "^3.4|^4.0|^5.0", - "symfony/security-bundle": "^3.4|^4.0|^5.0" + "lcobucci/jwt": "^3.4|^4.0", + "symfony/framework-bundle": "^4.4|^5.1", + "symfony/security-bundle": "^4.4|^5.1" }, "require-dev": { - "symfony/browser-kit": "^3.4|^4.0|^5.0", - "symfony/console": "^3.4|^4.0|^5.0", - "symfony/dom-crawler": "^3.4|^4.0|^5.0", - "symfony/phpunit-bridge": "^3.4|^4.0|^5.0", - "symfony/var-dumper": "^3.4|^4.0|^5.0", - "symfony/yaml": "^3.4|^4.0|^5.0" + "namshi/jose": "^7.2", + "symfony/browser-kit": "^4.4|^5.1", + "symfony/console": "^4.4|^5.1", + "symfony/dom-crawler": "^4.4|^5.1", + "symfony/phpunit-bridge": "^4.4|^5.1", + "symfony/var-dumper": "^4.4|^5.1", + "symfony/yaml": "^4.4|^5.1" }, "suggest": { "gesdinet/jwt-refresh-token-bundle": "Implements a refresh token system over Json Web Tokens in Symfony", From 987cfc78ef34f6c7c5cd39faa0990805605ff371 Mon Sep 17 00:00:00 2001 From: Robin Chalas Date: Sun, 3 Jan 2021 15:20:39 +0100 Subject: [PATCH 2/2] Fix CS --- .php_cs | 25 +++----- Command/CheckConfigCommand.php | 2 +- Command/GenerateTokenCommand.php | 2 +- DependencyInjection/Configuration.php | 2 +- .../LexikJWTAuthenticationExtension.php | 3 +- .../Security/Factory/JWTFactory.php | 5 +- Encoder/HeaderAwareJWTEncoderInterface.php | 3 - Encoder/JWTEncoderInterface.php | 2 - Encoder/LcobucciJWTEncoder.php | 3 - Event/AuthenticationFailureEvent.php | 9 +-- Event/AuthenticationSuccessEvent.php | 12 +--- Event/JWTAuthenticatedEvent.php | 9 +-- Event/JWTCreatedEvent.php | 15 +---- Event/JWTDecodedEvent.php | 6 -- Event/JWTFailureEventInterface.php | 2 - Event/JWTNotFoundEvent.php | 6 +- Exception/JWTDecodeFailureException.php | 4 +- Exception/UserNotFoundException.php | 2 +- Helper/JWTSplitter.php | 1 + README.md | 2 +- Response/JWTAuthenticationFailureResponse.php | 4 +- Response/JWTAuthenticationSuccessResponse.php | 1 - .../Authentication/Provider/JWTProvider.php | 17 ++--- ...PreAuthenticationJWTUserTokenInterface.php | 2 - Security/Firewall/AbstractListener.php | 64 ------------------- Security/Firewall/JWTListener.php | 31 ++------- Security/Guard/JWTTokenAuthenticator.php | 25 ++------ .../AuthenticationFailureHandler.php | 5 +- .../AuthenticationSuccessHandler.php | 4 +- Security/User/JWTUser.php | 7 +- Security/User/JWTUserInterface.php | 1 - .../PayloadAwareUserProviderInterface.php | 1 - Services/JWSProvider/DefaultJWSProvider.php | 25 ++++---- Services/JWSProvider/JWSProviderInterface.php | 3 - Services/JWSProvider/LcobucciJWSProvider.php | 10 ++- Services/JWTManager.php | 26 ++------ Services/JWTManagerInterface.php | 4 -- Services/JWTTokenManagerInterface.php | 4 -- Services/KeyLoader/AbstractKeyLoader.php | 12 ++-- Services/KeyLoader/KeyLoaderInterface.php | 2 +- Services/KeyLoader/OpenSSLKeyLoader.php | 6 +- Services/KeyLoader/RawKeyLoader.php | 6 +- Signature/LoadedJWS.php | 10 +-- Tests/DependencyInjection/AutowiringTest.php | 30 ++++----- .../LexikJWTAuthenticationExtensionTest.php | 10 ++- Tests/Encoder/DefaultEncoderTest.php | 10 +-- .../Bundle/Controller/TestController.php | 6 +- .../CompleteTokenAuthenticationTest.php | 2 +- Tests/Functional/GetTokenTest.php | 5 +- Tests/Functional/TestCase.php | 2 +- .../Utils/CallableEventSubscriber.php | 16 ++--- Tests/Functional/app/AppKernel.php | 6 +- .../JWTAuthenticationFailureResponseTest.php | 2 +- .../JWTAuthenticationSuccessResponseTest.php | 2 +- .../Firewall/JWTListenerTest.php | 18 ++---- .../Provider/JWTProviderTest.php | 4 +- .../Guard/JWTTokenAuthenticatorTest.php | 23 ++++--- .../AuthenticationFailureHandlerTest.php | 4 +- .../AuthenticationSuccessHandlerTest.php | 6 +- Tests/Security/User/JWTUserProviderTest.php | 2 +- .../JWSProvider/AbstractJWSProviderTest.php | 9 ++- .../JWSProvider/DefaultJWSProviderTest.php | 2 +- .../JWSProvider/LcobucciJWSProviderTest.php | 2 +- Tests/Services/JWTManagerTest.php | 1 - .../KeyLoader/AbstractTestKeyLoader.php | 2 +- Tests/Signature/LoadedJWSTest.php | 9 +-- Tests/Stubs/User.php | 10 +-- .../ChainTokenExtractorTest.php | 4 +- .../AuthorizationHeaderTokenExtractor.php | 2 +- TokenExtractor/ChainTokenExtractor.php | 7 +- TokenExtractor/SplitCookieExtractor.php | 3 +- TokenExtractor/TokenExtractorInterface.php | 2 - phpstan.neon | 4 ++ 73 files changed, 192 insertions(+), 398 deletions(-) delete mode 100644 Security/Firewall/AbstractListener.php create mode 100644 phpstan.neon diff --git a/.php_cs b/.php_cs index b31935af..e697c1e2 100755 --- a/.php_cs +++ b/.php_cs @@ -1,21 +1,14 @@ in(array(__DIR__)) -; +$finder = PhpCsFixer\Finder::create()->in([__DIR__]); -return Symfony\CS\Config\Config::create() - ->level(Symfony\CS\FixerInterface::SYMFONY_LEVEL) - ->fixers(array( - '-phpdoc_scalar', - '-extra_empty_lines', - '-unalign_double_arrow', - '-unalign_equals', - 'align_double_arrow', - 'newline_after_open_tag', - 'ordered_use', - 'short_array_syntax', - )) +return PhpCsFixer\Config::create() + ->setRules([ + '@Symfony' => true, + 'ordered_imports' => true, + 'array_syntax' => ['syntax' => 'short'], + 'phpdoc_scalar' => false, + ]) ->setUsingCache(false) - ->finder($finder) + ->setFinder($finder); ; diff --git a/Command/CheckConfigCommand.php b/Command/CheckConfigCommand.php index 9eb2169c..5b4c4b8d 100644 --- a/Command/CheckConfigCommand.php +++ b/Command/CheckConfigCommand.php @@ -22,7 +22,7 @@ class CheckConfigCommand extends Command public function __construct(KeyLoaderInterface $keyLoader, $signatureAlgorithm) { - $this->keyLoader = $keyLoader; + $this->keyLoader = $keyLoader; $this->signatureAlgorithm = $signatureAlgorithm; parent::__construct(); diff --git a/Command/GenerateTokenCommand.php b/Command/GenerateTokenCommand.php index 3b7d6be9..d2e4b9b8 100644 --- a/Command/GenerateTokenCommand.php +++ b/Command/GenerateTokenCommand.php @@ -28,7 +28,7 @@ public function __construct(JWTTokenManagerInterface $tokenManager, \Traversable { parent::__construct(); - $this->tokenManager = $tokenManager; + $this->tokenManager = $tokenManager; $this->userProviders = $userProviders; } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 25cd5966..481622db 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -109,7 +109,7 @@ public function getConfigTreeBuilder() private function getTokenExtractorsNode() { $builder = new TreeBuilder('token_extractors'); - $node = \method_exists(TreeBuilder::class, 'getRootNode') ? $builder->getRootNode() : $builder->root('token_extractors'); + $node = $builder->getRootNode(); $node ->addDefaultsIfNotSet() ->children() diff --git a/DependencyInjection/LexikJWTAuthenticationExtension.php b/DependencyInjection/LexikJWTAuthenticationExtension.php index 281c43e5..a33ac360 100644 --- a/DependencyInjection/LexikJWTAuthenticationExtension.php +++ b/DependencyInjection/LexikJWTAuthenticationExtension.php @@ -27,7 +27,7 @@ class LexikJWTAuthenticationExtension extends Extension public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); - $config = $this->processConfiguration($configuration, $configs); + $config = $this->processConfiguration($configuration, $configs); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); @@ -63,7 +63,6 @@ public function load(array $configs, ContainerBuilder $container) $e->setPath('lexik_jwt_authentication'); throw $e; - } $container->setParameter('lexik_jwt_authentication.pass_phrase', $config['pass_phrase']); diff --git a/DependencyInjection/Security/Factory/JWTFactory.php b/DependencyInjection/Security/Factory/JWTFactory.php index ae8e084f..14514209 100644 --- a/DependencyInjection/Security/Factory/JWTFactory.php +++ b/DependencyInjection/Security/Factory/JWTFactory.php @@ -158,9 +158,8 @@ public function addConfiguration(NodeDefinition $node) /** * Create an entry point, by default it sends a 401 header and ends the request. * - * @param ContainerBuilder $container - * @param string $id - * @param mixed $defaultEntryPoint + * @param string $id + * @param mixed $defaultEntryPoint * * @return string */ diff --git a/Encoder/HeaderAwareJWTEncoderInterface.php b/Encoder/HeaderAwareJWTEncoderInterface.php index 7715fbf7..788c395f 100644 --- a/Encoder/HeaderAwareJWTEncoderInterface.php +++ b/Encoder/HeaderAwareJWTEncoderInterface.php @@ -10,9 +10,6 @@ interface HeaderAwareJWTEncoderInterface extends JWTEncoderInterface { /** - * @param array $data - * @param array $header - * * @return string the encoded token string * * @throws JWTEncodeFailureException If an error occurred while trying to create diff --git a/Encoder/JWTEncoderInterface.php b/Encoder/JWTEncoderInterface.php index a65b223f..e048ea49 100644 --- a/Encoder/JWTEncoderInterface.php +++ b/Encoder/JWTEncoderInterface.php @@ -13,8 +13,6 @@ interface JWTEncoderInterface { /** - * @param array $data - * * @return string the encoded token string * * @throws JWTEncodeFailureException If an error occurred while trying to create diff --git a/Encoder/LcobucciJWTEncoder.php b/Encoder/LcobucciJWTEncoder.php index 0889938d..b664b3d8 100644 --- a/Encoder/LcobucciJWTEncoder.php +++ b/Encoder/LcobucciJWTEncoder.php @@ -18,9 +18,6 @@ class LcobucciJWTEncoder implements JWTEncoderInterface, HeaderAwareJWTEncoderIn */ protected $jwsProvider; - /** - * @param JWSProviderInterface $jwsProvider - */ public function __construct(JWSProviderInterface $jwsProvider) { $this->jwsProvider = $jwsProvider; diff --git a/Event/AuthenticationFailureEvent.php b/Event/AuthenticationFailureEvent.php index 324aa5d5..b0cd682c 100644 --- a/Event/AuthenticationFailureEvent.php +++ b/Event/AuthenticationFailureEvent.php @@ -24,14 +24,10 @@ class AuthenticationFailureEvent extends Event */ protected $response; - /** - * @param AuthenticationException $exception - * @param Response $response - */ public function __construct(AuthenticationException $exception, Response $response) { $this->exception = $exception; - $this->response = $response; + $this->response = $response; } /** @@ -50,9 +46,6 @@ public function getResponse() return $this->response; } - /** - * @param Response $response - */ public function setResponse(Response $response) { $this->response = $response; diff --git a/Event/AuthenticationSuccessEvent.php b/Event/AuthenticationSuccessEvent.php index b8807020..2827002e 100644 --- a/Event/AuthenticationSuccessEvent.php +++ b/Event/AuthenticationSuccessEvent.php @@ -28,15 +28,10 @@ class AuthenticationSuccessEvent extends Event */ protected $response; - /** - * @param array $data - * @param UserInterface $user - * @param Response $response - */ public function __construct(array $data, UserInterface $user, Response $response) { - $this->data = $data; - $this->user = $user; + $this->data = $data; + $this->user = $user; $this->response = $response; } @@ -48,9 +43,6 @@ public function getData() return $this->data; } - /** - * @param array $data - */ public function setData(array $data) { $this->data = $data; diff --git a/Event/JWTAuthenticatedEvent.php b/Event/JWTAuthenticatedEvent.php index 53863bfa..226a2ab6 100644 --- a/Event/JWTAuthenticatedEvent.php +++ b/Event/JWTAuthenticatedEvent.php @@ -20,14 +20,10 @@ class JWTAuthenticatedEvent extends Event */ protected $token; - /** - * @param array $payload - * @param TokenInterface $token - */ public function __construct(array $payload, TokenInterface $token) { $this->payload = $payload; - $this->token = $token; + $this->token = $token; } /** @@ -38,9 +34,6 @@ public function getPayload() return $this->payload; } - /** - * @param array $payload - */ public function setPayload(array $payload) { $this->payload = $payload; diff --git a/Event/JWTCreatedEvent.php b/Event/JWTCreatedEvent.php index 536445ce..0ef04d6b 100644 --- a/Event/JWTCreatedEvent.php +++ b/Event/JWTCreatedEvent.php @@ -25,15 +25,10 @@ class JWTCreatedEvent extends Event */ protected $user; - /** - * @param array $data - * @param UserInterface $user - * @param array $header - */ public function __construct(array $data, UserInterface $user, array $header = []) { - $this->data = $data; - $this->user = $user; + $this->data = $data; + $this->user = $user; $this->header = $header; } @@ -45,9 +40,6 @@ public function getHeader() return $this->header; } - /** - * @param array $header - */ public function setHeader(array $header) { $this->header = $header; @@ -61,9 +53,6 @@ public function getData() return $this->data; } - /** - * @param array $data - */ public function setData(array $data) { $this->data = $data; diff --git a/Event/JWTDecodedEvent.php b/Event/JWTDecodedEvent.php index 13b522a3..3b40681f 100644 --- a/Event/JWTDecodedEvent.php +++ b/Event/JWTDecodedEvent.php @@ -21,9 +21,6 @@ class JWTDecodedEvent extends Event */ protected $isValid; - /** - * @param array $payload - */ public function __construct(array $payload) { $this->payload = $payload; @@ -38,9 +35,6 @@ public function getPayload() return $this->payload; } - /** - * @param array $payload - */ public function setPayload(array $payload) { $this->payload = $payload; diff --git a/Event/JWTFailureEventInterface.php b/Event/JWTFailureEventInterface.php index 7620d4f5..01e78d22 100644 --- a/Event/JWTFailureEventInterface.php +++ b/Event/JWTFailureEventInterface.php @@ -30,8 +30,6 @@ public function getException(); /** * Calling this allows to return a custom Response immediately after * the corresponding implementation of this event is dispatched. - * - * @param Response $response */ public function setResponse(Response $response); } diff --git a/Event/JWTNotFoundEvent.php b/Event/JWTNotFoundEvent.php index b1a1a809..24dd592f 100644 --- a/Event/JWTNotFoundEvent.php +++ b/Event/JWTNotFoundEvent.php @@ -13,13 +13,9 @@ */ class JWTNotFoundEvent extends AuthenticationFailureEvent implements JWTFailureEventInterface { - /** - * @param AuthenticationException|null $exception - * @param Response|null $response - */ public function __construct(AuthenticationException $exception = null, Response $response = null) { $this->exception = $exception; - $this->response = $response; + $this->response = $response; } } diff --git a/Exception/JWTDecodeFailureException.php b/Exception/JWTDecodeFailureException.php index 7c9bc84b..84d3a38b 100644 --- a/Exception/JWTDecodeFailureException.php +++ b/Exception/JWTDecodeFailureException.php @@ -9,9 +9,9 @@ */ class JWTDecodeFailureException extends JWTFailureException { - const INVALID_TOKEN = 'invalid_token'; + const INVALID_TOKEN = 'invalid_token'; const UNVERIFIED_TOKEN = 'unverified_token'; - const EXPIRED_TOKEN = 'expired_token'; + const EXPIRED_TOKEN = 'expired_token'; } diff --git a/Exception/UserNotFoundException.php b/Exception/UserNotFoundException.php index e98f50f3..62aaed92 100644 --- a/Exception/UserNotFoundException.php +++ b/Exception/UserNotFoundException.php @@ -17,7 +17,7 @@ class UserNotFoundException extends AuthenticationException public function __construct(string $userIdentityField, string $identity) { $this->userIdentityField = $userIdentityField; - $this->identity = $identity; + $this->identity = $identity; } /** diff --git a/Helper/JWTSplitter.php b/Helper/JWTSplitter.php index 5016e300..869863fb 100644 --- a/Helper/JWTSplitter.php +++ b/Helper/JWTSplitter.php @@ -33,6 +33,7 @@ public function __construct(string $jwt) /** * @param array $parts + * * @return string */ public function getParts($parts = []) diff --git a/README.md b/README.md index 3cf55851..11f67608 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ LexikJWTAuthenticationBundle This bundle provides JWT (Json Web Token) authentication for your Symfony API. -It is compatible and tested with PHP 7.1+ on Symfony 3.4, 4.x and 5.x. +It is compatible and tested with PHP 7.1+ on Symfony 4.x and 5.x. Documentation ------------- diff --git a/Response/JWTAuthenticationFailureResponse.php b/Response/JWTAuthenticationFailureResponse.php index d7817020..44830547 100644 --- a/Response/JWTAuthenticationFailureResponse.php +++ b/Response/JWTAuthenticationFailureResponse.php @@ -13,7 +13,9 @@ */ final class JWTAuthenticationFailureResponse extends JsonResponse { - public function __construct(string $message = 'Bad credentials', string $statusCode = JsonResponse::HTTP_UNAUTHORIZED) + private $message; + + public function __construct(string $message = 'Bad credentials', int $statusCode = JsonResponse::HTTP_UNAUTHORIZED) { $this->message = $message; diff --git a/Response/JWTAuthenticationSuccessResponse.php b/Response/JWTAuthenticationSuccessResponse.php index c92a9360..b51384a9 100644 --- a/Response/JWTAuthenticationSuccessResponse.php +++ b/Response/JWTAuthenticationSuccessResponse.php @@ -2,7 +2,6 @@ namespace Lexik\Bundle\JWTAuthenticationBundle\Response; -use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\JsonResponse; /** diff --git a/Security/Authentication/Provider/JWTProvider.php b/Security/Authentication/Provider/JWTProvider.php index c64a71fb..d9b89a58 100644 --- a/Security/Authentication/Provider/JWTProvider.php +++ b/Security/Authentication/Provider/JWTProvider.php @@ -8,11 +8,11 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTManagerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\User\UserProviderInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * JWTProvider. @@ -50,10 +50,7 @@ class JWTProvider implements AuthenticationProviderInterface private $userIdClaim; /** - * @param UserProviderInterface $userProvider - * @param JWTManagerInterface $jwtManager - * @param EventDispatcherInterface $dispatcher - * @param string $userIdClaim + * @param string $userIdClaim */ public function __construct( UserProviderInterface $userProvider, @@ -63,11 +60,11 @@ public function __construct( ) { @trigger_error(sprintf('The "%s" class is deprecated since version 2.0 and will be removed in 3.0. See "%s" instead.', __CLASS__, JWTTokenAuthenticator::class), E_USER_DEPRECATED); - $this->userProvider = $userProvider; - $this->jwtManager = $jwtManager; - $this->dispatcher = $dispatcher; + $this->userProvider = $userProvider; + $this->jwtManager = $jwtManager; + $this->dispatcher = $dispatcher; $this->userIdentityField = 'username'; - $this->userIdClaim = $userIdClaim; + $this->userIdClaim = $userIdClaim; } /** @@ -99,8 +96,6 @@ public function authenticate(TokenInterface $token) * Load user from payload, using username by default. * Override this to load by another property. * - * @param array $payload - * * @return \Symfony\Component\Security\Core\User\UserInterface */ protected function getUserFromPayload(array $payload) diff --git a/Security/Authentication/Token/PreAuthenticationJWTUserTokenInterface.php b/Security/Authentication/Token/PreAuthenticationJWTUserTokenInterface.php index cf6aa888..5d597461 100644 --- a/Security/Authentication/Token/PreAuthenticationJWTUserTokenInterface.php +++ b/Security/Authentication/Token/PreAuthenticationJWTUserTokenInterface.php @@ -6,9 +6,7 @@ interface PreAuthenticationJWTUserTokenInterface extends GuardTokenInterface { - /** - * @param array $payload * @return void */ public function setPayload(array $payload); diff --git a/Security/Firewall/AbstractListener.php b/Security/Firewall/AbstractListener.php deleted file mode 100644 index 1989aa1b..00000000 --- a/Security/Firewall/AbstractListener.php +++ /dev/null @@ -1,64 +0,0 @@ -getKernel(), $event->getRequest(), $event->getRequestType()); - $this->event = $event; - } - - public function getResponse() - { - return $this->event->getResponse(); - } - - public function setResponse(Response $response) - { - $this->event->setResponse($response); - } - - public function hasResponse() - { - return $this->event->hasResponse(); - } - } - } - - /** - * @internal - */ - abstract class AbstractListener implements ListenerInterface - { - public function handle(GetResponseEvent $event) - { - if (class_exists(RequestEvent::class) && !$event instanceof RequestEvent) { - $event = new ForwardRequestEvent($event); - } - - $this->__invoke($event); - } - - abstract public function __invoke($event); - } -} else { - abstract class AbstractListener - { - abstract public function __invoke($event); - } -} diff --git a/Security/Firewall/JWTListener.php b/Security/Firewall/JWTListener.php index 127a35a9..6e8bf95d 100644 --- a/Security/Firewall/JWTListener.php +++ b/Security/Firewall/JWTListener.php @@ -9,14 +9,13 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\JWTUserToken; use Lexik\Bundle\JWTAuthenticationBundle\Security\Guard\JWTTokenAuthenticator; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; -use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; -use Symfony\Component\Security\Http\Firewall\ListenerInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * JWTListener. @@ -27,7 +26,7 @@ * @deprecated since 2.0, will be removed in 3.0. See * {@link JWTTokenAuthenticator} instead */ -class JWTListener extends AbstractListener +class JWTListener { /** * @var TokenStorageInterface @@ -54,11 +53,6 @@ class JWTListener extends AbstractListener */ protected $tokenExtractors; - /** - * @param TokenStorageInterface $tokenStorage - * @param AuthenticationManagerInterface $authenticationManager - * @param array $config - */ public function __construct( TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, @@ -66,16 +60,13 @@ public function __construct( ) { @trigger_error(sprintf('The "%s" class is deprecated since version 2.0 and will be removed in 3.0. See "%s" instead.', __CLASS__, JWTTokenAuthenticator::class), E_USER_DEPRECATED); - $this->tokenStorage = $tokenStorage; + $this->tokenStorage = $tokenStorage; $this->authenticationManager = $authenticationManager; - $this->config = array_merge(['throw_exceptions' => false], $config); - $this->tokenExtractors = []; + $this->config = array_merge(['throw_exceptions' => false], $config); + $this->tokenExtractors = []; } - /** - * @param GetResponseEvent|RequestEvent $event - */ - public function __invoke($event) + public function __invoke(RequestEvent $event) { $requestToken = $this->getRequestToken($event->getRequest()); @@ -112,25 +103,17 @@ public function __invoke($event) } } - /** - * @param TokenExtractorInterface $extractor - */ public function addTokenExtractor(TokenExtractorInterface $extractor) { $this->tokenExtractors[] = $extractor; } - /** - * @param EventDispatcherInterface $dispatcher - */ public function setDispatcher(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; } /** - * @param Request $request - * * @return string */ protected function getRequestToken(Request $request) diff --git a/Security/Guard/JWTTokenAuthenticator.php b/Security/Guard/JWTTokenAuthenticator.php index 0ec4c080..ce230c10 100644 --- a/Security/Guard/JWTTokenAuthenticator.php +++ b/Security/Guard/JWTTokenAuthenticator.php @@ -20,9 +20,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Security\User\PayloadAwareUserProviderInterface; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -31,6 +29,7 @@ use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Guard\AbstractGuardAuthenticator; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * JWTTokenAuthenticator (Guard implementation). @@ -62,21 +61,15 @@ class JWTTokenAuthenticator extends AbstractGuardAuthenticator */ private $preAuthenticationTokenStorage; - /** - * @param JWTTokenManagerInterface $jwtManager - * @param EventDispatcherInterface $dispatcher - * @param TokenExtractorInterface $tokenExtractor - * @param TokenStorageInterface $preAuthenticationTokenStorage - */ public function __construct( JWTTokenManagerInterface $jwtManager, EventDispatcherInterface $dispatcher, TokenExtractorInterface $tokenExtractor, TokenStorageInterface $preAuthenticationTokenStorage ) { - $this->jwtManager = $jwtManager; - $this->dispatcher = $dispatcher; - $this->tokenExtractor = $tokenExtractor; + $this->jwtManager = $jwtManager; + $this->dispatcher = $dispatcher; + $this->tokenExtractor = $tokenExtractor; $this->preAuthenticationTokenStorage = $preAuthenticationTokenStorage; } @@ -133,7 +126,7 @@ public function getCredentials(Request $request) * * {@inheritdoc} * - * @param PreAuthenticationJWTUserTokenInterface Implementation of the (Security) TokenInterface + * @param PreAuthenticationJWTUserTokenInterface $preAuthToken Implementation of the (Security) TokenInterface * * @throws \InvalidArgumentException If preAuthToken is not of the good type * @throws InvalidPayloadException If the user identity field is not a key of the payload @@ -142,15 +135,12 @@ public function getCredentials(Request $request) public function getUser($preAuthToken, UserProviderInterface $userProvider) { if (!$preAuthToken instanceof PreAuthenticationJWTUserTokenInterface) { - throw new \InvalidArgumentException( - sprintf('The first argument of the "%s()" method must be an instance of "%s".', __METHOD__, PreAuthenticationJWTUserTokenInterface::class) - ); + throw new \InvalidArgumentException(sprintf('The first argument of the "%s()" method must be an instance of "%s".', __METHOD__, PreAuthenticationJWTUserTokenInterface::class)); } $payload = $preAuthToken->getPayload(); $idClaim = $this->jwtManager->getUserIdClaim(); - if (!isset($payload[$idClaim])) { throw new InvalidPayloadException($idClaim); } @@ -183,7 +173,6 @@ public function onAuthenticationFailure(Request $request, AuthenticationExceptio $eventName = Events::JWT_INVALID; } - $this->dispatcher->dispatch($event, $eventName); return $event->getResponse(); @@ -205,7 +194,7 @@ public function onAuthenticationSuccess(Request $request, TokenInterface $token, public function start(Request $request, AuthenticationException $authException = null) { $exception = new MissingTokenException('JWT Token not found', 0, $authException); - $event = new JWTNotFoundEvent($exception, new JWTAuthenticationFailureResponse($exception->getMessageKey())); + $event = new JWTNotFoundEvent($exception, new JWTAuthenticationFailureResponse($exception->getMessageKey())); $this->dispatcher->dispatch($event, Events::JWT_NOT_FOUND); diff --git a/Security/Http/Authentication/AuthenticationFailureHandler.php b/Security/Http/Authentication/AuthenticationFailureHandler.php index 09cc9680..00fa3cba 100644 --- a/Security/Http/Authentication/AuthenticationFailureHandler.php +++ b/Security/Http/Authentication/AuthenticationFailureHandler.php @@ -5,10 +5,10 @@ use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * AuthenticationFailureHandler. @@ -22,9 +22,6 @@ class AuthenticationFailureHandler implements AuthenticationFailureHandlerInterf */ protected $dispatcher; - /** - * @param EventDispatcherInterface $dispatcher - */ public function __construct(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; diff --git a/Security/Http/Authentication/AuthenticationSuccessHandler.php b/Security/Http/Authentication/AuthenticationSuccessHandler.php index a088e739..a14c9410 100644 --- a/Security/Http/Authentication/AuthenticationSuccessHandler.php +++ b/Security/Http/Authentication/AuthenticationSuccessHandler.php @@ -7,11 +7,11 @@ use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse; use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Cookie\JWTCookieProvider; use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * AuthenticationSuccessHandler. @@ -58,7 +58,7 @@ public function handleAuthenticationSuccess(UserInterface $user, $jwt = null) } $response = new JWTAuthenticationSuccessResponse($jwt, [], $jwtCookies); - $event = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response); + $event = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response); $this->dispatcher->dispatch($event, Events::AUTHENTICATION_SUCCESS); $responseData = $event->getData(); diff --git a/Security/User/JWTUser.php b/Security/User/JWTUser.php index da802a96..32e85db1 100644 --- a/Security/User/JWTUser.php +++ b/Security/User/JWTUser.php @@ -14,10 +14,13 @@ class JWTUser implements JWTUserInterface private $username; private $roles; + /** + * @final + */ public function __construct(string $username, array $roles = []) { $this->username = $username; - $this->roles = $roles; + $this->roles = $roles; } /** @@ -53,6 +56,7 @@ public function getRoles() */ public function getPassword() { + return null; } /** @@ -60,6 +64,7 @@ public function getPassword() */ public function getSalt() { + return null; } /** diff --git a/Security/User/JWTUserInterface.php b/Security/User/JWTUserInterface.php index 71296621..0ff8fddb 100644 --- a/Security/User/JWTUserInterface.php +++ b/Security/User/JWTUserInterface.php @@ -10,7 +10,6 @@ interface JWTUserInterface extends UserInterface * Creates a new instance from a given JWT payload. * * @param string $username - * @param array $payload * * @return JWTUserInterface */ diff --git a/Security/User/PayloadAwareUserProviderInterface.php b/Security/User/PayloadAwareUserProviderInterface.php index 16f4cd5e..4627fb27 100644 --- a/Security/User/PayloadAwareUserProviderInterface.php +++ b/Security/User/PayloadAwareUserProviderInterface.php @@ -12,7 +12,6 @@ interface PayloadAwareUserProviderInterface extends UserProviderInterface * Load a user by its username, including the JWT token payload. * * @param string $username - * @param array $payload * * @throws UsernameNotFoundException if the user is not found * diff --git a/Services/JWSProvider/DefaultJWSProvider.php b/Services/JWSProvider/DefaultJWSProvider.php index 99ab6d67..c56ebbcb 100644 --- a/Services/JWSProvider/DefaultJWSProvider.php +++ b/Services/JWSProvider/DefaultJWSProvider.php @@ -47,11 +47,10 @@ class DefaultJWSProvider implements JWSProviderInterface private $clockSkew; /** - * @param KeyLoaderInterface $keyLoader - * @param string $cryptoEngine - * @param string $signatureAlgorithm - * @param int $ttl - * @param int $clockSkew + * @param string $cryptoEngine + * @param string $signatureAlgorithm + * @param int $ttl + * @param int $clockSkew * * @throws \InvalidArgumentException If the given algorithm is not supported */ @@ -68,16 +67,14 @@ public function __construct(KeyLoaderInterface $keyLoader, $cryptoEngine, $signa $cryptoEngine = 'openssl' == $cryptoEngine ? 'OpenSSL' : 'SecLib'; if (!$this->isAlgorithmSupportedForEngine($cryptoEngine, $signatureAlgorithm)) { - throw new \InvalidArgumentException( - sprintf('The algorithm "%s" is not supported for %s', $signatureAlgorithm, $cryptoEngine) - ); + throw new \InvalidArgumentException(sprintf('The algorithm "%s" is not supported for %s', $signatureAlgorithm, $cryptoEngine)); } - $this->keyLoader = $keyLoader; - $this->cryptoEngine = $cryptoEngine; + $this->keyLoader = $keyLoader; + $this->cryptoEngine = $cryptoEngine; $this->signatureAlgorithm = $signatureAlgorithm; - $this->ttl = $ttl; - $this->clockSkew = $clockSkew; + $this->ttl = $ttl; + $this->clockSkew = $clockSkew; } /** @@ -86,8 +83,8 @@ public function __construct(KeyLoaderInterface $keyLoader, $cryptoEngine, $signa public function create(array $payload, array $header = []) { $header['alg'] = $this->signatureAlgorithm; - $jws = new JWS($header, $this->cryptoEngine); - $claims = ['iat' => time()]; + $jws = new JWS($header, $this->cryptoEngine); + $claims = ['iat' => time()]; if (null !== $this->ttl && !isset($payload['exp'])) { $claims['exp'] = time() + $this->ttl; diff --git a/Services/JWSProvider/JWSProviderInterface.php b/Services/JWSProvider/JWSProviderInterface.php index 4624fceb..6ea23803 100644 --- a/Services/JWSProvider/JWSProviderInterface.php +++ b/Services/JWSProvider/JWSProviderInterface.php @@ -12,9 +12,6 @@ interface JWSProviderInterface /** * Creates a new JWS signature from a given payload. * - * @param array $payload - * @param array $header - * * @return \Lexik\Bundle\JWTAuthenticationBundle\Signature\CreatedJWS */ public function create(array $payload, array $header = []); diff --git a/Services/JWSProvider/LcobucciJWSProvider.php b/Services/JWSProvider/LcobucciJWSProvider.php index a3908519..cf84b55e 100644 --- a/Services/JWSProvider/LcobucciJWSProvider.php +++ b/Services/JWSProvider/LcobucciJWSProvider.php @@ -7,13 +7,13 @@ use Lcobucci\JWT\Encoding\JoseEncoder; use Lcobucci\JWT\Encoding\MicrosecondBasedDateConversion; use Lcobucci\JWT\Parser; -use Lcobucci\JWT\Token\Parser as JWTParser; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer\Hmac; use Lcobucci\JWT\Signer\Key; use Lcobucci\JWT\Signer\Key\InMemory; use Lcobucci\JWT\Token; use Lcobucci\JWT\Token\Builder as JWTBuilder; +use Lcobucci\JWT\Token\Parser as JWTParser; use Lcobucci\JWT\Token\Plain; use Lcobucci\JWT\Token\RegisteredClaims; use Lcobucci\JWT\Validation\Constraint\SignedWith; @@ -75,8 +75,8 @@ public function __construct(KeyLoaderInterface $keyLoader, string $cryptoEngine, } $this->keyLoader = $keyLoader; - $this->signer = $this->getSignerForAlgorithm($signatureAlgorithm); - $this->ttl = $ttl; + $this->signer = $this->getSignerForAlgorithm($signatureAlgorithm); + $this->ttl = $ttl; $this->clockSkew = $clockSkew; $this->useDateObjects = method_exists(Token::class, 'payload') || class_exists(Plain::class); // exists only on lcobucci/jwt 3.4+ } @@ -180,9 +180,7 @@ private function getSignerForAlgorithm($signatureAlgorithm) ]; if (!isset($signerMap[$signatureAlgorithm])) { - throw new \InvalidArgumentException( - sprintf('The algorithm "%s" is not supported by %s', $signatureAlgorithm, __CLASS__) - ); + throw new \InvalidArgumentException(sprintf('The algorithm "%s" is not supported by %s', $signatureAlgorithm, __CLASS__)); } $signerClass = $signerMap[$signatureAlgorithm]; diff --git a/Services/JWTManager.php b/Services/JWTManager.php index c5a58dc1..a755ff4a 100644 --- a/Services/JWTManager.php +++ b/Services/JWTManager.php @@ -8,10 +8,10 @@ use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent; use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTEncodedEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Provides convenient methods to manage JWT creation/verification. @@ -42,22 +42,17 @@ class JWTManager implements JWTManagerInterface, JWTTokenManagerInterface protected $userIdClaim; /** - * @param JWTEncoderInterface $encoder - * @param EventDispatcherInterface $dispatcher - * @param string|null $userIdClaim + * @param string|null $userIdClaim */ public function __construct(JWTEncoderInterface $encoder, EventDispatcherInterface $dispatcher, $userIdClaim = null) { - $this->jwtEncoder = $encoder; - $this->dispatcher = $dispatcher; + $this->jwtEncoder = $encoder; + $this->dispatcher = $dispatcher; $this->userIdentityField = 'username'; - $this->userIdClaim = $userIdClaim; + $this->userIdClaim = $userIdClaim; } /** - * @param UserInterface $user - * @param array $payload - * * @return string The JWT token */ public function create(UserInterface $user) @@ -69,9 +64,6 @@ public function create(UserInterface $user) } /** - * @param UserInterface $user - * @param array $payload - * * @return string The JWT token */ public function createFromPayload(UserInterface $user, array $payload) @@ -83,9 +75,6 @@ public function createFromPayload(UserInterface $user, array $payload) } /** - * @param UserInterface $user - * @param array $payload - * * @return string The JWT token */ private function generateJwtStringAndDispatchEvents(UserInterface $user, array $payload) @@ -129,12 +118,11 @@ public function decode(TokenInterface $token) * Add user identity to payload, username by default. * Override this if you need to identify it by another property. * - * @param UserInterface $user - * @param array &$payload + * @param array &$payload */ protected function addUserIdentityToPayload(UserInterface $user, array &$payload) { - $accessor = PropertyAccess::createPropertyAccessor(); + $accessor = PropertyAccess::createPropertyAccessor(); $payload[$this->userIdClaim ?: $this->userIdentityField] = $accessor->getValue($user, $this->userIdentityField); } diff --git a/Services/JWTManagerInterface.php b/Services/JWTManagerInterface.php index f48b7b00..b9bb8b5a 100644 --- a/Services/JWTManagerInterface.php +++ b/Services/JWTManagerInterface.php @@ -15,15 +15,11 @@ interface JWTManagerInterface { /** - * @param UserInterface $user - * * @return string The JWT token */ public function create(UserInterface $user); /** - * @param TokenInterface $token - * * @return array|false The JWT token payload or false if an error occurs */ public function decode(TokenInterface $token); diff --git a/Services/JWTTokenManagerInterface.php b/Services/JWTTokenManagerInterface.php index 800cdd0c..0bbfb67a 100644 --- a/Services/JWTTokenManagerInterface.php +++ b/Services/JWTTokenManagerInterface.php @@ -17,15 +17,11 @@ interface JWTTokenManagerInterface { /** - * @param UserInterface $user - * * @return string The JWT token */ public function create(UserInterface $user); /** - * @param TokenInterface $token - * * @return array|false The JWT token payload or false if an error occurs */ public function decode(TokenInterface $token); diff --git a/Services/KeyLoader/AbstractKeyLoader.php b/Services/KeyLoader/AbstractKeyLoader.php index 9c5b12c7..14a37d5d 100644 --- a/Services/KeyLoader/AbstractKeyLoader.php +++ b/Services/KeyLoader/AbstractKeyLoader.php @@ -18,7 +18,7 @@ abstract class AbstractKeyLoader implements KeyLoaderInterface public function __construct(?string $signingKey = null, ?string $publicKey = null, ?string $passphrase = null) { $this->signingKey = $signingKey; - $this->publicKey = $publicKey; + $this->publicKey = $publicKey; $this->passphrase = $passphrase; } @@ -57,9 +57,7 @@ protected function getKeyPath($type) $path = self::TYPE_PUBLIC === $type ? $this->publicKey : $this->signingKey; if (!is_file($path) || !is_readable($path)) { - throw new \RuntimeException( - sprintf('%s key is not a file or is not readable.', ucfirst($type)) - ); + throw new \RuntimeException(sprintf('%s key is not a file or is not readable.', ucfirst($type))); } return $path; @@ -68,16 +66,14 @@ protected function getKeyPath($type) private function readKey($type) { $isPublic = self::TYPE_PUBLIC === $type; - $key = $isPublic ? $this->publicKey : $this->signingKey; + $key = $isPublic ? $this->publicKey : $this->signingKey; if (!$key || !is_file($key) || !is_readable($key)) { if ($isPublic) { return null; } - throw new \RuntimeException( - sprintf('Signature key "%s" does not exist or is not readable. Did you correctly set the "lexik_jwt_authentication.signature_key" configuration key?', $key, $type) - ); + throw new \RuntimeException(sprintf('Signature key "%s" does not exist or is not readable. Did you correctly set the "lexik_jwt_authentication.signature_key" configuration key?', $key)); } return file_get_contents($key); diff --git a/Services/KeyLoader/KeyLoaderInterface.php b/Services/KeyLoader/KeyLoaderInterface.php index 85a30772..f435e031 100644 --- a/Services/KeyLoader/KeyLoaderInterface.php +++ b/Services/KeyLoader/KeyLoaderInterface.php @@ -11,7 +11,7 @@ */ interface KeyLoaderInterface { - const TYPE_PUBLIC = 'public'; + const TYPE_PUBLIC = 'public'; const TYPE_PRIVATE = 'private'; diff --git a/Services/KeyLoader/OpenSSLKeyLoader.php b/Services/KeyLoader/OpenSSLKeyLoader.php index 62dad8a1..2d0a68a4 100644 --- a/Services/KeyLoader/OpenSSLKeyLoader.php +++ b/Services/KeyLoader/OpenSSLKeyLoader.php @@ -26,7 +26,7 @@ public function loadKey($type) } $rawKey = file_get_contents($this->getKeyPath($type)); - $key = call_user_func_array("openssl_pkey_get_$type", self::TYPE_PRIVATE == $type ? [$rawKey, $this->getPassphrase()] : [$rawKey]); + $key = call_user_func_array("openssl_pkey_get_$type", self::TYPE_PRIVATE == $type ? [$rawKey, $this->getPassphrase()] : [$rawKey]); if (!$key) { $sslError = ''; @@ -37,9 +37,7 @@ public function loadKey($type) $sslError .= "\n $msg"; } - throw new \RuntimeException( - sprintf('Failed to load %s key: %s', $type, $sslError) - ); + throw new \RuntimeException(sprintf('Failed to load %s key: %s', $type, $sslError)); } return $key; diff --git a/Services/KeyLoader/RawKeyLoader.php b/Services/KeyLoader/RawKeyLoader.php index 8e7e2688..06392ed7 100644 --- a/Services/KeyLoader/RawKeyLoader.php +++ b/Services/KeyLoader/RawKeyLoader.php @@ -42,11 +42,9 @@ public function dumpKey() // no public key provided, compute it from signing key try { - $publicKey = openssl_pkey_get_details(openssl_pkey_get_private($signingKey, $this->getPassphrase()))['key']; + $publicKey = openssl_pkey_get_details(openssl_pkey_get_private($signingKey, $this->getPassphrase()))['key']; } catch (\Throwable $e) { - throw new \RuntimeException( - 'Secret key either does not exist, is not readable or is invalid. Did you correctly set the "lexik_jwt_authentication.secret_key" config option?' - ); + throw new \RuntimeException('Secret key either does not exist, is not readable or is invalid. Did you correctly set the "lexik_jwt_authentication.secret_key" config option?'); } return $publicKey; diff --git a/Signature/LoadedJWS.php b/Signature/LoadedJWS.php index f77a2bc7..0d5d3529 100644 --- a/Signature/LoadedJWS.php +++ b/Signature/LoadedJWS.php @@ -11,8 +11,8 @@ final class LoadedJWS { const VERIFIED = 'verified'; - const EXPIRED = 'expired'; - const INVALID = 'invalid'; + const EXPIRED = 'expired'; + const INVALID = 'invalid'; private $header; private $payload; @@ -22,10 +22,10 @@ final class LoadedJWS public function __construct(array $payload, bool $isVerified, bool $hasLifetime = true, array $header = [], int $clockSkew = 0) { - $this->payload = $payload; - $this->header = $header; + $this->payload = $payload; + $this->header = $header; $this->hasLifetime = $hasLifetime; - $this->clockSkew = $clockSkew; + $this->clockSkew = $clockSkew; if (true === $isVerified) { $this->state = self::VERIFIED; diff --git a/Tests/DependencyInjection/AutowiringTest.php b/Tests/DependencyInjection/AutowiringTest.php index cf3bc9f5..7a934f63 100644 --- a/Tests/DependencyInjection/AutowiringTest.php +++ b/Tests/DependencyInjection/AutowiringTest.php @@ -23,10 +23,10 @@ class AutowiringTest extends TestCase public function testAutowiring() { $container = $this->createContainerBuilder([ - 'framework' => ['secret' => 'test'], + 'framework' => ['secret' => 'test'], 'lexik_jwt_authentication' => [ - 'secret_key' => 'private.pem', - 'public_key' => 'public.pem', + 'secret_key' => 'private.pem', + 'public_key' => 'public.pem', 'pass_phrase' => 'testing', ], ]); @@ -51,11 +51,11 @@ public function testAutowiring() public function testAutowireConfiguredEncoderServiceForInterfaceTypeHint() { $container = $this->createContainerBuilder([ - 'framework' => ['secret' => 'testing'], + 'framework' => ['secret' => 'testing'], 'lexik_jwt_authentication' => [ - 'secret_key' => 'private.pem', + 'secret_key' => 'private.pem', 'pass_phrase' => 'testing', - 'encoder' => ['service' => 'app.dummy_encoder'], + 'encoder' => ['service' => 'app.dummy_encoder'], ], ]); @@ -79,16 +79,16 @@ public function testAutowireConfiguredEncoderServiceForInterfaceTypeHint() private static function createContainerBuilder(array $configs = []) { $container = new ContainerBuilder(new ParameterBag([ - 'kernel.bundles' => ['FrameworkBundle' => FrameworkBundle::class, 'LexikJWTAuthenticationBundle' => LexikJWTAuthenticationBundle::class], + 'kernel.bundles' => ['FrameworkBundle' => FrameworkBundle::class, 'LexikJWTAuthenticationBundle' => LexikJWTAuthenticationBundle::class], 'kernel.bundles_metadata' => [], - 'kernel.cache_dir' => __DIR__, - 'kernel.debug' => false, - 'kernel.environment' => 'test', - 'kernel.name' => 'kernel', - 'kernel.root_dir' => __DIR__, - 'kernel.project_dir' => __DIR__, - 'kernel.container_class' => 'AutowiringTestContainer', - 'kernel.charset' => 'utf8', + 'kernel.cache_dir' => __DIR__, + 'kernel.debug' => false, + 'kernel.environment' => 'test', + 'kernel.name' => 'kernel', + 'kernel.root_dir' => __DIR__, + 'kernel.project_dir' => __DIR__, + 'kernel.container_class' => 'AutowiringTestContainer', + 'kernel.charset' => 'utf8', 'kernel.runtime_environment' => 'test', 'env(base64:default::SYMFONY_DECRYPTION_SECRET)' => 'dummy', 'kernel.build_dir' => __DIR__, diff --git a/Tests/DependencyInjection/LexikJWTAuthenticationExtensionTest.php b/Tests/DependencyInjection/LexikJWTAuthenticationExtensionTest.php index 485eb279..733a8320 100644 --- a/Tests/DependencyInjection/LexikJWTAuthenticationExtensionTest.php +++ b/Tests/DependencyInjection/LexikJWTAuthenticationExtensionTest.php @@ -6,11 +6,9 @@ use Lexik\Bundle\JWTAuthenticationBundle\Encoder\DefaultEncoder; use Lexik\Bundle\JWTAuthenticationBundle\Encoder\LcobucciJWTEncoder; use PHPUnit\Framework\TestCase; -use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\EventDispatcher\EventDispatcher; /** * Tests the bundle extension and the configuration of services. @@ -21,7 +19,7 @@ class LexikJWTAuthenticationExtensionTest extends TestCase { public function testEncoderConfiguration() { - $container = $this->getContainer(['secret_key' => 'private.pem', 'public_key' => 'public.pem', 'pass_phrase' => 'test']); + $container = $this->getContainer(['secret_key' => 'private.pem', 'public_key' => 'public.pem', 'pass_phrase' => 'test']); $encoderDef = $container->findDefinition('lexik_jwt_authentication.encoder'); $this->assertSame(LcobucciJWTEncoder::class, $encoderDef->getClass()); $this->assertEquals(new Reference('lexik_jwt_authentication.jws_provider.lcobucci'), $encoderDef->getArgument(0)); @@ -48,10 +46,10 @@ public function testEncoderConfiguration() public function testDeprecatedDefaultEncoderService() { $container = $this->getContainer([ - 'secret_key' => 'private.pem', - 'public_key' => 'public.pem', + 'secret_key' => 'private.pem', + 'public_key' => 'public.pem', 'pass_phrase' => 'test', - 'encoder' => ['service' => 'lexik_jwt_authentication.encoder.default'], + 'encoder' => ['service' => 'lexik_jwt_authentication.encoder.default'], ]); $encoderDef = $container->findDefinition('lexik_jwt_authentication.encoder'); $this->assertSame(DefaultEncoder::class, $encoderDef->getClass()); diff --git a/Tests/Encoder/DefaultEncoderTest.php b/Tests/Encoder/DefaultEncoderTest.php index c9d44311..d2c8a8e1 100644 --- a/Tests/Encoder/DefaultEncoderTest.php +++ b/Tests/Encoder/DefaultEncoderTest.php @@ -26,10 +26,10 @@ public function testDecodeFromValidJWS() { $payload = [ 'username' => 'chalasr', - 'exp' => time() + 3600, + 'exp' => time() + 3600, ]; - $loadedJWS = new LoadedJWS($payload, true); + $loadedJWS = new LoadedJWS($payload, true); $jwsProvider = $this->getJWSProviderMock(); $jwsProvider ->expects($this->once()) @@ -46,7 +46,7 @@ public function testDecodeFromValidJWS() */ public function testEncodeFromValidJWS() { - $createdJWS = new CreatedJWS('jwt', true); + $createdJWS = new CreatedJWS('jwt', true); $jwsProvider = $this->getJWSProviderMock(); $jwsProvider ->expects($this->once()) @@ -99,7 +99,7 @@ public function testDecodeFromExpiredPayload() $this->expectException(JWTDecodeFailureException::class); $this->expectExceptionMessage('Expired JWT Token'); - $loadedJWS = new LoadedJWS(['exp' => time() - 3600], true); + $loadedJWS = new LoadedJWS(['exp' => time() - 3600], true); $jwsProvider = $this->getJWSProviderMock(); $jwsProvider ->expects($this->once()) @@ -118,7 +118,7 @@ public function testDecodeWithInvalidIssudAtClaimInPayload() $this->expectException(JWTDecodeFailureException::class); $this->expectExceptionMessage('Invalid JWT Token'); - $loadedJWS = new LoadedJWS(['exp' => time() + 3600, 'iat' => time() + 3600], true); + $loadedJWS = new LoadedJWS(['exp' => time() + 3600, 'iat' => time() + 3600], true); $jwsProvider = $this->getJWSProviderMock(); $jwsProvider ->expects($this->once()) diff --git a/Tests/Functional/Bundle/Controller/TestController.php b/Tests/Functional/Bundle/Controller/TestController.php index 4a5f6900..c097ec48 100644 --- a/Tests/Functional/Bundle/Controller/TestController.php +++ b/Tests/Functional/Bundle/Controller/TestController.php @@ -2,9 +2,7 @@ namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Functional\Bundle\Controller; -use Lexik\Bundle\JWTAuthenticationBundle\Tests\Stubs\User; use Symfony\Component\HttpFoundation\JsonResponse; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\User\UserInterface; class TestController @@ -12,8 +10,8 @@ class TestController public function securedAction(UserInterface $user) { return new JsonResponse([ - 'class' => get_class($user), - 'roles' => $user->getRoles(), + 'class' => get_class($user), + 'roles' => $user->getRoles(), 'username' => $user->getUsername(), ]); } diff --git a/Tests/Functional/CompleteTokenAuthenticationTest.php b/Tests/Functional/CompleteTokenAuthenticationTest.php index d251c356..72550ca1 100644 --- a/Tests/Functional/CompleteTokenAuthenticationTest.php +++ b/Tests/Functional/CompleteTokenAuthenticationTest.php @@ -27,7 +27,7 @@ public function testAccessSecuredRoute() static::accessSecuredRoute(); $response = static::$client->getResponse(); - $content = json_decode($response->getContent(), true); + $content = json_decode($response->getContent(), true); $this->assertSuccessful($response); diff --git a/Tests/Functional/GetTokenTest.php b/Tests/Functional/GetTokenTest.php index 7efc16e6..cf1b7b7d 100644 --- a/Tests/Functional/GetTokenTest.php +++ b/Tests/Functional/GetTokenTest.php @@ -5,9 +5,9 @@ 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; use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTDecodedEvent; -use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent; use Lexik\Bundle\JWTAuthenticationBundle\Events; use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse; use Symfony\Component\HttpFoundation\Cookie; @@ -46,7 +46,7 @@ public function testGetTokenWithListener() }); static::$client->request('POST', '/login_check', ['_username' => 'lexik', '_password' => 'dummy']); - static::$client->request('GET', '/api/secured', [], [], [ 'HTTP_AUTHORIZATION' => "Bearer ".$this->getToken(static::$client->getResponse()) ]); + static::$client->request('GET', '/api/secured', [], [], ['HTTP_AUTHORIZATION' => 'Bearer '.$this->getToken(static::$client->getResponse())]); $this->assertArrayHasKey('added_data', $payloadTested->payload, 'The payload should contains a "added_data" claim.'); $this->assertSame('still visible after the event', $payloadTested->payload['added_data'], 'The "added_data" claim should be equal to "still visible after the event".'); @@ -105,6 +105,7 @@ private function getToken(Response $response) $cookies = $response->headers->getCookies(); if (isset($cookies[0]) && 'token' === $cookies[0]->getName()) { $this->assertSame(Cookie::SAMESITE_STRICT, $cookies[0]->getSameSite()); + return $cookies[0]->getValue(); } diff --git a/Tests/Functional/TestCase.php b/Tests/Functional/TestCase.php index ed010a25..0bc456f7 100644 --- a/Tests/Functional/TestCase.php +++ b/Tests/Functional/TestCase.php @@ -31,7 +31,7 @@ protected static function createAuthenticatedClient($token = null) } $client = static::$kernel->getContainer()->get('test.client'); - $token = null === $token ? self::getAuthenticatedToken() : $token; + $token = null === $token ? self::getAuthenticatedToken() : $token; if (null === $token) { throw new \LogicException('Unable to create an authenticated client from a null JWT token'); diff --git a/Tests/Functional/Utils/CallableEventSubscriber.php b/Tests/Functional/Utils/CallableEventSubscriber.php index d926fdf9..79153457 100644 --- a/Tests/Functional/Utils/CallableEventSubscriber.php +++ b/Tests/Functional/Utils/CallableEventSubscriber.php @@ -15,16 +15,16 @@ class CallableEventSubscriber implements EventSubscriberInterface { - private static $listeners = []; + private static $listeners = []; private static $eventClassMap = [ - Events::JWT_CREATED => JWTCreatedEvent::class, - Events::JWT_DECODED => JWTDecodedEvent::class, - Events::JWT_INVALID => JWTInvalidEvent::class, - Events::JWT_NOT_FOUND => JWTNotFoundEvent::class, - Events::JWT_ENCODED => JWTEncodedEvent::class, + Events::JWT_CREATED => JWTCreatedEvent::class, + Events::JWT_DECODED => JWTDecodedEvent::class, + Events::JWT_INVALID => JWTInvalidEvent::class, + Events::JWT_NOT_FOUND => JWTNotFoundEvent::class, + Events::JWT_ENCODED => JWTEncodedEvent::class, Events::JWT_AUTHENTICATED => JWTAuthenticatedEvent::class, - Events::JWT_EXPIRED => JWTExpiredEvent::class, + Events::JWT_EXPIRED => JWTExpiredEvent::class, ]; public static function getSubscribedEvents() @@ -42,7 +42,7 @@ public static function getSubscribedEvents() * Executes the good listener depending on the passed event. * * @param object $event An instance of one of the events - * defined in {@link self::$eventClassMap} + * defined in {@link self::$eventClassMap} */ public function handleEvent($event) { diff --git a/Tests/Functional/app/AppKernel.php b/Tests/Functional/app/AppKernel.php index dc5ea3ee..caaa1280 100644 --- a/Tests/Functional/app/AppKernel.php +++ b/Tests/Functional/app/AppKernel.php @@ -25,9 +25,9 @@ public function __construct($environment, $debug, $testCase = null) { parent::__construct($environment, $debug); - $this->testCase = $testCase; - $this->encoder = getenv('ENCODER') ?: 'default'; - $this->userProvider = getenv('PROVIDER') ?: 'in_memory'; + $this->testCase = $testCase; + $this->encoder = getenv('ENCODER') ?: 'default'; + $this->userProvider = getenv('PROVIDER') ?: 'in_memory'; $this->signatureAlgorithm = getenv('ALGORITHM'); } diff --git a/Tests/Response/JWTAuthenticationFailureResponseTest.php b/Tests/Response/JWTAuthenticationFailureResponseTest.php index e6e1e59d..40e01150 100644 --- a/Tests/Response/JWTAuthenticationFailureResponseTest.php +++ b/Tests/Response/JWTAuthenticationFailureResponseTest.php @@ -15,7 +15,7 @@ final class JWTAuthenticationFailureResponseTest extends TestCase public function testResponse() { $expected = [ - 'code' => 401, + 'code' => 401, 'message' => 'message', ]; diff --git a/Tests/Response/JWTAuthenticationSuccessResponseTest.php b/Tests/Response/JWTAuthenticationSuccessResponseTest.php index 26b562cd..5466a468 100644 --- a/Tests/Response/JWTAuthenticationSuccessResponseTest.php +++ b/Tests/Response/JWTAuthenticationSuccessResponseTest.php @@ -16,7 +16,7 @@ public function testResponse() { $data = [ 'username' => 'foobar', - 'email' => 'dev@lexik.fr', + 'email' => 'dev@lexik.fr', ]; $expected = ['token' => 'jwt'] + $data; $response = new JWTAuthenticationSuccessResponse($expected['token'], $data); diff --git a/Tests/Security/Authentication/Firewall/JWTListenerTest.php b/Tests/Security/Authentication/Firewall/JWTListenerTest.php index f502b847..028386cc 100644 --- a/Tests/Security/Authentication/Firewall/JWTListenerTest.php +++ b/Tests/Security/Authentication/Firewall/JWTListenerTest.php @@ -10,7 +10,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Component\Security\Http\Firewall\ListenerInterface; /** * JWTListenerTest. @@ -27,22 +26,19 @@ class JWTListenerTest extends TestCase */ public function testHandle() { - $handle = class_exists(RequestEvent::class) ? '__invoke' : 'handle'; - // no token extractor : should return void - $listener = new JWTListener($this->getTokenStorageMock(), $this->getAuthenticationManagerMock()); $listener->setDispatcher($this->getEventDispatcherMock()); - $this->assertNull($listener->$handle($this->getEvent())); + $this->assertNull($listener($this->getEvent())); // one token extractor with no result : should return void - $listener = new JWTListener($this->getTokenStorageMock(), $this->getAuthenticationManagerMock()); + $listener = new JWTListener($this->getTokenStorageMock(), $this->getAuthenticationManagerMock()); $dispatcher = $this->getEventDispatcherMock(); $this->expectEvent(Events::JWT_NOT_FOUND, JWTNotFoundEvent::class, $dispatcher); $listener->setDispatcher($dispatcher); $listener->addTokenExtractor($this->getAuthorizationHeaderTokenExtractorMock(false)); - $this->assertNull($listener->$handle($this->getEvent())); + $this->assertNull($listener($this->getEvent())); // request token found : should enter authentication process @@ -52,7 +48,7 @@ public function testHandle() $listener = new JWTListener($this->getTokenStorageMock(), $authenticationManager); $listener->setDispatcher($this->getEventDispatcherMock()); $listener->addTokenExtractor($this->getAuthorizationHeaderTokenExtractorMock('token')); - $listener->$handle($this->getEvent()); + $listener($this->getEvent()); // request token found : authentication fail @@ -66,7 +62,7 @@ public function testHandle() ->method('authenticate') ->will($this->throwException($invalidTokenException)); - $listener = new JWTListener($this->getTokenStorageMock(), $authenticationManager); + $listener = new JWTListener($this->getTokenStorageMock(), $authenticationManager); $dispatcher = $this->getEventDispatcherMock(); $this->expectEvent(Events::JWT_INVALID, JWTInvalidEvent::class, $dispatcher); @@ -79,7 +75,7 @@ public function testHandle() ->method('setResponse') ->with(new JWTAuthenticationFailureResponse($invalidTokenException->getMessage())); - $listener->$handle($event); + $listener($event); } /** @@ -135,7 +131,7 @@ protected function getEvent() ->getMock(); $event = $this - ->getMockBuilder(class_exists(RequestEvent::class) ? RequestEvent::class : 'Symfony\Component\HttpKernel\Event\GetResponseEvent') + ->getMockBuilder(RequestEvent::class) ->disableOriginalConstructor() ->getMock(); diff --git a/Tests/Security/Authentication/Provider/JWTProviderTest.php b/Tests/Security/Authentication/Provider/JWTProviderTest.php index d6685140..517318ba 100644 --- a/Tests/Security/Authentication/Provider/JWTProviderTest.php +++ b/Tests/Security/Authentication/Provider/JWTProviderTest.php @@ -52,7 +52,7 @@ public function testAuthenticateWithInvalidJWT() ->disableOriginalConstructor() ->getMock(); - $userProvider = $this->getUserProviderMock(); + $userProvider = $this->getUserProviderMock(); $eventDispatcher = $this->getEventDispatcherMock(); $jwtManager = $this->getJWTManagerMock(); @@ -73,7 +73,7 @@ public function testAuthenticateWithoutUsername() ->disableOriginalConstructor() ->getMock(); - $userProvider = $this->getUserProviderMock(); + $userProvider = $this->getUserProviderMock(); $eventDispatcher = $this->getEventDispatcherMock(); $jwtManager = $this->getJWTManagerMock(); diff --git a/Tests/Security/Guard/JWTTokenAuthenticatorTest.php b/Tests/Security/Guard/JWTTokenAuthenticatorTest.php index 8410e315..5629e84b 100644 --- a/Tests/Security/Guard/JWTTokenAuthenticatorTest.php +++ b/Tests/Security/Guard/JWTTokenAuthenticatorTest.php @@ -20,12 +20,11 @@ use Lexik\Bundle\JWTAuthenticationBundle\Tests\Stubs\User as AdvancedUserStub; use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface; use PHPUnit\Framework\TestCase; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\User\UserProviderInterface; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class JWTTokenAuthenticatorTest extends TestCase { @@ -101,9 +100,9 @@ public function testGetCredentialsReturnsNullWithoutToken() public function testGetUser() { $userIdClaim = 'sub'; - $payload = [$userIdClaim => 'lexik']; - $rawToken = 'token'; - $userRoles = ['ROLE_USER']; + $payload = [$userIdClaim => 'lexik']; + $rawToken = 'token'; + $userRoles = ['ROLE_USER']; $userStub = new AdvancedUserStub('lexik', 'password', 'user@gmail.com', $userRoles); @@ -161,7 +160,7 @@ public function testGetUserWithInvalidFirstArg() public function testGetUserWithInvalidUserThrowsException() { $userIdClaim = 'username'; - $payload = [$userIdClaim => 'lexik']; + $payload = [$userIdClaim => 'lexik']; $decodedToken = new PreAuthenticationJWTUserToken('rawToken'); $decodedToken->setPayload($payload); @@ -189,10 +188,10 @@ public function testGetUserWithInvalidUserThrowsException() public function testCreateAuthenticatedToken() { - $rawToken = 'token'; + $rawToken = 'token'; $userRoles = ['ROLE_USER']; - $payload = ['sub' => 'lexik']; - $userStub = new AdvancedUserStub('lexik', 'password', 'user@gmail.com', $userRoles); + $payload = ['sub' => 'lexik']; + $userStub = new AdvancedUserStub('lexik', 'password', 'user@gmail.com', $userRoles); $decodedToken = new PreAuthenticationJWTUserToken($rawToken); $decodedToken->setPayload($payload); @@ -248,7 +247,7 @@ public function testCreateAuthenticatedTokenThrowsExceptionIfNotPreAuthenticated public function testOnAuthenticationFailureWithInvalidToken() { - $authException = new InvalidTokenException(); + $authException = new InvalidTokenException(); $expectedResponse = new JWTAuthenticationFailureResponse('Invalid JWT Token'); $dispatcher = $this->getEventDispatcherMock(); @@ -269,7 +268,7 @@ public function testOnAuthenticationFailureWithInvalidToken() public function testStart() { - $authException = new MissingTokenException('JWT Token not found'); + $authException = new MissingTokenException('JWT Token not found'); $failureResponse = new JWTAuthenticationFailureResponse($authException->getMessageKey()); $dispatcher = $this->getEventDispatcherMock(); diff --git a/Tests/Security/Http/Authentication/AuthenticationFailureHandlerTest.php b/Tests/Security/Http/Authentication/AuthenticationFailureHandlerTest.php index 0a288547..b0155b18 100644 --- a/Tests/Security/Http/Authentication/AuthenticationFailureHandlerTest.php +++ b/Tests/Security/Http/Authentication/AuthenticationFailureHandlerTest.php @@ -25,9 +25,9 @@ public function testOnAuthenticationFailure() $authenticationException = $this->getAuthenticationException(); - $handler = new AuthenticationFailureHandler($dispatcher); + $handler = new AuthenticationFailureHandler($dispatcher); $response = $handler->onAuthenticationFailure($this->getRequest(), $authenticationException); - $content = json_decode($response->getContent(), true); + $content = json_decode($response->getContent(), true); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertEquals(401, $response->getStatusCode()); diff --git a/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php b/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php index 76116ea7..44150c11 100644 --- a/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php +++ b/Tests/Security/Http/Authentication/AuthenticationSuccessHandlerTest.php @@ -23,7 +23,7 @@ class AuthenticationSuccessHandlerTest extends TestCase public function testOnAuthenticationSuccess() { $request = $this->getRequest(); - $token = $this->getToken(); + $token = $this->getToken(); $response = (new AuthenticationSuccessHandler($this->getJWTManager('secrettoken'), $this->getDispatcher())) ->onAuthenticationSuccess($request, $token); @@ -65,7 +65,7 @@ public function testHandleAuthenticationSuccessWithGivenJWT() public function testOnAuthenticationSuccessSetCookie() { $request = $this->getRequest(); - $token = $this->getToken(); + $token = $this->getToken(); $cookieProvider = new JWTCookieProvider('access_token', 60); @@ -84,7 +84,7 @@ public function testOnAuthenticationSuccessSetCookie() public function testOnAuthenticationSuccessSetSplitCookie() { $request = $this->getRequest(); - $token = $this->getToken(); + $token = $this->getToken(); $headerPayloadCookieProvider = new JWTCookieProvider('jwt_hp', 60, null, null, null, true, false, ['header', 'payload']); $signatureCookieProvider = new JWTCookieProvider('jwt_s', 60, null, null, null, true, true, ['signature']); diff --git a/Tests/Security/User/JWTUserProviderTest.php b/Tests/Security/User/JWTUserProviderTest.php index e103ee92..255138ba 100644 --- a/Tests/Security/User/JWTUserProviderTest.php +++ b/Tests/Security/User/JWTUserProviderTest.php @@ -29,7 +29,7 @@ public function testSupportsClass() public function testLoadUserByUsername() { $userProvider = new JWTUserProvider(JWTUser::class); - $user = $userProvider->loadUserByUsername('lexik'); + $user = $userProvider->loadUserByUsername('lexik'); $this->assertInstanceOf(JWTUser::class, $user); $this->assertSame('lexik', $user->getUsername()); diff --git a/Tests/Services/JWSProvider/AbstractJWSProviderTest.php b/Tests/Services/JWSProvider/AbstractJWSProviderTest.php index 08aba1c3..fd232dc9 100644 --- a/Tests/Services/JWSProvider/AbstractJWSProviderTest.php +++ b/Tests/Services/JWSProvider/AbstractJWSProviderTest.php @@ -2,7 +2,6 @@ namespace Lexik\Bundle\JWTAuthenticationBundle\Tests\Services\JWSProvider; -use Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProvider\LcobucciJWSProvider; use Lexik\Bundle\JWTAuthenticationBundle\Signature\CreatedJWS; use Lexik\Bundle\JWTAuthenticationBundle\Signature\LoadedJWS; use PHPUnit\Framework\TestCase; @@ -79,7 +78,7 @@ public function testCreate() ->method('getPassphrase') ->willReturn('foobar'); - $payload = ['username' => 'chalasr']; + $payload = ['username' => 'chalasr']; $jwsProvider = new static::$providerClass($keyLoaderMock, 'openssl', 'RS384', 3600, 0); $this->assertInstanceOf(CreatedJWS::class, $created = $jwsProvider->create($payload)); @@ -102,7 +101,7 @@ public function testLoad($jwt) ->willReturn(static::$publicKey); $jwsProvider = new static::$providerClass($keyLoaderMock, 'openssl', 'RS384', 3600, 0); - $loadedJWS = $jwsProvider->load($jwt); + $loadedJWS = $jwsProvider->load($jwt); $this->assertInstanceOf(LoadedJWS::class, $loadedJWS); $payload = $loadedJWS->getPayload(); @@ -131,7 +130,7 @@ public function testAllowEmptyTtl() static::$publicKey ); $provider = new static::$providerClass($keyLoader, 'openssl', 'RS256', null, 0); - $jws = $provider->create(['username' => 'chalasr']); + $jws = $provider->create(['username' => 'chalasr']); $this->assertInstanceOf(CreatedJWS::class, $jws); $this->assertTrue($jws->isSigned()); @@ -166,7 +165,7 @@ public function testCreateWithExtraStandardClaims() ->method('getPassphrase') ->willReturn('foobar'); - $payload = ['username' => 'chalasr']; + $payload = ['username' => 'chalasr']; $jwsProvider = new static::$providerClass($keyLoaderMock, 'openssl', 'RS384', 3600, 0); $this->assertInstanceOf(CreatedJWS::class, $created = $jwsProvider->create($payload)); diff --git a/Tests/Services/JWSProvider/DefaultJWSProviderTest.php b/Tests/Services/JWSProvider/DefaultJWSProviderTest.php index a68f85a5..15ebfac7 100644 --- a/Tests/Services/JWSProvider/DefaultJWSProviderTest.php +++ b/Tests/Services/JWSProvider/DefaultJWSProviderTest.php @@ -14,6 +14,6 @@ */ final class DefaultJWSProviderTest extends AbstractJWSProviderTest { - protected static $providerClass = DefaultJWSProvider::class; + protected static $providerClass = DefaultJWSProvider::class; protected static $keyLoaderClass = KeyLoaderInterface::class; } diff --git a/Tests/Services/JWSProvider/LcobucciJWSProviderTest.php b/Tests/Services/JWSProvider/LcobucciJWSProviderTest.php index 07e0880b..93504a97 100644 --- a/Tests/Services/JWSProvider/LcobucciJWSProviderTest.php +++ b/Tests/Services/JWSProvider/LcobucciJWSProviderTest.php @@ -12,6 +12,6 @@ */ final class LcobucciJWSProviderTest extends AbstractJWSProviderTest { - protected static $providerClass = LcobucciJWSProvider::class; + protected static $providerClass = LcobucciJWSProvider::class; protected static $keyLoaderClass = RawKeyLoader::class; } diff --git a/Tests/Services/JWTManagerTest.php b/Tests/Services/JWTManagerTest.php index 0092aeaf..bc4b2214 100644 --- a/Tests/Services/JWTManagerTest.php +++ b/Tests/Services/JWTManagerTest.php @@ -8,7 +8,6 @@ use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTManager; use Lexik\Bundle\JWTAuthenticationBundle\Tests\Stubs\User as CustomUser; use PHPUnit\Framework\TestCase; -use Symfony\Contracts\EventDispatcher\Event; use Symfony\Component\Security\Core\User\User; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; diff --git a/Tests/Services/KeyLoader/AbstractTestKeyLoader.php b/Tests/Services/KeyLoader/AbstractTestKeyLoader.php index 16cba3dd..15065f9a 100644 --- a/Tests/Services/KeyLoader/AbstractTestKeyLoader.php +++ b/Tests/Services/KeyLoader/AbstractTestKeyLoader.php @@ -50,7 +50,7 @@ public function doTearDown() protected function removeKeysIfExist() { $privateKey = 'private.pem'; - $publicKey = 'public.pem'; + $publicKey = 'public.pem'; if (file_exists($publicKey)) { unlink($publicKey); diff --git a/Tests/Signature/LoadedJWSTest.php b/Tests/Signature/LoadedJWSTest.php index f5d3306b..953802e1 100644 --- a/Tests/Signature/LoadedJWSTest.php +++ b/Tests/Signature/LoadedJWSTest.php @@ -9,6 +9,7 @@ /** * Tests the CreatedJWS model class. + * * @group time-sensitive */ final class LoadedJWSTest extends TestCase @@ -24,8 +25,8 @@ protected function doSetUp() { $this->goodPayload = [ 'username' => 'chalasr', - 'exp' => time() + 3600, - 'iat' => time(), + 'exp' => time() + 3600, + 'iat' => time(), ]; } @@ -110,8 +111,8 @@ public function testIsNotExpiredDaySavingTransition() $dstPayload = [ 'username' => 'test', - 'exp' => $timestamp + 3600, - 'iat' => $timestamp, + 'exp' => $timestamp + 3600, + 'iat' => $timestamp, ]; $jws = new LoadedJWS($dstPayload, true); diff --git a/Tests/Stubs/User.php b/Tests/Stubs/User.php index 226e448b..f3cdfa88 100644 --- a/Tests/Stubs/User.php +++ b/Tests/Stubs/User.php @@ -33,10 +33,10 @@ public function __construct($username, $password, $email = '', array $roles = [] throw new \InvalidArgumentException('The username cannot be empty.'); } - $this->username = $username; - $this->password = $password; - $this->roles = $roles; - $this->email = $email; + $this->username = $username; + $this->password = $password; + $this->roles = $roles; + $this->email = $email; } /** @@ -76,10 +76,12 @@ public function getUsername() public function eraseCredentials() { } + public function getEmail() { return $this->email; } + public function setEmail($email) { $this->email = $email; diff --git a/Tests/TokenExtractor/ChainTokenExtractorTest.php b/Tests/TokenExtractor/ChainTokenExtractorTest.php index e714410d..b5401029 100644 --- a/Tests/TokenExtractor/ChainTokenExtractorTest.php +++ b/Tests/TokenExtractor/ChainTokenExtractorTest.php @@ -26,7 +26,7 @@ public function testGetIterator() public function testAddExtractor() { $extractor = new ChainTokenExtractor($this->getTokenExtractorMap()); - $custom = $this->getTokenExtractorMock(null); + $custom = $this->getTokenExtractorMock(null); $extractor->addExtractor($custom); $map = []; @@ -41,7 +41,7 @@ public function testAddExtractor() public function testRemoveExtractor() { $extractor = new ChainTokenExtractor([]); - $custom = $this->getTokenExtractorMock(null); + $custom = $this->getTokenExtractorMock(null); $extractor->addExtractor($custom); $result = $extractor->removeExtractor(function (TokenExtractorInterface $extractor) use ($custom) { diff --git a/TokenExtractor/AuthorizationHeaderTokenExtractor.php b/TokenExtractor/AuthorizationHeaderTokenExtractor.php index b704f245..6c317dd0 100644 --- a/TokenExtractor/AuthorizationHeaderTokenExtractor.php +++ b/TokenExtractor/AuthorizationHeaderTokenExtractor.php @@ -28,7 +28,7 @@ class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface public function __construct($prefix, $name) { $this->prefix = $prefix; - $this->name = $name; + $this->name = $name; } /** diff --git a/TokenExtractor/ChainTokenExtractor.php b/TokenExtractor/ChainTokenExtractor.php index a552d121..0be4b37b 100644 --- a/TokenExtractor/ChainTokenExtractor.php +++ b/TokenExtractor/ChainTokenExtractor.php @@ -20,9 +20,6 @@ class ChainTokenExtractor implements \IteratorAggregate, TokenExtractorInterface */ private $map; - /** - * @param array $map - */ public function __construct(array $map) { $this->map = $map; @@ -30,8 +27,6 @@ public function __construct(array $map) /** * Adds a new token extractor to the map. - * - * @param TokenExtractorInterface $extractor */ public function addExtractor(TokenExtractorInterface $extractor) { @@ -41,7 +36,7 @@ public function addExtractor(TokenExtractorInterface $extractor) /** * Removes a token extractor from the map. * - * @param Closure $filter A function taking an extractor as argument, + * @param \Closure $filter A function taking an extractor as argument, * used to find the extractor to remove, * * @return bool True in case of success, false otherwise diff --git a/TokenExtractor/SplitCookieExtractor.php b/TokenExtractor/SplitCookieExtractor.php index f00ee997..f2bfff36 100644 --- a/TokenExtractor/SplitCookieExtractor.php +++ b/TokenExtractor/SplitCookieExtractor.php @@ -11,7 +11,6 @@ */ class SplitCookieExtractor implements TokenExtractorInterface { - /** * @var array */ @@ -26,7 +25,7 @@ public function __construct($cookies) } /** - * @inheritDoc + * {@inheritDoc} */ public function extract(Request $request) { diff --git a/TokenExtractor/TokenExtractorInterface.php b/TokenExtractor/TokenExtractorInterface.php index de168cbe..861d3035 100644 --- a/TokenExtractor/TokenExtractorInterface.php +++ b/TokenExtractor/TokenExtractorInterface.php @@ -12,8 +12,6 @@ interface TokenExtractorInterface { /** - * @param Request $request - * * @return string|false */ public function extract(Request $request); diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..e83e6477 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,4 @@ +parameters: + excludes_analyse: + - vendor/* + - Tests/*