[종이] Chapter 8. Spring Security - Security 구조, 폼 로그인#107
Conversation
|
Security 설정이 깔끔하게 잘 구성된 것 같아요 ! |
| @Component | ||
| public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { | ||
|
|
||
| @Override | ||
| public void commence( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| AuthenticationException authException | ||
| ) throws IOException { | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| BaseErrorCode code = GeneralErrorCode.UNAUTHORIZED; | ||
|
|
||
| response.setContentType("application/json;charset=UTF-8"); | ||
| response.setStatus(code.getStatus().value()); | ||
|
|
||
| ApiResponse<Void> errorResponse = ApiResponse.onFailure(code, null); | ||
| objectMapper.writeValue(response.getOutputStream(), errorResponse); | ||
| } | ||
| } |
There was a problem hiding this comment.
지금 저희가 CustomAuthenticationEntryPoint 를 만든 이유부터 생각해 보면 좋을 것 같습니다. 만약 컨트롤러나 서비스에서 예외가 발생했다면 @RestControllerAdvice를 활용해서 만들어두신 GeneralExceptionAdvice가 바로 잡아 냈을 것입니다. 그러나 시큐리티 필터에서 에러가 났다면 RestControllerAdvice가 잡아낼 수 없기 때문에 CustomAuthenticationEntryPoint 를 만들고 objectMapper로 JSON을 만들어 클라이언트에게 반환하게 해두신거죠
그런데 여기서 한 가지 아쉬운 점이 있습니다. CustomAuthenticationEntryPoint 에서 ObjectMapper로 직접 JSON 응답을 만들고 있잖아요? 이러면 에러 응답 포맷을 바꿀 때 GeneralExceptionAdvice랑 CustomAuthenticationEntryPoint 두 군데를 다 수정해야 합니다.
이걸 해결하는 방법? 좀 더 깔끔한 구조를 만드는 방법?으로 HandlerExceptionResolver를 CustomAuthenticationEntryPoint 에 주입하는 방식이 있습니다.
위에서 말씀드렸듯이 시큐리티 필터에서 에러가 났다면 RestControllerAdvice가 잡아낼 수 없기 때문에 이 방법을 사용해서 필터에서 터진 예외를 resolver.resolveException()으로 MVC 쪽에 토스해버리는 겁니다. 그러면 우리가 이미 만들어둔 @RestControllerAdvice가 그 예외를 잡아서 처리해주니까, 에러 응답 로직이 한 곳으로 모이게 됩니다.
구현은 GeneralExceptionAdvice에 AuthenticationException과 AccessDeniedException 전용 핸들러를 추가하는 방식으로 하면 될 것 같습니다!
There was a problem hiding this comment.
참고로 CustomAccessDeniedHandler도 같은 구조라서, 리팩토링할 때 같이 적용하면 될 것 같습니다~
✏️ 작업 내용
#️⃣ 연관된 이슈
closes #106
💡 함께 공유하고 싶은 부분
🤔 질문
✅ 워크북 체크리스트
✅ 컨벤션 체크리스트
📌 주안점