TIL

8/28

iksadnorth 2023. 8. 28. 23:45

👣 개요

3주차 강의 중 숙련 part의 강의는 굉장히 영양가 있는 강의들로 가득찼다.
해당 강의는 보안을 위한 Spring Security 강의와, Validation, RestTemplate, JPA 연관관계에 대한
내용으로 이뤄져 있고 모두 내가 주먹구구식으로만 배워왔던 지식들이었다.

이러한 강의를 체계적으로 배울 수 있어서 새롭게 알게 된 내용과 
그동안 알지 못해 불편했던 것들을 많이 알 수 있었다.

 

👣 JWT를 위한 UsernamePasswordAuthenticationFilter 확장

그 동안 JWT를 구현하기 위해 OncePerRequestFilter를 확장해서 사용하기만 했다.
그러다 보니 로그인 기능 구현 시, 직접 Authentication 객체를 인증 처리하고
SecurityContextHolder에 직접 넣어줬다.
때문에 JWT에서 쿠키-세션으로 롤백하기가 어려웠고 유지보수가 어려웠다.

하지만 강의에서는 놀랍게도 인증 처리를 Filter에서 처리했고
UsernamePasswordAuthenticationFilter를 확장해서 구현하고 있었다.

UsernamePasswordAuthenticationFilter에서는 AuthenticationManager를 이용해서 인증 여부를 따진다.
나의 경우 내가 직접 UserDetailService를 호출해서 인증 여부를 확인했지만
AuthenticationManager를 이용하면 추상화된 방법으로 인증 여부를 따질 수 있다.
UsernamePasswordAuthenticationFilter의 메서드 3개를 재정의해서 인증 과정에 관여할 수 있다.

attemptAuthentication
인증된 Authentication 객체를 전달하는 함수. 
Username, Password를 이용해서 인증 전 Authentication 객체를 만들고
AuthenticationManager.authenticate를 이용해서 인증된 Authentication 객체를 Return한다.

successfulauthentication
로그인 성공 시 수행하는 작업 정의 함수.

unsuccessfulauthentication
로그인 실패 시 수행하는 작업 정의 함수.

위 메서드들을 적절히 재정의해서 JWT 토큰을 발급할 수 있다.

 

👣 Validation 예외 처리

만약 Validation에서 문제가 발생해 오류가 발생하면 BindingResult 객체를 받아서 
오류 처리를 수행할 수 있다.

@PostMapping("/user/signup")
public String signup(@Valid SignupRequestDto requestDto, BindingResult bindingResult) {
    // Validation 예외처리
    
    // 문제를 유발한 Field Load
    bindingResult.getFieldErrors()
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        // Field 명
        fieldError.getField()
        // Validation 오류 이유 출력.
        fieldError.getDefaultMessage()
    }
}

해당 객체를 이용해 오류 이유를 Client에게 적절히 알려줄 수 있다.

 

'TIL' 카테고리의 다른 글

8/30  (0) 2023.08.30
8/29  (0) 2023.08.29
WIL - 8/21 ~ 8/27  (0) 2023.08.27
8/26  (0) 2023.08.26
8/25  (0) 2023.08.25