Skip to content

Commit 8bafd7e

Browse files
committed
Fix: catch exception on refresh user
1 parent aa615e0 commit 8bafd7e

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

Security/User/KeycloakBearerUserProvider.php

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
88
use KnpU\OAuth2ClientBundle\Client\OAuth2Client;
99
use KnpU\OAuth2ClientBundle\Security\User\OAuthUserProvider;
10+
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
1011
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
1112
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
1213
use Symfony\Component\Security\Core\User\UserInterface;
@@ -37,9 +38,7 @@ public function loadUserByUsername($accessToken): UserInterface
3738
$provider = $this->getKeycloakClient()->getOAuth2Provider();
3839

3940
if (!$provider instanceof Keycloak) {
40-
throw new \RuntimeException(
41-
sprintf('The OAuth2 client provider must be an instance of %s', Keycloak::class)
42-
);
41+
throw new \RuntimeException(sprintf('The OAuth2 client provider must be an instance of %s', Keycloak::class));
4342
}
4443

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

5958
if (!isset($jwt['resource_access'][$provider->getClientId()])) {
60-
throw new \UnexpectedValueException(sprintf(
61-
'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\'',
62-
$provider->getClientId(),
63-
$provider->realm,
64-
$jwt['username']
65-
));
59+
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']));
6660
}
6761

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

84-
$user = $this->loadUserByUsername($user->getAccessToken());
85-
86-
if (!$user) {
87-
throw new UsernameNotFoundException();
78+
try {
79+
$user = $this->loadUserByUsername($user->getAccessToken());
80+
} catch (\Exception $e) {
81+
throw new UsernameNotFoundException(sprintf('Error during token introspection: %s', $e->getMessage()));
8882
}
8983

9084
return $user;

0 commit comments

Comments
 (0)