12.17 TIL - 인증 정보 객체

이서준·2025년 12월 17일

SpringSecurity

목록 보기
4/4

인증 정보 객체

  • Spring Security에서 인증된 사용자를 다룰 때 Authenticaiton, Principal, UserDetails가 있음

1. Authentication

  • Spring Security에서 현재 인증 상태 전체를 표현하는 객체

구성 요소

  • principal : 사용자 식별 정보
  • credentials : 비밀번호 / JWT 토큰
  • authorities : ROLE, 권한
  • authenticated: 인증 성공 여부
  • details : IP, 세션 정보 등

사용하는 곳

  • SecurityContextHolder.getContext().setAuthentication(authentication);
  • Spring Security Filter 내부
  • 권한 거맛(@PreAuthorize)
  • 컨트롤러에서 현재 로그인 유저 접근

2. Principal

  • 요청의 주체를 나타내는 최소 단위 인터페이스
  • Java 표준 인터페이스
  • 사용자 식별용 (username, email, id)
  • 권한 정보는 없음

사용하는 곳

  • 컨트롤러 메서드 파라미터
  • @AuthenticationPrinciapl 이전 단계 개념

단점

  • 사용자 상세 정보 없음
  • 권한, 상태 정보 없음

3. UserDetails

  • Spring Security가 사용자 정보를 저장하기 위해 만든 표준 인터페이스
  • Authenticationprincipal에 들어가는 실제 사용자 객체

역할

  • DB의 User Entity를 Security 전용 모델로 감싸는 역할
  • 인증&인가 판단 기준 제공

사용하는 곳

  • UserDetailsService.loadUserByUsername()
  • Authenticationprincipal
  • 권한 검사 시 사용

정리

[ 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);
  1. Jwt Filter에서 토큰 검증
  2. 사용자 정보를 Authentication 생성
  3. SecurityContextHolder에 저장
  4. Controller에서 사용

Controller에서 사용

  1. 모두 사용
@PutMapping("/{id}")
public ... update(@AuthenticationPrincipal UserinfoDetails userDetails,
									@PathVariable Long id,
                  @RequestBody @Valid ... request) {

        ....
}
  1. 권한
@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);

참고 : https://velog.io/@haruceki/Authentication-Principal-UserDetails-%EA%B0%9D%EC%B2%B4-%EC%B0%A8%EC%9D%B4

profile
Allons-y

0개의 댓글