Skip to content

Commit

Permalink
Fix: catch exception on refresh user
Browse files Browse the repository at this point in the history
  • Loading branch information
BeBlood committed Mar 28, 2023
1 parent aa615e0 commit 8bafd7e
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions Security/User/KeycloakBearerUserProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\OAuth2Client;
use KnpU\OAuth2ClientBundle\Security\User\OAuthUserProvider;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
Expand Down Expand Up @@ -37,9 +38,7 @@ public function loadUserByUsername($accessToken): UserInterface
$provider = $this->getKeycloakClient()->getOAuth2Provider();

if (!$provider instanceof Keycloak) {
throw new \RuntimeException(
sprintf('The OAuth2 client provider must be an instance of %s', Keycloak::class)
);
throw new \RuntimeException(sprintf('The OAuth2 client provider must be an instance of %s', Keycloak::class));
}

$response = (new Client())->request('POST', $provider->getTokenIntrospectionUrl(), [
Expand All @@ -57,12 +56,7 @@ public function loadUserByUsername($accessToken): UserInterface
}

if (!isset($jwt['resource_access'][$provider->getClientId()])) {
throw new \UnexpectedValueException(sprintf(
'The token does not have the necessary permissions. Configure roles in the client \'%s\' of the realm \'%s\' and associate them with the user \'%s\'',
$provider->getClientId(),
$provider->realm,
$jwt['username']
));
throw new \UnexpectedValueException(sprintf('The token does not have the necessary permissions. Configure roles in the client \'%s\' of the realm \'%s\' and associate them with the user \'%s\'', $provider->getClientId(), $provider->realm, $jwt['username']));
}

return (new KeycloakBearerUser($jwt['username'], $jwt['resource_access'][$provider->getClientId()]['roles']))
Expand All @@ -81,10 +75,10 @@ public function refreshUser(UserInterface $user): UserInterface
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}

$user = $this->loadUserByUsername($user->getAccessToken());

if (!$user) {
throw new UsernameNotFoundException();
try {
$user = $this->loadUserByUsername($user->getAccessToken());
} catch (\Exception $e) {
throw new UsernameNotFoundException(sprintf('Error during token introspection: %s', $e->getMessage()));
}

return $user;
Expand Down

0 comments on commit 8bafd7e

Please sign in to comment.