Last active
June 23, 2022 22:26
-
-
Save rbaul/5fc59461800e55ae3e411ec5b0b3e503 to your computer and use it in GitHub Desktop.
Auditing Configuration (Spring Boot 2.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import lombok.*; | |
import org.springframework.data.annotation.CreatedBy; | |
import org.springframework.data.annotation.CreatedDate; | |
import org.springframework.data.annotation.LastModifiedBy; | |
import org.springframework.data.annotation.LastModifiedDate; | |
import org.springframework.data.jpa.domain.support.AuditingEntityListener; | |
import javax.persistence.EntityListeners; | |
import javax.persistence.MappedSuperclass; | |
import java.util.Calendar; | |
@Getter | |
@AllArgsConstructor | |
@NoArgsConstructor | |
@ToString | |
@EqualsAndHashCode | |
@MappedSuperclass | |
@EntityListeners(AuditingEntityListener.class) | |
public class AuditableEntity { | |
@CreatedBy | |
private String createdBy; | |
@CreatedDate | |
private Calendar createdDate; | |
@LastModifiedBy | |
private String lastModifiedBy; | |
@LastModifiedDate | |
private Calendar lastModifiedDate; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.data.domain.AuditorAware; | |
import org.springframework.data.jpa.repository.config.EnableJpaAuditing; | |
import org.springframework.security.core.Authentication; | |
import org.springframework.security.core.context.SecurityContextHolder; | |
import java.util.Optional; | |
@Configuration | |
@EnableJpaAuditing | |
public class AuditingConfig { | |
@Bean | |
public AuditorAware<String> auditorAware() { | |
return () -> { | |
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); | |
if (authentication == null || !authentication.isAuthenticated() || | |
!(authentication.getPrincipal() instanceof Principal)) { | |
return Optional.of("anonymousUser"); | |
} | |
Principal principal = authentication.getPrincipal(); | |
return Optional.of(userDetailsPrincipal.getName()); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment