From 30d26d019ac2bdf8b657daac1d7e44905556a670 Mon Sep 17 00:00:00 2001 From: Florent Morselli Date: Sat, 27 Aug 2022 17:36:03 +0200 Subject: [PATCH] JWTHandler based on AccessTokenHandlerInterface --- .../LexikJWTAuthenticationExtension.php | 4 ++ Resources/config/access_token_handler.xml | 12 +++++ Security/AccessToken/JWTHandler.php | 47 +++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 Resources/config/access_token_handler.xml create mode 100644 Security/AccessToken/JWTHandler.php diff --git a/DependencyInjection/LexikJWTAuthenticationExtension.php b/DependencyInjection/LexikJWTAuthenticationExtension.php index 43d414e0..12a5e97f 100644 --- a/DependencyInjection/LexikJWTAuthenticationExtension.php +++ b/DependencyInjection/LexikJWTAuthenticationExtension.php @@ -13,6 +13,7 @@ use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpKernel\DependencyInjection\Extension; +use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface; /** * This is the class that loads and manages your bundle configuration. @@ -44,6 +45,9 @@ public function load(array $configs, ContainerBuilder $container) $loader->load('token_authenticator.xml'); $loader->load('token_extractor.xml'); $loader->load('guard_authenticator.xml'); + if (interface_exists(AccessTokenHandlerInterface::class)) { + $loader->load('access_token_handler.xml'); + } if (isset($config['private_key_path'])) { $config['secret_key'] = $config['private_key_path']; diff --git a/Resources/config/access_token_handler.xml b/Resources/config/access_token_handler.xml new file mode 100644 index 00000000..8d9cba7d --- /dev/null +++ b/Resources/config/access_token_handler.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/Security/AccessToken/JWTHandler.php b/Security/AccessToken/JWTHandler.php new file mode 100644 index 00000000..acff5881 --- /dev/null +++ b/Security/AccessToken/JWTHandler.php @@ -0,0 +1,47 @@ +jwtManager = $jwtManager; + } + + public function getUserIdentifierFrom(string $accessToken): string + { + + try { + if (!$payload = $this->jwtManager->parse($accessToken)) { + throw new AuthenticationException('Invalid JWT Token'); + } + } catch (\Throwable $e) { + throw new AuthenticationException('Invalid JWT Token', 0, $e); + } + + $idClaim = $this->jwtManager->getUserIdClaim(); + if (!isset($payload[$idClaim])) { + throw new AuthenticationException(sprintf('Unable to find key "%s" in the token payload.', $idClaim)); + } + if (!is_string($payload[$idClaim]) || $payload[$idClaim] === '') { + throw new AuthenticationException(sprintf('Invalid key "%s" in the token payload.', $idClaim)); + } + + return $payload[$idClaim]; + } +}