[JPA] 로그인한 사용자 정보 가져오기
본문 바로가기

Web 개발/Java, SpringBoot, JPA

[JPA] 로그인한 사용자 정보 가져오기

728x90
반응형

1. Config 파일 생성

@Configuration
@EnableJpaAuditing(auditorAwareRef = "commonAuditorAware")

public class JpaAuditingConfiguration {

    @Bean
    public AuditorAware<String> commonAuditorAware() {

        /*
          if you are using spring security, you can get the currently logged username with following code segment.
          SecurityContextHolder.getContext().getAuthentication().getName()
         */

        return new CommonAuditorAware();
    }
}

 

2. AuditorAware 생성

AuditorAware를 상속받는 commonAuditorAware 클래스 생성

public class CommonAuditorAware implements AuditorAware<String> {

    @Autowired
    UserServiceImpl userService;

    @Override
    public Optional<String> getCurrentAuditor() {
    
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication || !authentication.isAuthenticated()) {
            return Optional.empty();
        }
        
        User user = (User) authentication.getPrincipal();
        return Optional.of(user.getUserId());
    
    }
}

 

3. Entity 에 Listener 추가

@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class AuditorCreateEntity<String>
{
    @CreatedBy
    private String createdBy;

    @CreatedDate
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate;
}

 

참고: https://mia-dahae.tistory.com/150

728x90
반응형