커스텀한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");등을 통한권한 검증시 활용