본문 바로가기
Back-End/Spring Security

Authentication Components (2) SecurityContextHolder, SecurityContext

by sharekim 2021. 3. 17.

SecurityContextHolder

SecurityContextHolder

The SecurityContextHolder is where Spring Security stores the details of who is authenticated. Spring Security does not care how the SecurityContextHolder is populated. If it contains a value, then it is used as the currently authenticated user.

The simplest way to indicate a user is authenticated is to set the SecurityContextHolder directly.

SecurityContextHolder는 스프링시큐리티가 인증정보를 저장하는 곳이다. SecurityContextHolder가 value를 가지고 있으면 SecurityContextHolder는 현재 유저로서 사용된다.

유저인증의 가장 간단한 방법은 SecurityContextHolder를 셋팅하는 것이다.

 

Example 53. Setting SecurityContextHolder

SecurityContext context = SecurityContextHolder.createEmptyContext(); 
Authentication authentication =
    new TestingAuthenticationToken("username", "password", "ROLE_USER"); 
context.setAuthentication(authentication);

SecurityContextHolder.setContext(context); 

 

SecurityContextHolder를 셋팅하는 방법은,

1. SecurityContext를 EmptyContext로 생성

2. Authentication에 AuthenticationToken을 담고, 담은 Authentication을 생성한 SecurityContext에 셋팅

3. SecurityContextHolder에 SecurityContext를 셋팅

 

 

Example 54. Access Currently Authenticated User

SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
String username = authentication.getName();
Object principal = authentication.getPrincipal();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

현재 인증된 유저에 접근하는 방법

1. SecurityContext객체를 context 변수에 담는다.

2. context변수로부터 Authentication을 얻어 authentication 변수에 담는다.

3. authentication의 getName(), getPrincipal() 메서드를 이용해 username 과 principal을 얻는다.

4. authentication의 getAuthorities() 메서드로 GrantedAuthority Collection을 얻는다.

 

SecurityContext

The SecurityContext is obtained from the SecurityContextHolder.

The SecurityContext contains an Authentication object.

SecurityContext는 Authentication Object를 포함하는 것으로 SecurityContextHolder에 의해 얻어지는 것이다.

 

** 모든 출처는 Spring.io입니다.

댓글