
principal : 사용자 식별 정보credentials : 비밀번호 / JWT 토큰authorities : ROLE, 권한authenticated: 인증 성공 여부details : IP, 세션 정보 등SecurityContextHolder.getContext().setAuthentication(authentication);@AuthenticationPrinciapl 이전 단계 개념Authentication의 principal에 들어가는 실제 사용자 객체
UserDetailsService.loadUserByUsername()Authentication의 principal[ HTTP 요청 ]
↓
Authentication
├── principal → UserDetails (또는 String / CustomPrincipal)
├── credentials → 비밀번호 / JWT
├── authorities → ROLE_USER, ROLE_ADMIN
| 객체 | 역할 |
|---|---|
| Authentication | 인증 전체 정보 |
| Principal | 사용자 식별자 |
| UserDetails | 사용자 상세 정보 |
//JWT 토큰에서 값을 가져오기
Long userId = jwtUtil.extractUserId(token);
String username = jwtUtil.extractUsername(token);
UserRole role = jwtUtil.extractUserRole(token);
//사용자 상세 정보에 담기
CustomUserDetails userDetails = new CustomUserDetails(userId, username, role);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
Authentication 생성SecurityContextHolder에 저장Controller에서 사용@PutMapping("/{id}")
public ... update(@AuthenticationPrincipal UserinfoDetails userDetails,
@PathVariable Long id,
@RequestBody @Valid ... request) {
....
}
@PreAuthorize("hasRole('ADMIN')")
@PostMapping
public ... create(~~~ request) {
...
}
Authentication은 인터페이스
- 구현체 예
- UsernamePasswordAuthenticationToken
- JwtAuthenticationToken
- AnonymousAuthenticationToken
principal은 UserDetails 아니어도 됨
List<SimpleGrantedAuthority> authorities = List.of(new SimpleGrantedAuthority(role.name())); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userId, null, >authorities);