Spring Security - 사용자정의 UserDetails 구현체 정의

TopOfTheHead·2025년 12월 20일

Spring Security

목록 보기
7/21

커스텀UserDetails 구현체를 생성
。기존 UserDetails개별 사용자의 이름, PW, 권한 등의 세부정보를 추가로 정의하여 현재 로그인유저의 정보를 추가로 포함하는 UserDetails 구현체를 정의
UserDetailsService / UserDetails

Controller@AuthenticationPrincipal을 통해 해당 UserDetail 구현체에 현재 로그인중인 Authentication 객체principal을 주입하여 @PathVariable 등을 사용하지 않아도 현재 로그인한 사용자의 principal 정보를 가져올 수 있음

  • UserDetails 구현체템플릿 역할의 인터페이스 정의
    。해당 UserDetails 구현체가 수행할 동작을 정의
public interface CurrentUser {
	UUID getId();
  	String getEmail();
	UserRole getRole();
}
  • UserDetails 구현체 클래스 정의
    。해당 UserDetail 구현체Controller에서 @AuthenticationPrincipal에 의해 주입되서 활용됨
@AllArgsConstructor
@NoArgsConstructor
public class DefaultCurrentUser implements UserDetails, CurrentUser {
	private UUID id;
	private String email;
	private UserRole role;
	@Override
	public UUID getId() {
		return id;
	}
  	@Override
	public String getEmail() {
		return email;
	}
	@Override
	public UserRole getRole() {
		return role;
	}
	// UserDetails 를 구현했으므로 구현해야되는 메서드
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
	}
	// UserDetails 를 구현했으므로 구현해야되는 메서드
	@Override
	public String getPassword() {
		return "";
	}
	// UserDetails 를 구현했으므로 구현해야되는 메서드
	@Override
	public String getUsername() {
		return "";
	}
}

new SimpleGrantedAuthority("ROLE_" + role.name())를 통해 로그인사용자역할을 정의하여 권한 설정하도록 설정하기.
▶ 이후 서비스 레이어 방어로직 또는 auth.requestMatchers(SecurityPath.ADMIN).hasRole("ADMIN"); 등을 통한 권한 검증 시 활용

profile
공부기록 블로그

0개의 댓글