I want to log RegisteredClient.clientId
, RegisteredClient.clientName
when it performs successful client credentials flow. How can I achieve this?
Current Behavior
I checked logs (with TRACE level) when a client exchanges its application credentials, such as client ID and client secret, for an access token.
Below is a summary of what I get in the logs:
2025-02-26T12:31:25.511+06:00 TRACE 31608 --- [nio-9090-exec-1] o.s.s.authentication.ProviderManager : Authenticating request with ClientSecretAuthenticationProvider (3/20)
2025-02-26T12:31:25.515+06:00 TRACE 31608 --- [nio-9090-exec-1] s.a.a.ClientSecretAuthenticationProvider : Retrieved registered client
2025-02-26T12:31:25.592+06:00 TRACE 31608 --- [nio-9090-exec-1] s.a.a.ClientSecretAuthenticationProvider : Validated client authentication parameters
2025-02-26T12:31:25.593+06:00 TRACE 31608 --- [nio-9090-exec-1] s.a.a.ClientSecretAuthenticationProvider : Authenticated client secret
2025-02-26T12:31:25.593+06:00 DEBUG 31608 --- [nio-9090-exec-1] o.s.a.w.OAuth2ClientAuthenticationFilter : Set SecurityContextHolder authentication to OAuth2ClientAuthenticationToken
...
2025-02-26T12:31:25.593+06:00 TRACE 31608 --- [nio-9090-exec-1] o.s.security.web.FilterChainProxy : Invoking OAuth2TokenEndpointFilter (21/25)
2025-02-26T12:31:25.593+06:00 TRACE 31608 --- [nio-9090-exec-1] o.s.s.authentication.ProviderManager : Authenticating request with OAuth2ClientCredentialsAuthenticationProvider (1/20)
2025-02-26T12:31:25.593+06:00 TRACE 31608 --- [nio-9090-exec-1] 2ClientCredentialsAuthenticationProvider : Retrieved registered client
2025-02-26T12:31:25.593+06:00 TRACE 31608 --- [nio-9090-exec-1] 2ClientCredentialsAuthenticationProvider : Validated token request parameters
2025-02-26T12:31:25.594+06:00 TRACE 31608 --- [nio-9090-exec-1] 2ClientCredentialsAuthenticationProvider : Generated access token
2025-02-26T12:31:25.594+06:00 TRACE 31608 --- [nio-9090-exec-1] 2ClientCredentialsAuthenticationProvider : Saved authorization
2025-02-26T12:31:25.594+06:00 TRACE 31608 --- [nio-9090-exec-1] 2ClientCredentialsAuthenticationProvider : Authenticated token request
The above log only describes the event when a client successfully received OAuth2ClientAuthenticationToken
. But it doesn't tell more about the client information such as clientId
, clientName
. Is it possible to add these information in the logs, so if anyone wants to have this they can enable the specific class in their logger configuration?
Spring Security fires an event for each authentication that succeeds. Implement a listener for that event:
@Component
public class AuthenticationSuccessEventListener {
@EventListener
public void onSuccess(AuthenticationSuccessEvent event) {
if (event.getAuthentication() instanceof OAuth2ClientAuthenticationToken authentication) {
RegisteredClient registeredClient = authentication.getRegisteredClient();
log.info("clientId={}, clientName={}", registeredClient.getClientId(), registeredClient.getClientName());
}
}
}