보통의 Entity(JPA에서의..)는 등록사용자ID, 등록일자를 가지게 된다.
package kr.co.xfilegolf.sale;
import kr.co.xfilegolf.SecurityUtils;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
* @author jason, Moon
* @since 2016-10-09
@Entity
@Table(name = "SALE")
@Data
public class Sale {
@GeneratedValue
@Column(name = "ID")
private Long id;
@Column(name = "PRODUCT_CODE")
private String productCode;
@Column(name = "SERIAL_NUMBER")
private String serialNumber;
@Column(name = "SALES_ON")
private LocalDate salesOn;
@Column(name = "CREATED_BY")
private String createdBy;
@Column(name = "CREATED_ON")
private LocalDateTime createdOn;
@Column(name = "LAST_MODIFIED_BY")
private String lastModifiedBy;
@Column(name = "LAST_MODIFIED_ON")
private LocalDateTime lastModifiedOn;
@PostPersist
public void postPersist() {
this.createdOn = LocalDateTime.now();
this.createdBy = SecurityUtils.currentUserName();
이때, 데이터가 저장될때 현재 세션의 사용자ID를 가져와서 해당 컬럼에 넣어주는 작업을 해야한다.
Spring Security에서는 SecurityContextHolder를 제공해 현재 세션의 사용자 정보를 가져올 수 있다.
먼저, 현재 세션 사용자의 객체를 가져오는 것은 아래와 같다.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
Authentication 객체의 getPrincipal() 메서드를 실행하게 되면, UserDetails를 구현한 사용자 객체를 Return 한다.
UserDetails를 구현한 객체가 가지고 있는 정보들을 가져올 수 있다.
필자는 curruntuserName() 메서드를 만들어서 현재 사용자의 ID를 Return 하게 했다.
public static String currentUserName() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
return user.getUsername();
두번째로, 현재 사용자의 Authorities를 가져오는 메서드는 Authentication 객체의 getAuthentication() 메서드이다.
현재 사용자가 "ROLE_ADMIN"이라는 ROLE을 가지고 있는지 확인하는 메서드는 아래와 같이 만들었다.
public static boolean hasAdminRole() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream().filter(o -> o.getAuthority().equals("ROLE_ADMIN")).findAny().isPresent();
getAuthentication() 메서드는 GrantedAuthority 를 상속 받은 권한 객체 Collection을 Return 한다.
stream을 사용해서, "ROLE_AMDIN"을 Filtering 하고, 해당 결과가 있는지를 반환한다.