Skip to content

Commit 7f1bcf3

Browse files
author
Steve Riesenberg
committed
Add logging for authentication providers
Issue spring-projectsgh-159
1 parent 061badf commit 7f1bcf3

14 files changed

+207
-0
lines changed

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java

+10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717

1818
import java.time.Instant;
1919

20+
import org.apache.commons.logging.Log;
21+
import org.apache.commons.logging.LogFactory;
22+
2023
import org.springframework.security.authentication.AuthenticationProvider;
2124
import org.springframework.security.core.Authentication;
2225
import org.springframework.security.core.AuthenticationException;
@@ -47,6 +50,7 @@
4750
*/
4851
public final class ClientSecretAuthenticationProvider implements AuthenticationProvider {
4952
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1";
53+
private final Log logger = LogFactory.getLog(getClass());
5054
private final RegisteredClientRepository registeredClientRepository;
5155
private final CodeVerifierAuthenticator codeVerifierAuthenticator;
5256
private PasswordEncoder passwordEncoder;
@@ -95,6 +99,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
9599
throwInvalidClient(OAuth2ParameterNames.CLIENT_ID);
96100
}
97101

102+
this.logger.trace("Retrieved registered client");
103+
98104
if (!registeredClient.getClientAuthenticationMethods().contains(
99105
clientAuthentication.getClientAuthenticationMethod())) {
100106
throwInvalidClient("authentication_method");
@@ -114,9 +120,13 @@ public Authentication authenticate(Authentication authentication) throws Authent
114120
throwInvalidClient("client_secret_expires_at");
115121
}
116122

123+
this.logger.trace("Validated client authentication parameters");
124+
117125
// Validate the "code_verifier" parameter for the confidential client, if available
118126
this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient);
119127

128+
this.logger.trace("Authenticated client secret");
129+
120130
return new OAuth2ClientAuthenticationToken(registeredClient,
121131
clientAuthentication.getClientAuthenticationMethod(), clientAuthentication.getCredentials());
122132
}

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/CodeVerifierAuthenticator.java

+11
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
import java.util.Base64;
2222
import java.util.Map;
2323

24+
import org.apache.commons.logging.Log;
25+
import org.apache.commons.logging.LogFactory;
26+
2427
import org.springframework.security.oauth2.core.AuthorizationGrantType;
2528
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
2629
import org.springframework.security.oauth2.core.OAuth2Error;
@@ -47,6 +50,7 @@
4750
*/
4851
final class CodeVerifierAuthenticator {
4952
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE);
53+
private final Log logger = LogFactory.getLog(getClass());
5054
private final OAuth2AuthorizationService authorizationService;
5155

5256
CodeVerifierAuthenticator(OAuth2AuthorizationService authorizationService) {
@@ -81,6 +85,8 @@ private boolean authenticate(OAuth2ClientAuthenticationToken clientAuthenticatio
8185
throwInvalidGrant(OAuth2ParameterNames.CODE);
8286
}
8387

88+
this.logger.trace("Retrieved authorization with authorization code");
89+
8490
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
8591
OAuth2AuthorizationRequest.class.getName());
8692

@@ -90,17 +96,22 @@ private boolean authenticate(OAuth2ClientAuthenticationToken clientAuthenticatio
9096
if (registeredClient.getClientSettings().isRequireProofKey()) {
9197
throwInvalidGrant(PkceParameterNames.CODE_CHALLENGE);
9298
} else {
99+
this.logger.trace("Did not authenticate code verifier since requireProofKey=false");
93100
return false;
94101
}
95102
}
96103

104+
this.logger.trace("Validated code verifier parameters");
105+
97106
String codeChallengeMethod = (String) authorizationRequest.getAdditionalParameters()
98107
.get(PkceParameterNames.CODE_CHALLENGE_METHOD);
99108
String codeVerifier = (String) parameters.get(PkceParameterNames.CODE_VERIFIER);
100109
if (!codeVerifierValid(codeVerifier, codeChallenge, codeChallengeMethod)) {
101110
throwInvalidGrant(PkceParameterNames.CODE_VERIFIER);
102111
}
103112

113+
this.logger.trace("Authenticated code verifier");
114+
104115
return true;
105116
}
106117

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java

+10
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
*/
1616
package org.springframework.security.oauth2.server.authorization.authentication;
1717

