From 436615212d426887456f0c133d81ad81f7035e45 Mon Sep 17 00:00:00 2001 From: ELMAKHROUBI ABDELLAH Date: Wed, 10 Nov 2021 15:54:50 +0100 Subject: [PATCH 1/5] use the new authenticator system introduced since 5.3 --- .../KeycloakBearerAuthenticator.php | 235 +++--------------- Security/User/KeycloakBearerUserProvider.php | 89 +++---- composer.json | 2 +- 3 files changed, 87 insertions(+), 239 deletions(-) diff --git a/Security/Authenticator/KeycloakBearerAuthenticator.php b/Security/Authenticator/KeycloakBearerAuthenticator.php index 5be65c5..ab09105 100644 --- a/Security/Authenticator/KeycloakBearerAuthenticator.php +++ b/Security/Authenticator/KeycloakBearerAuthenticator.php @@ -3,207 +3,20 @@ namespace ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\Authenticator; -use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; -use Symfony\Component\Security\Core\Exception\BadCredentialsException; -use Symfony\Component\Security\Core\User\UserInterface; -use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Guard\AbstractGuardAuthenticator; +use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException; +use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator; +use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; +use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface; +use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; -class KeycloakBearerAuthenticator extends AbstractGuardAuthenticator +class KeycloakBearerAuthenticator extends AbstractAuthenticator { - /** - * Returns a response that directs the user to authenticate. - * - * This is called when an anonymous request accesses a resource that - * requires authentication. The job of this method is to return some - * response that "helps" the user start into the authentication process. - * - * Examples: - * - * - For a form login, you might redirect to the login page - * - * return new RedirectResponse('/login'); - * - * - For an API token authentication system, you return a 401 response - * - * return new Response('Auth header required', 401); - * - * @param Request $request The request that resulted in an AuthenticationException - * @param AuthenticationException|null $authException The exception that started the authentication process - * - * @return JsonResponse - */ - public function start(Request $request, AuthenticationException $authException = null) - { - $data = [ - // you might translate this message - 'message' => 'Auth header required' - ]; - - return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); - } - - /** - * Does the authenticator support the given Request? - * - * If this returns false, the authenticator will be skipped. - * - * @param Request $request - * - * @return bool - */ - public function supports(Request $request) - { - return !empty($request->headers->get('Authorization')); - } - - /** - * Get the authentication credentials from the request and return them - * as any type (e.g. an associate array). - * - * Whatever value you return here will be passed to getUser() and checkCredentials() - * - * For example, for a form login, you might: - * - * return [ - * 'username' => $request->request->get('_username'), - * 'password' => $request->request->get('_password'), - * ]; - * - * Or for an API token that's on a header, you might use: - * - * return ['api_key' => $request->headers->get('X-API-TOKEN')]; - * - * @param Request $request - * - * @return mixed Any non-null value - * - * @throws \UnexpectedValueException If null is returned - */ - public function getCredentials(Request $request) - { - return [ - 'token' => $request->headers->get('Authorization'), - ]; - } - - /** - * Return a UserInterface object based on the credentials. - * - * The *credentials* are the return value from getCredentials() - * - * You may throw an AuthenticationException if you wish. If you return - * null, then a UsernameNotFoundException is thrown for you. - * - * @param mixed $credentials - * @param UserProviderInterface $userProvider - * - * @throws AuthenticationException - * - * @return UserInterface|null - */ - public function getUser($credentials, UserProviderInterface $userProvider) - { - $token = $credentials['token']; - - if (!$token) { - throw new BadCredentialsException('Token is not present in the request headers'); - } - - try { - $user = $userProvider->loadUserByUsername($this->formatToken($token)); - } catch (\Exception $e) { - throw new BadCredentialsException(sprintf('Error when introspecting the token: %s', $e->getMessage())); - } - - return $user; - - } - - /** - * Returns true if the credentials are valid. - * - * If any value other than true is returned, authentication will - * fail. You may also throw an AuthenticationException if you wish - * to cause authentication to fail. - * - * The *credentials* are the return value from getCredentials() - * - * @param mixed $credentials - * @param UserInterface $user - * - * @return bool - * - * @throws AuthenticationException - */ - public function checkCredentials($credentials, UserInterface $user) - { - return true; - } - - /** - * Called when authentication executed, but failed (e.g. wrong username password). - * - * This should return the Response sent back to the user, like a - * RedirectResponse to the login page or a 403 response. - * - * If you return null, the request will continue, but the user will - * not be authenticated. This is probably not what you want to do. - * - * @param Request $request - * @param AuthenticationException $exception - * - * @return Response|null - */ - public function onAuthenticationFailure(Request $request, AuthenticationException $exception) - { - return new JsonResponse(['error' => $exception->getMessage()], Response::HTTP_FORBIDDEN); - } - - /** - * Called when authentication executed and was successful! - * - * This should return the Response sent back to the user, like a - * RedirectResponse to the last page they visited. - * - * If you return null, the current request will continue, and the user - * will be authenticated. This makes sense, for example, with an API. - * - * @param Request $request - * @param TokenInterface $token - * @param string $providerKey The provider (i.e. firewall) key - * - * @return Response|null - */ - public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) - { - return null; - } - - /** - * Does this method support remember me cookies? - * - * Remember me cookie will be set if *all* of the following are met: - * A) This method returns true - * B) The remember_me key under your firewall is configured - * C) The "remember me" functionality is activated. This is usually - * done by having a _remember_me checkbox in your form, but - * can be configured by the "always_remember_me" and "remember_me_parameter" - * parameters under the "remember_me" firewall key - * D) The onAuthenticationSuccess method returns a Response object - * - * @return bool - */ - public function supportsRememberMe() - { - return false; - } - /** * @param string $token * @return string @@ -212,4 +25,38 @@ class KeycloakBearerAuthenticator extends AbstractGuardAuthenticator { return trim(preg_replace('/^(?:\s+)?[B-b]earer\s/', '', $token)); } + + public function supports(Request $request): ?bool + { + return $request->headers->has('Authorization'); + } + + public function authenticate(Request $request): PassportInterface + { + $token = $request->headers->get('Authorization'); + if (null === $token) { + // The token header was empty, authentication fails with HTTP Status + // Code 401 "Unauthorized" + throw new CustomUserMessageAuthenticationException('Token is not present in the request headers'); + } + + return new SelfValidatingPassport(new UserBadge($this->formatToken($token))); + } + + public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response + { + return null; + } + + public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response + { + $data = [ + // you may want to customize or obfuscate the message first + 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()) + // or to translate this message + // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData()) + ]; + + return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); + } } diff --git a/Security/User/KeycloakBearerUserProvider.php b/Security/User/KeycloakBearerUserProvider.php index 1391d97..4ce7c17 100644 --- a/Security/User/KeycloakBearerUserProvider.php +++ b/Security/User/KeycloakBearerUserProvider.php @@ -6,12 +6,13 @@ namespace ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\User; use GuzzleHttp\Client; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; -use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; +use Symfony\Component\Security\Core\Exception\UserNotFoundException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; -class KeycloakBearerUserProvider implements UserProviderInterface -{ + +class KeycloakBearerUserProvider implements UserProviderInterface{ + /** * @var string */ @@ -50,18 +51,49 @@ class KeycloakBearerUserProvider implements UserProviderInterface } /** - * Loads the user for the given username. + * Refreshes the user after being reloaded from the session. * - * This method must throw UsernameNotFoundException if the user is not - * found. + * When a user is logged in, at the beginning of each request, the + * User object is loaded from the session and then this method is + * called. Your job is to make sure the user's data is still fresh by, + * for example, re-querying for fresh User data. * - * @param string $accessToken The username + * If your firewall is "stateless: true" (for a pure API, which is our case), this + * method is not called. But it is implement it anyway. * * @return UserInterface - * - * @throws UsernameNotFoundException if the user is not found */ - public function loadUserByUsername($accessToken) + public function refreshUser(UserInterface $user): UserInterface + { + if (!$user instanceof KeycloakBearerUser) { + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); + } + + $user = $this->loadUserByIdentifier($user->getAccessToken()); + + if (!$user) { + throw new UserNotFoundException(); + } + + return $user; + } + + /** + * @param string $class + * @return bool + */ + public function supportsClass(string $class) + { + return KeycloakBearerUser::class === $class || is_subclass_of(KeycloakBearerUser, User::class); + } + + + + /** + * @param string $accessToken + * @return UserInterface + */ + public function loadUserByIdentifier(string $accessToken): UserInterface { $client = new Client([ 'base_uri' => $this->issuer, @@ -103,42 +135,11 @@ class KeycloakBearerUserProvider implements UserProviderInterface } /** - * Refreshes the user. - * - * It is up to the implementation to decide if the user data should be - * totally reloaded (e.g. from the database), or if the UserInterface - * object can just be merged into some internal array of users / identity - * map. - * + * @param string $username * @return UserInterface - * - * @throws UnsupportedUserException if the user is not supported - * @throws UsernameNotFoundException if the user is not found */ - public function refreshUser(UserInterface $user) + public function loadUserByUsername(string $username): UserInterface { - if (!$user instanceof KeycloakBearerUser) { - throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); - } - - $user = $this->loadUserByUsername($user->getAccessToken()); - - if (!$user) { - throw new UsernameNotFoundException(); - } - - return $user; - } - - /** - * Whether this provider supports the given user class. - * - * @param string $class - * - * @return bool - */ - public function supportsClass($class) - { - return KeycloakBearerUser::class === $class; + return $this->loadUserByIdentifier($username); } } \ No newline at end of file diff --git a/composer.json b/composer.json index da358d6..86c5bc7 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ ], "minimum-stability": "stable", "require": { - "php": "^7.2.5|^8.0", + "php": ">=7.2.5", "symfony/config": "^5.0", "symfony/dependency-injection": "^5.0", "symfony/http-kernel": "^5.0", From 9e2b3efc80eeded3923a1c97d8a60774e043137d Mon Sep 17 00:00:00 2001 From: ELMAKHROUBI ABDELLAH Date: Wed, 10 Nov 2021 16:46:26 +0100 Subject: [PATCH 2/5] update config of security.yml --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a5bb9ab..529b058 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ Here is a simple configuration that restrict access to ```/api/*``` routes only ```yaml # config/packages/security.yaml security: + enable_authenticator_manager: true providers: keycloak_bearer_user_provider: id: ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\User\KeycloakBearerUserProvider @@ -68,13 +69,10 @@ security: security: false api: pattern: ^/api/ - guard: - provider: keycloak_bearer_user_provider - authenticators: - - ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\Authenticator\KeycloakBearerAuthenticator + provider: keycloak_bearer_user_provider + custom_authenticators: + - ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\Authenticator\KeycloakBearerAuthenticator stateless: true - main: - anonymous: ~ access_control: - { path: ^/api/, roles: ROLE_API } ``` From d99f4434ebff9c9ef42fd45b7712af535a14f82d Mon Sep 17 00:00:00 2001 From: Abdellah elmakhroubi Date: Wed, 10 Nov 2021 16:46:26 +0100 Subject: [PATCH 3/5] update config of security.yml --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a5bb9ab..529b058 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ Here is a simple configuration that restrict access to ```/api/*``` routes only ```yaml # config/packages/security.yaml security: + enable_authenticator_manager: true providers: keycloak_bearer_user_provider: id: ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\User\KeycloakBearerUserProvider @@ -68,13 +69,10 @@ security: security: false api: pattern: ^/api/ - guard: - provider: keycloak_bearer_user_provider - authenticators: - - ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\Authenticator\KeycloakBearerAuthenticator + provider: keycloak_bearer_user_provider + custom_authenticators: + - ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\Authenticator\KeycloakBearerAuthenticator stateless: true - main: - anonymous: ~ access_control: - { path: ^/api/, roles: ROLE_API } ``` From 4b6ba3e6615e593d24409c2a0d085bf4689108b2 Mon Sep 17 00:00:00 2001 From: ELMAKHROUBI ABDELLAH Date: Wed, 10 Nov 2021 17:05:56 +0100 Subject: [PATCH 4/5] update readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 529b058..612c024 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,12 @@ The best practice is to load your configuration from **.env** file. ``` # .env ... -###> Keycloak ### +###> Abel_keycloak_bearer_only_adapter ### OAUTH_KEYCLOAK_ISSUER=http://keycloak.local:8080 OAUTH_KEYCLOAK_REALM=my_realm OAUTH_KEYCLOAK_CLIENT_ID=my_bearer_client OAUTH_KEYCLOAK_CLIENT_SECRET=my_bearer_client_secret -###< Keycloak ### +###< Abel_keycloak_bearer_only_adapter ### ... ``` From 670a76807cfdc402c92669e206221b39b1a21556 Mon Sep 17 00:00:00 2001 From: "El. Abdellah" Date: Thu, 11 Nov 2021 14:42:02 +0100 Subject: [PATCH 5/5] refactor deprecated methodes --- Security/Authenticator/KeycloakBearerAuthenticator.php | 4 ++-- Security/User/KeycloakBearerUser.php | 10 +++++++++- Security/User/KeycloakBearerUserProvider.php | 7 ++++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Security/Authenticator/KeycloakBearerAuthenticator.php b/Security/Authenticator/KeycloakBearerAuthenticator.php index ab09105..e75d96a 100644 --- a/Security/Authenticator/KeycloakBearerAuthenticator.php +++ b/Security/Authenticator/KeycloakBearerAuthenticator.php @@ -28,13 +28,13 @@ class KeycloakBearerAuthenticator extends AbstractAuthenticator public function supports(Request $request): ?bool { - return $request->headers->has('Authorization'); + return true; } public function authenticate(Request $request): PassportInterface { $token = $request->headers->get('Authorization'); - if (null === $token) { + if (null === $token || empty($token)) { // The token header was empty, authentication fails with HTTP Status // Code 401 "Unauthorized" throw new CustomUserMessageAuthenticationException('Token is not present in the request headers'); diff --git a/Security/User/KeycloakBearerUser.php b/Security/User/KeycloakBearerUser.php index e8089ed..84eca85 100644 --- a/Security/User/KeycloakBearerUser.php +++ b/Security/User/KeycloakBearerUser.php @@ -245,6 +245,14 @@ class KeycloakBearerUser implements UserInterface, \Serializable return $this->preferred_username; } + /** + * @return string + */ + public function getUserIdentifier(): string + { + return $this->preferred_username; + } + /** * Removes sensitive data from the user. * @@ -298,4 +306,4 @@ class KeycloakBearerUser implements UserInterface, \Serializable $this->accessToken ) = unserialize($serialized, ['allowed_classes' => false]); } -} \ No newline at end of file +} diff --git a/Security/User/KeycloakBearerUserProvider.php b/Security/User/KeycloakBearerUserProvider.php index 4ce7c17..700b888 100644 --- a/Security/User/KeycloakBearerUserProvider.php +++ b/Security/User/KeycloakBearerUserProvider.php @@ -5,6 +5,7 @@ namespace ABEL\Bundle\keycloakBearerOnlyAdapterBundle\Security\User; use GuzzleHttp\Client; +use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UserNotFoundException; use Symfony\Component\Security\Core\User\UserInterface; @@ -115,11 +116,11 @@ class KeycloakBearerUserProvider implements UserProviderInterface{ $jwt = json_decode($response->getBody(), true); if (!$jwt['active']) { - throw new \UnexpectedValueException('The token does not exist or is not valid anymore'); + throw new CustomUserMessageAuthenticationException('The token does not exist or is not valid anymore'); } if (!isset($jwt['resource_access'][$this->client_id])) { - throw new \UnexpectedValueException('The token does not have the necessary permissions!'); + throw new CustomUserMessageAuthenticationException('The token does not have the necessary permissions!'); } return new KeycloakBearerUser( @@ -142,4 +143,4 @@ class KeycloakBearerUserProvider implements UserProviderInterface{ { return $this->loadUserByIdentifier($username); } -} \ No newline at end of file +}