SecurityContextHolder
Security 보안 Context 맥락 Holder 보유자 라는 의미로, spring-security-core 의존성 패키지에 포함되어 있는 클래스이다. Spring Security 내에서 현재 인증 정보를 저장하고 관리하는 데에 큰 역할이 있다. 특히, Spring Security 의 인증 상태인, Authentication 객체를 전역적으로 저장하며, JWT 인증을 설정할 때 Authentication 객체를 적용한다.
// SecurityContextHolder 에서 Authentication 설정하기
SecurityContextHolder.getContext().setAuthentication(authentication);
설정하는 메소드에서도 알 수 있다시피, SecurityContextHolder 안에는, SecurityContext 가 있고(getContext()로 불러오므로), 또 그 안에 Authentication 객체가 있다.
SecurityContextHolder > SecurityContext > Authentication
이런 포함관계를 가지는 것이다.
Authentication 객체
현재 사용자의 인증 상태를 나타내며, JWT 검증 후 생성된 Authentication 객체를 SecurityContext 에 설정하여 인증 상태를 유지하는 객체이다. UsernamePasswordAuthenticationToken 같은 구현체를 사용하여 생성할 수 있다.
Authentication authentication = new UsernamePasswordAuthenticationToken(
username, // Principal
null, // Credentials (JWT에서는 필요 없음)
authorities // GrantedAuthority 리스트
);
- Principal: 현재 사용자를 식별하는 정보 (주로 UserDetails 객체 또는 사용자 이름).
- Credentials: 인증 정보 (예: 비밀번호, 인증 토큰).
- Authorities: 사용자 권한(역할)의 리스트 (GrantedAuthority 객체로 구성).
- Details: 추가적인 인증 정보 (예: IP 주소, 세션 정보).
- Authenticated: 인증 여부(Boolean).
Authorities 리스트
이 권한 리스트는, 특정 사용자에게 여러 권한을 줄 수도 있기 때문에 한 사용자에게 리스트로 권한이 주어지는 것이다. Spring Security 에서 권한은 GrantedAuthority 인터페이스로 표현되며, 일반적으로 ROLE_ 접두어를 붙이고 표현된다. (ex. ROLE_USER, ROLE_ADMIN)
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"))) {
System.out.println("사용자가 관리자 역할을 가지고 있습니다.");
}
'Framework > Spring' 카테고리의 다른 글
[SAML 2.0] `SP-Initiated SSO 방식` vs `IdP-Initiated SSO 방식` (0) | 2025.01.29 |
---|---|
[Servlet] ServletRegistrationBean : Spring 이 Servlet 을 다루는 방법 (0) | 2025.01.07 |
[SAML 2.0] IdP 와 SP 인증을 직접 구현해보자. (2) - SP 설정 : SpringBoot 편 (4) | 2024.12.20 |
[SAML 2.0] IdP 와 SP 인증을 직접 구현해보자. (1) - IdP 설정 (0) | 2024.12.20 |
[SAML 2.0] Security Assertion Markup Language (0) | 2024.12.18 |