18+
import org.apache.commons.logging.Log;
19+
import org.apache.commons.logging.LogFactory;
20+
1821
import org.springframework.security.authentication.AuthenticationProvider;
1922
import org.springframework.security.core.Authentication;
2023
import org.springframework.security.core.AuthenticationException;
@@ -48,6 +51,7 @@
4851
*/
4952
public final class JwtClientAssertionAuthenticationProvider implements AuthenticationProvider {
5053
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1";
54+
private final Log logger = LogFactory.getLog(getClass());
5155
private static final ClientAuthenticationMethod JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD =
5256
new ClientAuthenticationMethod("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
5357
private final RegisteredClientRepository registeredClientRepository;
@@ -84,6 +88,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
8488
throwInvalidClient(OAuth2ParameterNames.CLIENT_ID);
8589
}
8690

91+
this.logger.trace("Retrieved registered client");
92+
8793
if (!registeredClient.getClientAuthenticationMethods().contains(ClientAuthenticationMethod.PRIVATE_KEY_JWT) &&
8894
!registeredClient.getClientAuthenticationMethods().contains(ClientAuthenticationMethod.CLIENT_SECRET_JWT)) {
8995
throwInvalidClient("authentication_method");
@@ -101,6 +107,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
101107
throwInvalidClient(OAuth2ParameterNames.CLIENT_ASSERTION, ex);
102108
}
103109

110+
this.logger.trace("Validated client authentication parameters");
111+
104112
// Validate the "code_verifier" parameter for the confidential client, if available
105113
this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient);
106114

@@ -109,6 +117,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
109117
ClientAuthenticationMethod.PRIVATE_KEY_JWT :
110118
ClientAuthenticationMethod.CLIENT_SECRET_JWT;
111119

120+
this.logger.trace("Authenticated client assertion");
121+
112122
return new OAuth2ClientAuthenticationToken(registeredClient, clientAuthenticationMethod, jwtAssertion);
113123
}
114124

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java

+28
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
import java.util.HashMap;
2121
import java.util.Map;
2222

23+
import org.apache.commons.logging.Log;
24+
import org.apache.commons.logging.LogFactory;
25+
26+
import org.springframework.core.log.LogMessage;
2327
import org.springframework.security.authentication.AuthenticationProvider;
2428
import org.springframework.security.core.Authentication;
2529
import org.springframework.security.core.AuthenticationException;
@@ -68,6 +72,7 @@
6872
*/
6973
public final class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
7074
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
75+
private final Log logger = LogFactory.getLog(getClass());
7176
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE =
7277
new OAuth2TokenType(OAuth2ParameterNames.CODE);
7378
private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE =
@@ -99,11 +104,16 @@ public Authentication authenticate(Authentication authentication) throws Authent
99104
getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
100105
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
101106

107+
this.logger.trace("Retrieved registered client");
108+
102109
OAuth2Authorization authorization = this.authorizationService.findByToken(
103110
authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
104111
if (authorization == null) {
105112
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
106113
}
114+
115+
this.logger.trace("Retrieved authorization with authorization code");
116+
107117
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode =
108118
authorization.getToken(OAuth2AuthorizationCode.class);
109119

@@ -115,6 +125,9 @@ public Authentication authenticate(Authentication authentication) throws Authent
115125
// Invalidate the authorization code given that a different client is attempting to use it
116126
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
117127
this.authorizationService.save(authorization);
128+
if (this.logger.isWarnEnabled()) {
129+
this.logger.warn(LogMessage.format("Invalidated authorization code used by registered client '%s'", registeredClient.getId()));
130+
}
118131
}
119132
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
120133
}
@@ -128,6 +141,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
128141
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
129142
}
130143

