Auditing-user

최종윤·2023년 1월 8일

JPA

목록 보기
14/15

https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-eight-adding-functionality-to-a-repository/

다음으로, 어느 user가 entity X를 생성,수정했는 지 username을
JPA에서 자동으로 넣어주는 기능이 Auditing 기능을 알아보겠습니다.

인증된 User 정보 얻기

authenticated user의 정보를 얻기 위해 AuditAware<T.> interface를 사용합니다. T는 auditing 정보를 포함하는 entity의 field의 type입니다.

authenticated user의 username을 반환하는 class를 다음 단계로 생성해야합니다.
1. AuditorAware<T.> interface를 상속받는 UsernameAuditorAware class를 생성합니다. authenticated user의 username을 저장하기 위해 T는 String이어야 합니다.

  1. getCurrentAuditor() method를 다음 단계로 구현합니다.
    1. SecurityContext에서 Authentication 객체를 얻습니다.
    2. authentication 객체를 찾을 수 없거나, 인증되지 않았다면 null 반환
    3. 인증된 객체가 있다면 username 반환
    ``
    public class UsernameAuditorAware implements AuditorAware {
    @Override
    public String getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
    
        return ((User) authentication.getPrincipal()).getUsername();
    }
    }
    ``

컨텍스트 설정

애플리케이션의 지속성 계층을 구성하는 구성 클래스를 다음과 같이 변경하여 애플리케이션의 애플리케이션 컨텍스트를 구성할 수 있습니다:

@Bean
AuditorAware<String.> auditorProvider() {
return new UsernameAuditorAware();
}
를 영속컨텍스트 설정 클래스에 추가합니다.
@EnableJpaAuditing이 붙어있는 설정 클래스에 Bean 클래스로 등록하면 auditing 기능이 자동으로 사용하여 user정보를 set합니다.
``
@Configuration
@EnableJpaAuditing(dateTimeProviderRef = "dateTimeProvider")
@EnableJpaRepositories(basePackages = {
"net.petrikainulainen.springdata.jpa.todo"
})
@EnableTransactionManagement
class PersistenceContext {

@Bean
AuditorAware<String> auditorProvider() {
    return new UsernameAuditorAware();
}

@Bean
DateTimeProvider dateTimeProvider(DateTimeService dateTimeService) {
    return new AuditingDateTimeProvider(dateTimeService);
}

}
``

Entity class 수정

@Column(name = "created_by_user", nullable = false)
@CreatedBy
private String createdByUser;

@Column name과 nullable 속성을 추가하고, @CreatedBy를 붙여 entity 생성한 user의 정보를 포함하는 필드로 식별하게 합니다.

@CreatedDate와 같이 @CreatedBy를 필드를 포함하는 추상클래스를 생성하여 상속시키는 방법도 있습니다.

@CreatedDate 와 같이 JPA Auditing infrastructure을 이용하지 않고도 entity lifecycle events를 더하는 callback methods를 생성해서 생성자,수정자 fields 값을 set할 수 있습니다. 이는 더 간단하고 직설적이지만 다음 복잡한 JPA 방법을 사용하는 2가지 이유가 있습니다.

  1. callback methods 를 사용하는 것은 base class(or entity class)와 Spring Security 사이에 결합을 생성합니다.

  2. 생성,수정 시간을 JPA의 auditing infrastructure로 set했다면, user 정보도 JPA를 사용하여 구현해야 서로 다른 방법으로 auditing 정보를 set하지 않습니다.

profile
https://github.com/jyzayu

0개의 댓글