Skip to content

UserAuditorAware

Ryujy edited this page Feb 22, 2025 · 1 revision

UserAuditorAware

문제 발생 과정

  1. JPA Auditing 기능인 @CreatedBy, @ModifiedBy 어노테이션을 적용하고, 시큐리티에서 제공하는 유저 정보를 활용하기 위해 AuditorAware 를 구현해 빈으로 설정하였습니다.
    1. getCurrentAuditor() 를 오버라이딩해, Spring Security에서 사용자의 인증 정보를 기반으로 현재 사용자의 ID를 가져오는 메소드를 구현하였습니다.
  2. 하지만 구현 후 회원가입 기능에 장애가 발생하였습니다.

기대 결과

{
  "message": "회원가입이 성공적으로 완료되었습니다."
}

실제 결과

{
"message": "class java.lang.String cannot be cast to class com.ioteam.order_management_platform.user.security.UserDetailsImpl (java.lang.String is in module java.base of loader 'bootstrap'; com.ioteam.order_management_platform.user.security.UserDetailsImpl is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @4e0cd6fd)",
"errorCode": "E_NOT_DEFINED"
}

원인 분석

  • 로그인 하지 않은 경우, Spring Security Context 내 Authentication 객체가 존재하지 않거나, Authentication 객체의 authenticated 의 값이 false 일 것으로 예상하였습니다.

  • 실제 디버깅 결과 Authentication 객체의 authenticated 값이 true 이며, principal 객체는 anonymousUser 라는 String 타입의 결과를 반환하였습니다.

    → 회원가입 유저에 대한 검사 로직에 포함되지 않는 문제가 발생하였습니다.

디버깅시 userDetails 값 확인

  • 회원가입시
스크린샷_2025-02-22_오후_3 07 41
  • 로그인 후 생성 api 사용시(예시는 결제 요청)
스크린샷_2025-02-22_오후_3 16 33

해결 방법

적용한 해결책

→ 회원가입이라면 String의 anonymousUser를, 그 외의 인증된 유저인 경우 UserDetailsImple 타입의 객체를 반환하였습니다.

  1. authentication.getPrincipal() instanceof UserDetailsImpl userDetails 조건을 추가해 principal의 타입이 UserDetailsImpl 인지 검사하였습니다.
  2. 조건에 충족하지 못한 경우에는 Optional.empty()를 반환해 유저를 생성할 때에는 생성자와 수정자를 비워두고 db에 넣는 로직으로 변경하였습니다.

AS-IS TO-BE 모델

  • as-is

    public class UserAuditorAware implements AuditorAware<UUID> {
    	
    	@Override
    	public Optional<UUID> getCurrentAuditor() {
    	    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    	    if (null == authentication || !authentication.isAuthenticated()) {
    				return null;
    	
    	    UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
    		return Optional.of(userDetails.getUserId());
    	}
    }
  • to-be

    public class UserAuditorAware implements AuditorAware<UUID> {
    
    	@Override
    	public Optional<UUID> getCurrentAuditor() {
    		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    		if (authentication != null
    			&& authentication.isAuthenticated()
    			&& authentication.getPrincipal() instanceof UserDetailsImpl userDetails) {
    			return Optional.of(userDetails.getUserId());
    		} else {
    			// 인증된사용자 정보가 UserDetailsImpl이 아닌경우 빈값 반환
    			return Optional.empty();
    		}
    
    	}
    }

테스트 및 검증 결과

  • Request body
스크린샷_2025-02-22_오후_3 50 52
  • Response
스크린샷_2025-02-22_오후_3 52 04
  • Database

    created_at deleted_at modified_at created_by deleted_by modified_by user_id email nickname password role username
    2025-02-22 15:42:16.427 2025-02-22 15:42:16.427 cb51e3bd-26f0-4611-8f96-20fdcd62ef14 testCustomer11@test.com 멋쟁이사용자 $2a$10$jAkZBmFMd4WIGPcEryj.VO/1e26Ocl33D9sm7CDeOmF0p0vxAWnRu CUSTOMER customer

Clone this wiki locally