@AuthenticationPrincipal
어노테이션은 스프링 시큐리티(Spring Security)에서 현재 인증된 사용자(로그인한 사용자)의 정보를 컨트롤러(Controller)에서 쉽게 가져올 수 있도록 해주는 마법 같은 도구입니다.
UserDetails
라는 특별한 상자에 담아 관리합니다.@AuthenticationPrincipal
어노테이션은 이 UserDetails
상자를 컨트롤러의 메서드에 직접 전달해줍니다.예시:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/my-profile")
public String getMyProfile(@AuthenticationPrincipal UserDetails userDetails) {
String username = userDetails.getUsername(); // 로그인한 사용자의 아이디
// ... 다른 사용자 정보 사용 ...
return "내 아이디는 " + username + " 입니다.";
}
}
위 코드에서 @AuthenticationPrincipal UserDetails userDetails
부분은:
UserDetails
상자를 가져옵니다.UserDetails
상자를 getMyProfile
메서드의 userDetails
파라미터로 전달합니다.getMyProfile
메서드에서는 userDetails.getUsername()
과 같이 UserDetails
상자 안의 정보를 꺼내 사용할 수 있습니다.장점: