che01 님의 블로그
@AuthenticationPrincipal 가이드 본문
개념
Spring Security에서 현재 로그인한 사용자 정보를 자동으로 주입해주는 어노테이션
사용법
@GetMapping("/api/profile")
public ResponseEntity<?> getProfile(@AuthenticationPrincipal CustomUserDetails userDetails) {
Long userId = userDetails.getId();
String email = userDetails.getUsername();
return ResponseEntity.ok(Map.of("userId", userId, "email", email));
}
주의사항
- 인증 안된 사용자는 userDetails가 null
- 반드시 인증이 필요한 경로에서만 사용
내부 동작
// 이 코드를 Spring이 대신 해줌
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal();