Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] 시큐리티 에러 핸들러 수정 #143

Merged
merged 6 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/main/java/com/tiki/server/auth/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ public class SecurityConfig {
private final CustomAuthenticationEntryPointHandler customAuthenticationEntryPointHandler;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final ExceptionHandlerFilter exceptionHandlerFilter;
public static final String[] AUTH_WHITE_LIST = {
Chan531 marked this conversation as resolved.
Show resolved Hide resolved
"/api/v1/auth/sign-in",
"/api/v1/auth/reissue",
"/api/v1/members/password",
"/api/v1/members",
"/api/v1/mail/**",
"/actuator/health"
};

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
Expand All @@ -38,12 +46,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.authenticationEntryPoint(customAuthenticationEntryPointHandler))
.authorizeHttpRequests(request ->
request
.requestMatchers("/api/v1/auth/sign-in").permitAll()
.requestMatchers("/api/v1/auth/reissue").permitAll()
.requestMatchers("/api/v1/members/password").permitAll()
.requestMatchers("/api/v1/members").permitAll()
.requestMatchers("/api/v1/mail/**").permitAll()
.requestMatchers("/actuator/health").permitAll()
.requestMatchers(AUTH_WHITE_LIST).permitAll()
.anyRequest()
.authenticated())
.addFilterBefore(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public void commence(
HttpServletResponse response,
AuthenticationException authException
) throws IOException {
log.info("-EntryPoint-");
setResponse(response, ErrorCode.UNAUTHENTICATED_USER.getMessage());
log.info("[AuthenticationEntryPoint] " + authException.getMessage());
setResponse(response, ErrorCode.UNAUTHENTICATED.getMessage());
}

private void setResponse(HttpServletResponse response, String errorMessage) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import com.tiki.server.auth.exception.AuthException;
import com.tiki.server.auth.message.ErrorCode;
import com.tiki.server.common.dto.ErrorResponse;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
Expand Down Expand Up @@ -34,25 +32,14 @@ protected void doFilterInternal(
@NonNull FilterChain filterChain
) throws IOException {
try {
System.out.println("EHF");
filterChain.doFilter(request, response);
} catch (AuthException e) {
log.info("ExceptionHandlerFilter: AuthException - " + e);
log.info("[ExceptionHandlerFilter] - AuthException : " + e);
handleAuthException(response, e);
} catch (JwtException e) {
log.info("ExceptionHandlerFilter: JWTException - " + e);
handleJwtException(response);
} catch (IllegalArgumentException e) {
log.info("ExceptionHandlerFilter: IllegalArgumentException - " + e);
handleIllegalArgumentException(response);
} catch (ServletException e) {
log.info("ExceptionHandlerFilter: Exception - " + e);
throw new RuntimeException(e);
} catch (Exception e) {
log.info("[ExceptionHandlerFilter] - UncaughtException : " + e);
handleUncaughtException(response);
}
// catch (Exception e) {
// log.info("ExceptionHandlerFilter: Exception - " + e);
// handleUncaughtException(response);
// }
}

private void handleAuthException(HttpServletResponse response, AuthException e) throws IOException {
Expand All @@ -61,22 +48,13 @@ private void handleAuthException(HttpServletResponse response, AuthException e)
setResponse(response, httpStatus, errorMessage);
}

private void handleJwtException(HttpServletResponse response) throws IOException {
val jwtException = ErrorCode.INVALID_JWT_TOKEN;
setResponse(response, jwtException.getHttpStatus(), jwtException.getMessage());
}

private void handleIllegalArgumentException(HttpServletResponse response) throws IOException {
val uncaughtException = ErrorCode.EMPTY_JWT;
setResponse(response, uncaughtException.getHttpStatus(), uncaughtException.getMessage());
}

private void handleUncaughtException(HttpServletResponse response) throws IOException {
val uncaughtException = ErrorCode.UNCAUGHT_EXCEPTION;
setResponse(response, uncaughtException.getHttpStatus(), uncaughtException.getMessage());
}

private void setResponse(HttpServletResponse response, HttpStatus httpStatus, String errorMessage) throws IOException {
private void setResponse(HttpServletResponse response, HttpStatus httpStatus, String errorMessage)
throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setStatus(httpStatus.value());
Expand Down
13 changes: 6 additions & 7 deletions src/main/java/com/tiki/server/auth/jwt/JwtValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import com.tiki.server.auth.exception.AuthException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
Expand All @@ -20,15 +19,15 @@ public class JwtValidator {
public void validateToken(String token) {
try {
jwtProvider.getBodyFromJwt(token);
} catch (MalformedJwtException exception) {
log.info(exception.getMessage());
throw new AuthException(INVALID_JWT_TOKEN);
} catch (ExpiredJwtException exception) {
log.info(exception.getMessage());
throw new AuthException(EXPIRED_JWT_TOKEN);
} catch (UnsupportedJwtException exception) {
} catch (JwtException exception) {
log.info(exception.getMessage());
throw new AuthException(UNSUPPORTED_JWT_TOKEN);
throw new AuthException(INVALID_JWT_TOKEN);
} catch (Exception exception) {
log.info("예상치 못한 에러: " + exception);
throw new AuthException(UNCAUGHT_EXCEPTION);
}
}
}
4 changes: 1 addition & 3 deletions src/main/java/com/tiki/server/auth/message/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ public enum ErrorCode {
UNCAUGHT_EXCEPTION(BAD_REQUEST, "예상치 못한 오류입니다."),

/* 401 UNAUTHORIZED : 인증 없음 */
UNAUTHENTICATED_USER(UNAUTHORIZED, "잘못된 토큰 형식입니다."),
INVALID_KEY(UNAUTHORIZED, "유효하지 않은 키입니다."),
UNAUTHENTICATED(UNAUTHORIZED, "인증과정중 오류가 발생했습니다"),
UNMATCHED_TOKEN(UNAUTHORIZED, "토큰이 일치하지 않습니다."),
INVALID_JWT_TOKEN(UNAUTHORIZED, "잘못된 토큰 형식입니다."),
EXPIRED_JWT_TOKEN(UNAUTHORIZED, "만료된 토큰입니다."),
UNSUPPORTED_JWT_TOKEN(UNAUTHORIZED, "지원하지 않은 토큰입니다."),
EMPTY_JWT(UNAUTHORIZED, "빈 토큰입니다."),

/* 403 FORBIDDEN : 인가 없음 */
Expand Down
Loading