SecurityContextHolder는 Spring Security에서 인증된 사용자의 보안 정보를 애플리케이션의 전체 범위에서 관리하고 접근할 수 있도록 하는 핵심적인 역할을 합니다. 이 객체는 인증이 성공하면 Authentication 객체를 저장하며, 애플리케이션의 다른 컴포넌트가 이를 참조할 수 있게 합니다.
1. SecurityContextHolder의 역할
SecurityContextHolder는 보안 컨텍스트(SecurityContext) 를 관리하는 저장소입니다. SecurityContext는 현재 인증된 사용자에 대한 정보를 담고 있는 객체로, 주로 Authentication 객체가 포함됩니다.
- SecurityContextHolder는 각 요청에 대해 인증된 사용자 정보를 저장하고, 이 정보를 애플리케이션의 다른 컴포넌트들이 접근할 수 있도록 합니다.
- Authentication 객체는 현재 사용자가 누구인지, 어떤 권한을 가지고 있는지 등의 정보를 담고 있습니다.
2. SecurityContextHolder의 구성 요소
SecurityContextHolder는 다음과 같은 요소들을 관리합니다:
- SecurityContext: SecurityContext는 Authentication 객체를 포함하며, 이 객체는 주로 사용자의 인증 상태를 나타냅니다.
- Authentication: 이 객체는 현재 사용자의 인증 정보를 담고 있으며, 보통 Principal 객체(사용자 객체)와 함께 사용됩니다. 인증된 사용자 정보는 Authentication 객체를 통해 접근할 수 있습니다.
- SecurityContextHolder의 저장 방식: 기본적으로 SecurityContextHolder는 인증 정보를 ThreadLocal을 사용하여 각 스레드에 저장합니다. 이는 다중 요청 및 다중 스레드 환경에서 사용자 인증 정보를 독립적으로 관리할 수 있게 합니다.
3. SecurityContextHolder와 Authentication 객체
Authentication 객체는 사용자의 인증 상태와 세부 정보를 담고 있으며, SecurityContextHolder를 통해 애플리케이션의 다른 부분에서 이를 접근할 수 있습니다.
주요 필드 및 메소드
- Authentication 객체에는 getPrincipal(), getAuthorities(), getCredentials() 등의 메소드가 있습니다.
- getPrincipal(): 인증된 사용자의 기본 정보를 반환합니다. 일반적으로 User 객체나 사용자 이름 등이 될 수 있습니다.
- getAuthorities(): 사용자가 가진 권한을 반환합니다. 이는 보통 GrantedAuthority 목록으로 제공됩니다.
- getCredentials(): 인증에 사용된 자격 증명(예: 비밀번호)을 반환합니다.
- isAuthenticated(): 사용자가 인증되었는지 여부를 반환합니다.
SecurityContextHolder 사용 예시
SecurityContextHolder는 SecurityContext 객체를 현재 스레드에 설정하여, 애플리케이션 내에서 인증 정보를 관리합니다.
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
public class MyService {
public void performAction() {
// 현재 인증된 사용자 정보 가져오기
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 사용자의 principal 정보 가져오기 (예: UserDetails)
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails) principal).getUsername();
System.out.println("현재 인증된 사용자: " + username);
}
}
}
위 코드에서 SecurityContextHolder.getContext().getAuthentication()을 통해 현재 스레드의 Authentication 객체를 가져올 수 있습니다. 이를 통해 인증된 사용자의 정보를 애플리케이션 내 다른 컴포넌트에서 사용할 수 있게 됩니다.
4. SecurityContextHolder의 동작 방식
- 인증 요청이 들어오면: Spring Security는 요청이 들어올 때 Authentication 객체를 생성하고, 이 객체를 SecurityContextHolder에 저장합니다. SecurityContextHolder는 이 객체를 ThreadLocal에 저장하여, 이후의 요청 및 응답에서 인증 정보를 참조할 수 있게 합니다.
- 인증 성공 시: 인증이 성공하면, Spring Security는 Authentication 객체를 SecurityContext에 저장합니다. 이 객체는 사용자 정보(주로 Principal)와 권한(예: GrantedAuthority)을 포함합니다.
- 애플리케이션 내에서의 접근: SecurityContextHolder.getContext().getAuthentication()을 사용하면 애플리케이션 내의 다른 컴포넌트가 언제든지 인증 정보를 조회할 수 있습니다. 예를 들어, 요청에 따라 동적으로 인증된 사용자 정보를 처리하는 로직을 추가할 수 있습니다.
5. 보안 컨텍스트의 공유
- Request-Scope: 기본적으로 SecurityContextHolder는 ThreadLocal을 사용하여 스레드마다 보안 컨텍스트를 독립적으로 관리합니다. 즉, 각각의 HTTP 요청은 다른 스레드에서 실행되며, 각 요청에 대해 독립적인 보안 컨텍스트가 유지됩니다.
- Session-Scope: SecurityContext는 세션에 저장될 수 있습니다. 예를 들어, 사용자가 로그인하면 인증 정보는 HTTP 세션에 저장되고, SecurityContextHolder는 이를 참조하여 사용자 인증 정보를 계속 유지할 수 있습니다.
6. 보안 컨텍스트가 애플리케이션의 여러 컴포넌트에 공유되는 방식
Spring Security는 SecurityContext를 세션 또는 ThreadLocal을 통해 애플리케이션의 다른 컴포넌트와 공유할 수 있습니다. 예를 들어, 인증된 사용자의 정보를 SecurityContextHolder를 통해 쉽게 접근하고 사용할 수 있습니다.
- 컨트롤러에서 접근: Spring Security에서는 컨트롤러나 서비스 계층에서 SecurityContextHolder를 사용하여 인증된 사용자의 정보를 가져와 사용할 수 있습니다.
@Controller
public class MyController {
@GetMapping("/current-user")
public String getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName(); // 인증된 사용자의 이름
return "현재 사용자: " + username;
}
}
위의 예시에서 SecurityContextHolder.getContext().getAuthentication().getName()을 통해 현재 인증된 사용자의 이름을 가져옵니다.
요약:
- SecurityContextHolder는 Spring Security에서 인증된 사용자의 정보를 보관하고 관리하는 핵심적인 역할을 합니다.
- 인증이 성공하면 Authentication 객체가 SecurityContextHolder에 저장되어, 애플리케이션 내의 다른 컴포넌트에서 쉽게 접근할 수 있습니다.
- Authentication 객체는 사용자의 세부 정보(Principal), 권한(Authorities), 인증 상태 등을 포함하고 있으며, 이를 통해 애플리케이션은 사용자의 인증 정보를 활용할 수 있습니다.
'Spring and Spring Boot > Class, Annotation, Library' 카테고리의 다른 글
Spring Security Library : DispatcherServlet Class (0) | 2025.03.16 |
---|---|
Spring Security Library : HttpServletRequest Interface (0) | 2025.03.16 |
Library : Mockito에서 제공하는 when ~ then 구문을 활용한 스프링부트 단위 테스트 (0) | 2025.03.04 |
Annotation : HTTP 요청 데이터 바인딩 방법 비교하기 (@RequestBody, @RequestParam, @ModelAttribute) (1) | 2025.02.27 |
Class : HTTP 응답을 표현하는 데 사용되는 클래스 (ResponseEntity, HttpEntity) (0) | 2025.02.27 |