144+
this.logger.trace("Validated token request parameters");
145+
131146
// @formatter:off
132147
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
133148
.registeredClient(registeredClient)
@@ -149,6 +164,9 @@ public Authentication authenticate(Authentication authentication) throws Authent
149164
"The token generator failed to generate the access token.", ERROR_URI);
150165
throw new OAuth2AuthenticationException(error);
151166
}
167+
168+
this.logger.trace("Generated access token");
169+
152170
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
153171
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
154172
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
@@ -172,6 +190,9 @@ public Authentication authenticate(Authentication authentication) throws Authent
172190
"The token generator failed to generate the refresh token.", ERROR_URI);
173191
throw new OAuth2AuthenticationException(error);
174192
}
193+
194+
this.logger.trace("Generated refresh token");
195+
175196
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
176197
authorizationBuilder.refreshToken(refreshToken);
177198
}
@@ -191,6 +212,9 @@ public Authentication authenticate(Authentication authentication) throws Authent
191212
"The token generator failed to generate the ID token.", ERROR_URI);
192213
throw new OAuth2AuthenticationException(error);
193214
}
215+
216+
this.logger.trace("Generated id token");
217+
194218
idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
195219
generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
196220
authorizationBuilder.token(idToken, (metadata) ->
@@ -206,12 +230,16 @@ public Authentication authenticate(Authentication authentication) throws Authent
206230

207231
this.authorizationService.save(authorization);
208232

233+
this.logger.trace("Saved authorization");
234+
209235
Map<String, Object> additionalParameters = Collections.emptyMap();
210236
if (idToken != null) {
211237
additionalParameters = new HashMap<>();
212238
additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
213239
}
214240

241+
this.logger.trace("Authenticated token request");
242+
215243
return new OAuth2AccessTokenAuthenticationToken(
216244
registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
217245
}

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java

+20
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
import java.util.Set;
2121
import java.util.function.Consumer;
2222

23+
import org.apache.commons.logging.Log;
24+
import org.apache.commons.logging.LogFactory;
25+
2326
import org.springframework.security.authentication.AnonymousAuthenticationToken;
2427
import org.springframework.security.authentication.AuthenticationProvider;
2528
import org.springframework.security.core.Authentication;
@@ -67,6 +70,7 @@
6770
public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implements AuthenticationProvider {
6871
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1";
6972
private static final String PKCE_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1";
73+
private final Log logger = LogFactory.getLog(getClass());
7074
private static final StringKeyGenerator DEFAULT_STATE_GENERATOR =
7175
new Base64StringKeyGenerator(Base64.getUrlEncoder());
7276
private final RegisteredClientRepository registeredClientRepository;
@@ -105,6 +109,8 @@ public Authentication authenticate(Authentication authentication) throws Authent
105109
authorizationCodeRequestAuthentication, null);
106110
}
107111

112+
this.logger.trace("Retrieved registered client");
113+
108114
OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext =
109115
OAuth2AuthorizationCodeRequestAuthenticationContext.with(authorizationCodeRequestAuthentication)
110116
.registeredClient(registeredClient)
@@ -129,13 +135,16 @@ public Authentication authenticate(Authentication authentication) throws Authent
129135
authorizationCodeRequestAuthentication, registeredClient, null);
130136
}
131137

138+
this.logger.trace("Validated authorization code request parameters");
139+
132140
// ---------------
133141
// The request is valid - ensure the resource owner is authenticated
134142
// ---------------
135143

136144
Authentication principal = (Authentication) authorizationCodeRequestAuthentication.getPrincipal();
137145
if (!isPrincipalAuthenticated(principal)) {
138146
// Return the authorization request as-is where isAuthenticated() is false
147+
this.logger.trace("Did not authenticate authorization code request since principal not authenticated");
139148
return authorizationCodeRequestAuthentication;
140149
}
141150

@@ -156,11 +165,16 @@ public Authentication authenticate(Authentication authentication) throws Authent
156165
OAuth2Authorization authorization = authorizationBuilder(registeredClient, principal, authorizationRequest)
157166
.attribute(OAuth2ParameterNames.STATE, state)
158167
.build();
168+
169+
logger.trace("Generated authorization consent state");
170+
159171
this.authorizationService.save(authorization);
160172

161173
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null ?
162174
currentAuthorizationConsent.getScopes() : null;
163175

176+
this.logger.trace("Saved authorization");
177+
164178
return new OAuth2AuthorizationConsentAuthenticationToken(authorizationRequest.getAuthorizationUri(),
165179
registeredClient.getClientId(), principal, state, currentAuthorizedScopes, null);
166180
}
@@ -174,17 +188,23 @@ public Authentication authenticate(Authentication authentication) throws Authent
174188
throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, null);
175189
}
176190

191+
this.logger.trace("Generated authorization code");
192+
177193
OAuth2Authorization authorization = authorizationBuilder(registeredClient, principal, authorizationRequest)
178194
.authorizedScopes(authorizationRequest.getScopes())
179195
.token(authorizationCode)
180196
.build();
181197
this.authorizationService.save(authorization);
182198

199+
this.logger.trace("Saved authorization");
200+
183201
String redirectUri = authorizationRequest.getRedirectUri();
184202
if (!StringUtils.hasText(redirectUri)) {
185203
redirectUri = registeredClient.getRedirectUris().iterator().next();
186204
}
187205

206+
this.logger.trace("Authenticated authorization code request");
207+
188208
return new OAuth2AuthorizationCodeRequestAuthenticationToken(authorizationRequest.getAuthorizationUri(),
189209
registeredClient.getClientId(), principal, authorizationCode, redirectUri,
190210
authorizationRequest.getState(), authorizationRequest.getScopes());

0 commit comments

Comments
 (0)