SpringSecurity

SpringSecurity [SecurityContextHolder]

성찬우 2022. 6. 24. 21:04

시큐리티의 메인이라고 할 수 있는 SecurityContextHolder이다. 

1. 시큐리티에서 인증된 내용들을 가지고있으며,

2. [SecurityContext] 를 포함하고 있고 

3. SecurityContext 를 현재 스레드와 연결해 주는 역할을 한다. (ThreadLocal 사용)

 

SecurityContextHolder가 시큐리티에서 인증된 내용들을 가지고있다 라는 것을 알았으니 

우리는 SecurityContextHolder 를 통해서 유저의 정보를 확인 할 수 있다. 

기본적으로 다음과 같다. 

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

SecurityContextHolder에는 인증된 객체만이 들어가는데 이 객체는 Authentication 객체이다. 

logout 하기 전까지는 들어있다. 

authentication 이라는 Authentication 객체를 쓰고 . 을 눌러보면 다양한 메서드들이 나오는것을 확인 할 수 있다. 

Authentication객체가 무엇을 포함하고 있는지에 대해서 알아보겠다.

 


1

Object getPrincipal();

Principal 은 인증이 되는 주체이다. ("주체"에 해당하는 정보)

사용자 이름과 암호가 있는 인증 요청의 경우 username 입니다. 

요청시에는 인증 요청에 대한 내용을 채워야하며 

UserDetails 객체를 만든다. 

 

Returns:

인증되는 주체 또는 인증 후 인증된 주체. 시큐리티의 User 타입


2

Collection<? extends GrantedAuthority> getAuthorities();

AuthenticationManager 에 의해 세팅되며 , 권한을 나타냅니다. 

클래스는 신뢰할 수 있는 AuthenticationManager에 의해 설정되지 않았을 경우 해당 값에 의존해서는 안된다. 

구현시 반환된 컬렉션 배열에 대한 수정사항이 AuthenticationManager 객체에 영향을 주어서는 안된다. 

 

Returns:

주체에 부여된 권한 또는 토큰이 인증되지 않았을 경우 빈컬렉션( null이 아니다. )

 


3

boolean isAuthenticated();

인증 토큰을 AuthenticationManager  에 제공해야하는지 여부를 AbstractSecurityInterceptor에 알리기 위해서 사용됨.

일반적으로는 AuthenticationManager (또는 AuthenticationProviders)은 인증 성공 이후 불변하는 인증 토큰을 반환하며, 

이 경우 토큰은 이 메서드에 안전하게 True를 반환 할 수 있습니다. 

 true를 반환하면 더 이상 모든 요청에 대해 인증 관리자를 호출할 필요가 없으므로 성능이 향상됩니다.

 

Returns:

토큰이 인증되었으며 AbstractSecurityInterceptor가 재인증을 위해 토큰을 AuthenticationManager 에 다시 제시 할 필요가 없는 경우 True를 반환합니다. 

 

 


4

Object getCredentials();

credentials 자격을 의미함. 주체가 correct 한지 증명하는.

보통 password로 하지만 AuthenticationManager과 관련있는 것도 됩니다. 

Caller는 자격증명을 채워야 합니다. 

 

Returns:
Principal의 identity를 증명하는 credential  [저는 이거 먼소리인지 잘 모르겠음]ㅜ


 

 

SecurityContextHolder의 특징중 하나는 LocalThread의 사용이다. 

 

즉, Thread가 달라질 경우 제대로된 Authentication information 을 가져올 수 없다. 

때문에 SecurityContextHolder가 제공하는 다른 전략을 고민해 봐야 한다. 

 

 

하지만 우리는 Web 을 개발 하기 떄문에 이부분에 대해서는 크게 걱정할 필요는 없다.