Skip to content

Commit 4656b17

Browse files
fix : make the error message for client id and secret consistent
1 parent a5e0d14 commit 4656b17

File tree

9 files changed

+43
-37
lines changed

9 files changed

+43
-37
lines changed

src/main/java/com/patternknife/securityhelper/oauth2/config/logger/dto/ErrorDetails.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package com.patternknife.securityhelper.oauth2.config.logger.dto;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnore;
34
import com.patternknife.securityhelper.oauth2.config.response.TimestampUtil;
45
import com.patternknife.securityhelper.oauth2.util.CustomUtils;
5-
import com.fasterxml.jackson.annotation.JsonIgnore;
66
import lombok.ToString;
77

88
import java.util.Date;
@@ -12,15 +12,17 @@
1212
public class ErrorDetails {
1313
private Date timestamp;
1414

15-
// Never to be returned to clients, but must be logged.
16-
// @JsonIgnore
15+
// Never to be returned to clients, but must be logged. See the log file.
16+
@JsonIgnore
1717
private String message;
1818
private String details;
1919
private String userMessage;
2020
private Map<String, String> userValidationMessage;
2121

22+
// Never to be returned to clients, but must be logged. See the log file.
2223
@JsonIgnore
2324
private String stackTrace;
25+
// Never to be returned to clients, but must be logged. See the log file.
2426
@JsonIgnore
2527
private String cause;
2628

src/main/java/com/patternknife/securityhelper/oauth2/config/response/error/exception/auth/CustomOauth2AuthenticationException.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,22 @@
33
import com.patternknife.securityhelper.oauth2.config.logger.dto.ErrorMessages;
44
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
55

6+
/*
7+
* Only OAuth2AuthenticationException is allowed to be tossed.
8+
* */
69
public class CustomOauth2AuthenticationException extends OAuth2AuthenticationException {
710
protected ErrorMessages errorMessages;
811

912
public CustomOauth2AuthenticationException(){
10-
super("Default");
13+
super("default");
1114
}
1215
public CustomOauth2AuthenticationException(String message){
1316
super(message);
1417
errorMessages = ErrorMessages.builder().userMessage(message).message(message).build();
1518
}
1619

1720
public CustomOauth2AuthenticationException(ErrorMessages errorMessages){
18-
super(errorMessages.getMessage());
21+
super(errorMessages.getMessage() == null ? "default" : errorMessages.getMessage());
1922
this.errorMessages = errorMessages;
2023
}
2124
public ErrorMessages getErrorMessages() {

src/main/java/com/patternknife/securityhelper/oauth2/config/security/errorhandler/auth/authentication/AuthenticationFailureHandlerImpl.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
import com.fasterxml.jackson.databind.ObjectMapper;
44
import com.patternknife.securityhelper.oauth2.config.logger.dto.ErrorDetails;
5+
import com.patternknife.securityhelper.oauth2.config.logger.module.NonStopErrorLogConfig;
56
import com.patternknife.securityhelper.oauth2.config.response.error.CustomExceptionUtils;
67
import com.patternknife.securityhelper.oauth2.config.response.error.exception.auth.CustomOauth2AuthenticationException;
78
import com.patternknife.securityhelper.oauth2.config.response.error.message.SecurityUserExceptionMessage;
89
import jakarta.servlet.http.HttpServletRequest;
910
import jakarta.servlet.http.HttpServletResponse;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
1013
import org.springframework.http.HttpStatus;
1114
import org.springframework.security.core.AuthenticationException;
1215
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
@@ -17,6 +20,8 @@
1720

1821
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
1922

23+
private static final Logger logger = LoggerFactory.getLogger(NonStopErrorLogConfig.class);
24+
2025
@Override
2126
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
2227
throws IOException {
@@ -28,9 +33,9 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo
2833
"uri=" + request.getRequestURI(), ((CustomOauth2AuthenticationException) exception).getErrorMessages().getUserMessage(), stackTraces);
2934
}else if(exception instanceof OAuth2AuthenticationException) {
3035
errorDetails = new ErrorDetails(
31-
((OAuth2AuthenticationException) exception).getError().getErrorCode(),
36+
((OAuth2AuthenticationException) exception).getError().getErrorCode() + " / " + ((OAuth2AuthenticationException) exception).getError().getDescription(),
3237
"uri=" + request.getRequestURI(),
33-
((OAuth2AuthenticationException) exception).getError().getDescription(),
38+
SecurityUserExceptionMessage.AUTHENTICATION_LOGIN_FAILURE.getMessage(),
3439
stackTraces);
3540
}else{
3641
errorDetails = new ErrorDetails(
@@ -47,5 +52,7 @@ public void onAuthenticationFailure(HttpServletRequest request, HttpServletRespo
4752
// Write the error details to the response
4853
response.getWriter().write(new ObjectMapper().writeValueAsString(errorDetails));
4954

55+
logger.warn(errorDetails.toString());
56+
5057
}
5158
}

src/main/java/com/patternknife/securityhelper/oauth2/config/security/provider/auth/endpoint/CustomAuthenticationProvider.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ public Authentication authenticate(Authentication authentication)
8181
}
8282
}catch (UsernameNotFoundException e){
8383
throw new CustomOauth2AuthenticationException(ErrorMessages.builder().message(e.getMessage()).userMessage(e.getMessage()).build());
84-
} catch (Exception e){
84+
}catch (CustomOauth2AuthenticationException e){
85+
throw e;
86+
} catch (Exception e){
8587
throw new CustomOauth2AuthenticationException(ErrorMessages.builder().message(e.getMessage()).userMessage(SecurityUserExceptionMessage.AUTHENTICATION_LOGIN_ERROR.getMessage()).build());
8688
}
8789

src/main/java/com/patternknife/securityhelper/oauth2/config/security/serivce/Oauth2AuthenticationHashCheckService.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.patternknife.securityhelper.oauth2.config.security.serivce;
22

3+
import com.patternknife.securityhelper.oauth2.config.logger.dto.ErrorMessages;
4+
import com.patternknife.securityhelper.oauth2.config.response.error.exception.auth.CustomOauth2AuthenticationException;
35
import com.patternknife.securityhelper.oauth2.config.response.error.message.SecurityUserExceptionMessage;
6+
import jakarta.annotation.Nullable;
47
import lombok.RequiredArgsConstructor;
5-
import org.springframework.security.authentication.BadCredentialsException;
68
import org.springframework.security.core.userdetails.UserDetails;
79
import org.springframework.security.crypto.password.PasswordEncoder;
810
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
@@ -14,23 +16,23 @@ public class Oauth2AuthenticationHashCheckService {
1416

1517
private final PasswordEncoder passwordEncoder;
1618

17-
public void validateUsernamePassword(String inputPassword, UserDetails userDetails){
19+
public void validateUsernamePassword(String inputPassword, @Nullable UserDetails userDetails){
1820
if (userDetails == null) {
19-
throw new BadCredentialsException(SecurityUserExceptionMessage.ID_NO_EXISTS.getMessage());
21+
throw new CustomOauth2AuthenticationException(SecurityUserExceptionMessage.ID_NO_EXISTS.getMessage());
2022
}
2123
if (!passwordEncoder.matches(inputPassword, userDetails.getPassword())) {
22-
throw new BadCredentialsException(SecurityUserExceptionMessage.WRONG_ID_PASSWORD.getMessage());
24+
throw new CustomOauth2AuthenticationException(ErrorMessages.builder()
25+
.userMessage(SecurityUserExceptionMessage.AUTHENTICATION_LOGIN_FAILURE.getMessage()).message(SecurityUserExceptionMessage.WRONG_ID_PASSWORD.getMessage() + " (inputPassword : " + inputPassword + ", input username : " + userDetails.getUsername() + ")").build());
2326
}
2427
}
2528

26-
public Boolean validateClientCredentials(String inputClientSecret, RegisteredClient registeredClient){
29+
public void validateClientCredentials(String inputClientSecret, RegisteredClient registeredClient){
2730
if (registeredClient == null) {
28-
throw new BadCredentialsException(SecurityUserExceptionMessage.CLIENT_NO_EXISTS.getMessage());
31+
throw new CustomOauth2AuthenticationException(SecurityUserExceptionMessage.CLIENT_NO_EXISTS.getMessage());
2932
}
3033
if (!passwordEncoder.matches(inputClientSecret, registeredClient.getClientSecret())) {
31-
throw new BadCredentialsException(SecurityUserExceptionMessage.WRONG_CLIENT_ID_SECRET.getMessage());
32-
}else{
33-
return true;
34+
throw new CustomOauth2AuthenticationException(ErrorMessages.builder()
35+
.userMessage(SecurityUserExceptionMessage.AUTHENTICATION_LOGIN_FAILURE.getMessage()).message(SecurityUserExceptionMessage.WRONG_CLIENT_ID_SECRET.getMessage() + " (inputClientSecret : " + inputClientSecret+ ")").build());
3436
}
3537
}
3638

src/main/java/com/patternknife/securityhelper/oauth2/config/security/serivce/persistence/client/RegisteredClientRepositoryImpl.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import com.patternknife.securityhelper.oauth2.config.security.OAuth2ClientCachedInfo;
77
import com.patternknife.securityhelper.oauth2.config.security.dao.OauthClientDetailRepository;
88
import com.patternknife.securityhelper.oauth2.config.security.entity.OauthClientDetail;
9+
import jakarta.validation.constraints.NotNull;
910
import lombok.RequiredArgsConstructor;
1011
import org.springframework.security.oauth2.core.AuthorizationGrantType;
1112
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
@@ -51,7 +52,7 @@ public void save(RegisteredClient registeredClient) {
5152
}
5253

5354
@Override
54-
public RegisteredClient findById(String id) throws CustomOauth2AuthenticationException {
55+
public @NotNull RegisteredClient findById(String id) throws CustomOauth2AuthenticationException {
5556
// Assuming the ID is the client ID for simplification. Adjust if necessary.
5657
return oauthClientDetailRepository.findById(id)
5758
.map(this::mapToRegisteredClient)
@@ -60,7 +61,7 @@ public RegisteredClient findById(String id) throws CustomOauth2AuthenticationExc
6061
.userMessage(SecurityUserExceptionMessage.AUTHENTICATION_LOGIN_FAILURE.getMessage()).build()));
6162
}
6263
@Override
63-
public RegisteredClient findByClientId(String clientId) throws CustomOauth2AuthenticationException {
64+
public @NotNull RegisteredClient findByClientId(String clientId) throws CustomOauth2AuthenticationException {
6465
return oauthClientDetailRepository.findById(clientId)
6566
.map(this::mapToRegisteredClient)
6667
.orElseThrow(()->

src/main/java/com/patternknife/securityhelper/oauth2/domain/traditionaloauth/service/TraditionalOauthService.java

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import com.patternknife.securityhelper.oauth2.config.security.serivce.CommonOAuth2AuthorizationCycle;
99
import com.patternknife.securityhelper.oauth2.config.security.serivce.Oauth2AuthenticationHashCheckService;
1010
import com.patternknife.securityhelper.oauth2.config.security.serivce.persistence.authorization.OAuth2AuthorizationServiceImpl;
11+
import com.patternknife.securityhelper.oauth2.config.security.serivce.persistence.client.RegisteredClientRepositoryImpl;
1112
import com.patternknife.securityhelper.oauth2.config.security.serivce.userdetail.ConditionalDetailsService;
1213
import com.patternknife.securityhelper.oauth2.config.security.util.SecurityUtil;
1314
import com.patternknife.securityhelper.oauth2.domain.traditionaloauth.bo.BasicTokenResolver;
@@ -21,7 +22,6 @@
2122
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
2223
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
2324
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
24-
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
2525
import org.springframework.stereotype.Service;
2626
import org.springframework.web.context.request.RequestContextHolder;
2727
import org.springframework.web.context.request.ServletRequestAttributes;
@@ -39,7 +39,7 @@ public class TraditionalOauthService {
3939

4040
private static final Logger logger = LoggerFactory.getLogger(NonStopErrorLogConfig.class);
4141

42-
private final RegisteredClientRepository registeredClientRepository;
42+
private final RegisteredClientRepositoryImpl registeredClientRepository;
4343

4444
private final OAuth2AuthorizationServiceImpl authorizationService;
4545

@@ -49,7 +49,7 @@ public class TraditionalOauthService {
4949
private final Oauth2AuthenticationHashCheckService oauth2AuthenticationHashCheckService;
5050

5151

52-
public TraditionalOauthService(RegisteredClientRepository registeredClientRepository,
52+
public TraditionalOauthService(RegisteredClientRepositoryImpl registeredClientRepository,
5353
OAuth2AuthorizationServiceImpl authorizationService,
5454
ConditionalDetailsService conditionalDetailsService,
5555
CommonOAuth2AuthorizationCycle commonOAuth2AuthorizationCycle,
@@ -72,11 +72,7 @@ public SpringSecurityTraditionalOauthDTO.TokenResponse createAccessToken(SpringS
7272

7373
RegisteredClient registeredClient = registeredClientRepository.findByClientId(basicCredentials.getClientId());
7474

75-
assert registeredClient != null;
76-
if(!(basicCredentials.getClientId().equals(registeredClient.getClientId())
77-
&& oauth2AuthenticationHashCheckService.validateClientCredentials(basicCredentials.getClientSecret(), registeredClient))) {
78-
throw new UnauthorizedException(SecurityUserExceptionMessage.AUTHORIZATION_ERROR.getMessage());
79-
}
75+
oauth2AuthenticationHashCheckService.validateClientCredentials(basicCredentials.getClientSecret(), registeredClient);
8076

8177
UserDetails userDetails = conditionalDetailsService.loadUserByUsername(accessTokenRequest.getUsername(), basicCredentials.getClientId());
8278

@@ -105,13 +101,6 @@ public SpringSecurityTraditionalOauthDTO.TokenResponse refreshAccessToken(Spring
105101

106102
RegisteredClient registeredClient = registeredClientRepository.findByClientId(basicCredentials.getClientId());
107103

108-
assert registeredClient != null;
109-
110-
if(!(basicCredentials.getClientId().equals(registeredClient.getClientId())
111-
&& oauth2AuthenticationHashCheckService.validateClientCredentials(basicCredentials.getClientSecret(), registeredClient))) {
112-
throw new UnauthorizedException(SecurityUserExceptionMessage.AUTHORIZATION_ERROR.getMessage());
113-
}
114-
115104
OAuth2Authorization oAuth2Authorization = authorizationService.findByToken(refreshTokenRequest.getRefresh_token(), OAuth2TokenType.REFRESH_TOKEN);
116105

117106
UserDetails userDetails;

src/main/resources/application.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
spring.profiles.active=local
1+
spring.profiles.active=production
22
server.port=8370
33

44
spring.datasource.hikari.patternknife.url=jdbc:mysql://localhost:13506/sc_oauth2_pji?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true

src/main/resources/logback-spring.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@
141141

142142
<appender name="NonStopError"
143143
class="ch.qos.logback.core.rolling.RollingFileAppender">
144-
<file>${LOGS_ABSOLUTE_PATH}/non-stop/current.log</file>
144+
<file>${LOGS_ABSOLUTE_PATH}/non-stop-error/current.log</file>
145145
<encoder
146146
class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
147147
<!--<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>-->
@@ -209,7 +209,7 @@
209209
<!--<appender-ref ref="Console" />-->
210210
</logger>
211211

212-
<logger name="org.springframework.security" level="WARN">
212+
<logger name="org.springframework.security" level="ERROR">
213213
<appender-ref ref="SecurityError" />
214214
<!--<appender-ref ref="Console" />-->
215215
</logger>

0 commit comments

Comments
 (0)