SecurityContextHolder
- Security Context 데이터를 읽거나 쓸 수 있는 API 를 제공
- Security Context를 담고 있는 그릇과 같은 역할
- 기본 구현은 ThreadLocal을 활용
- Spring Web MVC는 Thread per Request 모델을기반으로 동작하고, SecurityContextHolder는 ThreadLocal을 기반으로 함. >> Spring Web MVC에서 controller, service, repository 어느 부분에서든 SecurityContextHolder를 통해 SecurityContext를 조회할 수 있다.
- Thread가 요청을 끝내고 Thread Pool에 반환되기 전 사용된 ThreadLocal 변수를 clear해야 하는데, SpringSecurity 에서는 SecurityContextHolder가 해당 메소드를 가지고, FilterChainProxy.doFilter()의 finally 블록에 호출된다.
- clearContext()는 SecurityContextHolderStrategy 인터페이스를 호출
- SecurityContextHolderStrategy 의 기본 구현체는 ThreadLocalSecurityContextHolderSgrategy임.
- ThreadLocal 변수의 내용을 모두 삭제.
... 생략
finally{
SecurityContextHolder.clearContext();
reqest.removeAttrivbute(FILTER_APPLIED);
}
Security Context
Authentication을 get, set
Authentication
- 인터페이스
- Authentication의 구현체:
- AbstractAuthenticaitonToken
- AnnonymousAuthenticationToken: 인증 없는 임의의 사용자
- JaasAuthenticationToken
- PreAuthenticatedAuthenticationToken
- RememberMeAuthenticationToken: rememberMe를 통해 인증된 사용자
- RunAsUserToken
- TestingAuthenticationToken
- UsernamePasswordAuthenticationToken: id, password를 통해 인증된 사용자
- Authentication의 method
- getAuthorities(): 사용자의 권한 목록을 반환
- getPrincipal():
- Principal: Authenticaion으로 표현되는 사용자를 인증 여부와 무관하게 하나로 표현
- 인증 전: getPrincipal() -> 사용자가 입력한 로그인 아이디를 반환
- 인증 후: getPrincipal() -> 사용자 객체 반환
- return Object: 인증 전과 후에 모두 다르기 때문에 return type이 Object로 선언됨
- Principal: Authenticaion으로 표현되는 사용자를 인증 여부와 무관하게 하나로 표현
- isAuthenticated(): 사용자의 인증 여부를 반환 (boolean)
- setAuthenticated(boolean isAuthenticated): 사용자의 인증 여부를 설정
요약
- SecurityContextHolder는 ThreadLocal 변수를 통해 SecurityContext를 담고있다.
- SecurityContext는 Authentication, 인터페이스 구현체들을 담고 있다.
- Authentication 구현체는 Principal, Credentials, Authorities를 필드로 가진다.
- Principal: (인증 전): 로그인 아이디 / (인증 후) 사용자 정보를 담은 User 객체
- Credenticals: 사용자 비밀번호
- Authorities: 사용자 권한 목록
'Spring' 카테고리의 다른 글
SpringSecurity: ExceptionTranslationFilter (0) | 2023.04.18 |
---|---|
Spring Security: SecurityContextPersistenceFilter (0) | 2023.04.18 |
Thread Per Request 모델과 ThreadLocal (0) | 2023.04.06 |
Spring Security: AnonymousAuthenticationFilter (0) | 2023.04.06 |
Spring Security: RequestCacheAwareFilter (0) | 2023.04.04 |