커스텀한UserDetails 구현체를 생성
。기존UserDetails에개별 사용자의 이름, PW, 권한등의 세부정보를 추가로 정의하여 현재로그인한유저의 정보를 추가로 포함하는UserDetails 구현체를 정의
UserDetailsService / UserDetails
。해당UserDetails 구현체는원본 유저 테이블에 저장된데이터를 추출하여Spring Security에 의해인증이 수행되는DTO 역할을 수행한다.
。Controller의@AuthenticationPrincipal을 통해 해당UserDetail 구현체에 현재 로그인중인Authentication 객체의principal을 주입하여@PathVariable등을 사용하지 않아도 현재 로그인한 사용자의principal정보를 가져올 수 있음
UserDetails 구현체의템플릿역할의인터페이스정의
。해당UserDetails 구현체가 수행할 동작을 정의
▶인증이 끝난 후어플리케이션에서 활용할사용자 정보를 포함해야하므로,Password는 제외public interface CurrentUser { UUID getId(); String getEmail(); UserRole getRole(); }
UserDetails 구현체 클래스정의
。해당UserDetail 구현체는Controller에서@AuthenticationPrincipal에 의해 주입되서 활용됨
。UserDetails 인터페이스구현 시getUsername(),getPassword()만 구현@Getter @Accessors(chain = true) public class CurrentUser implements UserDetails { @Setter private Long id; private String email; private String name; private String nickName; @Setter private Role role; private Map<String, Object> attributes; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return List.of( new SimpleGrantedAuthority("ROLE_" + this.role.name()) ); } @Builder private CurrentUser( String email, String nickName ){ this.email = email; this.nickName = nickName; this.name = nickName; } public static CurrentUser from(Users user){ if(user == null) throw new CustomException(ErrorCode.USER_NOT_FOUND, "계정이 없어 UserDetails의 생성이 불가능합니다."); return CurrentUser.builder() .nickName(user.getNickname()) .email(user.getEmail()) .build() .setId(user.getUserId()) .setRole(user.getRole()); } }。
new SimpleGrantedAuthority("ROLE_" + role.name())를 통해로그인한사용자의역할을 정의하여권한설정하도록 설정하기.
▶ 이후서비스 레이어 방어로직또는auth.requestMatchers(SecurityPath.ADMIN).hasRole("ADMIN");등을 통한권한 검증시 활용
이후
JWT 필터를 통해JWT 토큰으로 인증 후@AuthenticationPrincipal를 통해인증돤Authentication 구현체는DefaultCurrentUser가 아닌,CurrentUser로 주입
。해당JWT 토큰은인증이 끝난 경우CurrentUser정보를 저장하여SecurityContextHolder내 보관됨@RestController @RequestMapping("/api/profiles") public class ProfileController { @GetMapping("/me") public ResponseEntity<?> getMyProfile(@AuthenticationPrincipal CurrentUser currentUser) { // UUID userId = currentUser.getId(); String email = currentUser.getEmail(); // return ResponseEntity.ok("유저 ID: " + userId + ", 이메일: " + email); } }