Repository navigation
UserAuditorAware
Ryujy edited this page Feb 22, 2025
·
1 revision
- JPA Auditing 기능인 @CreatedBy, @ModifiedBy 어노테이션을 적용하고, 시큐리티에서 제공하는 유저 정보를 활용하기 위해 AuditorAware 를 구현해 빈으로 설정하였습니다.
- getCurrentAuditor() 를 오버라이딩해, Spring Security에서 사용자의 인증 정보를 기반으로 현재 사용자의 ID를 가져오는 메소드를 구현하였습니다.
- 하지만 구현 후 회원가입 기능에 장애가 발생하였습니다.
{
"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 타입의 결과를 반환하였습니다.
→ 회원가입 유저에 대한 검사 로직에 포함되지 않는 문제가 발생하였습니다.
- 회원가입시
- 로그인 후 생성 api 사용시(예시는 결제 요청)
→ 회원가입이라면 String의 anonymousUser를, 그 외의 인증된 유저인 경우 UserDetailsImple 타입의 객체를 반환하였습니다.
-
authentication.getPrincipal() instanceof UserDetailsImpl userDetails조건을 추가해 principal의 타입이 UserDetailsImpl 인지 검사하였습니다. - 조건에 충족하지 못한 경우에는
Optional.empty()를 반환해 유저를 생성할 때에는 생성자와 수정자를 비워두고 db에 넣는 로직으로 변경하였습니다.
-
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
- Response
-
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