[SpringBoot] 인증과 권한 관리 SecurityContextHolder
반응형
SecurityContextHolder는 Spring Security 프레임워크에서 사용자 인증과 권한 관리를 위해 중요한 역할을 합니다. 이 포스팅에서는 SecurityContextHolder의 사용목적, 기능, 그리고 사용방법을 설명하겠습니다.
1. 사용목적
SecurityContextHolder는 현재 요청의 컨텍스트에서 인증 정보를 쉽게 가져올 수 있도록 해줍니다. 이를 통해 애플리케이션에서 사용자의 ID나 권한 정보를 확인할 수 있습니다1.
2. 기능
- 현재 사용자 인증 정보 관리: 현재 요청의 컨텍스트에서 인증 정보를 쉽게 가져올 수 있습니다.
- 요청 스레드 기반의 보안 처리: 요청 스레드의 메모리에 인증 정보를 저장하여 무상태 환경에서도 사용할 수 있습니다.
- 스프링과의 통합: 다양한 보안 작업을 수행하며, 인증 및 권한 관리를 일관되게 처리할 수 있습니다.
3. 사용방법
SecurityContextHolder는 기본적으로 ThreadLocal을 사용하여 현재 스레드의 메모리에 인증 정보를 저장합니다. 이를 통해 각 요청은 독립적인 인증 정보를 가질 수 있습니다1.
예제 코드
java
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.dto.UserDTO;
@RestController
public class UserController {
@GetMapping("/api/current-user")
public UserDTO getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDTO) {
return (UserDTO) authentication.getPrincipal();
} else {
throw new RuntimeException("인증된 사용자가 없습니다.");
}
}
}
이 코드는 컨트롤러에서 현재 인증된 사용자의 정보를 가져오는 방법을 보여줍니다. SecurityContextHolder.getContext().getAuthentication()을 통해 인증 정보를 가져와서 사용자 정보를 반환합니다.
반응형
'낙서장[1] > 2. SpringBoot' 카테고리의 다른 글
[SpringBoot] 게시글 등록 주요 애노테이션 (0) | 2025.02.07 |
---|---|
[SpringBoot] 인증 JWT 개념 (0) | 2025.02.07 |
[SpringBoot] @RequestBody 애노테이션 (0) | 2025.01.24 |