Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

che01 님의 블로그

@AuthenticationPrincipal 가이드 본문

카테고리 없음

@AuthenticationPrincipal 가이드

che01 2025. 6. 17. 21:28

개념

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();