Spring Security 란?
스프링 시큐리티에서는 인증과 인가(권한)을 분리하여 체크할 수 있도록 구조를 만들었다.
- Authentication(인증) : A라고 주장하는 주체(user,subfject,principal)가 A가 맞는지 확인
- 코드에서 Authenitication : 인증 과정에서 사용되는 핵심 객체
- Id/Password, JWT, Oauth 등 여러 방식으로 인증에 필요한 값이 전달되는데 이것을 하나의 인터페이스로 받아 수행하도록 추상화 하는 역할
- 코드에서 Authenitication : 인증 과정에서 사용되는 핵심 객체
- Authorization(인가) : 특정 자원에 대한 권한이 있는지 확인하는 것
- Auuthentication을 거치고 인증이 되었으면 권한/인가 가 있는 지 확인 후, 서버 자원에 대해서 접근 할 수 있다.
- Credential(증명서) : 인증 과정 중, 주체가 본인을 인증하기 위해 서버에 제공하는 것(Id/Password)
- Spring Security는 서블릿 필터를 기반으로 동작하는데, 서블릿 필터는 서블릿이 호출 되기 전 전처리나 응답 이후 후처리 작업을 할 수 없다.
- 따라서 빈을 인식하지 못하는 서블릿 컨테이너를 위해 스프링 프레임 워크는 서블릿 필터의 구현체인 DelegatingFilterProxy를 제공하는데 '업무를 위임하다'라는 뜻을 가진 Delegate의 의미처럼 직접 처리하는 것이 아닌 해당 필터를 등록하면 ApplicationContext에서 Filter Bean들을 찾아 실행한다.
- 고유한 설정을 가진 여러개의 securityFilterChain을 두고 FilterChainProxy 설정을 통해 URL마다 SecurityFilterChain을 매핑할 수 있다. 특정 요청에 대해 스프링 시큐리티가 무시하길 바란다면, SecurityFilterChain에 보안 Filter를 0개 설정해서 무시할 수 있다.
Spring Security Structure
- 사용자가 로그인 정보와 함께 인증 요청(HttpRequest)
- AuthenticationFilter가 요청을 가로챔, 이 때 가로챈 정보를 통해 UsernamePasswordAuthenticationToken 객체 생성(아직 미검증 Authentication)
- ProviderManager 구현체인 AuthenticationManager에게 UsernamePasswordAuthenticationToken 객체 전달
- AuthenticationProvider에 UsernamePasswordAuthenticationToken 객체 전달
- 실제 DB로부터 사용자 인증 정보를 가져오는 UserDetailsService에 사용자 정보를 넘겨줌
- 넘겨받은 정보를 통해 DB에서 찾은 사용자 정보인 UserDetails 객체 생성
- AuthenticationProvider는 UserDetails를 넘겨 받고 사용자 정보를 비교
- 인증이 완료되면, 사용자 정보를 담은 Authenticatino 객체를 반환
- 최초의 AuthenticationFilter에 Authentication객체가 반환됨
- Authentication 객체를 SecurityContext에 저장
여기서 주의깊게 봐야할 부분은 UserDetailsService와 UserDetails이다. 실질적인 인증 과정은 사용자가 입력한 데이터(ID,PW등) 와 UserDetailsService의 loadUSerByUsername() 메소드가 반환하는 UserDetails객체를 비교함으로써 동작한다. 따라서 UserDetailsService와 UserDetails 구현을 어떻게 하느냐에 따라 인증의 세부 과정이 달라진다.
Authentication
현재 접근하는 주체의 정보와 권한을 담는 인터페이스이다. Authentication 객체는 SecurityContext에 저장되며,
SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.
|
public interface Authentication extends Principal, Serializable { |
|
// 현재 사용자의 권한 목록을 가져옴 |
|
Collection<? extends GrantedAuthority> getAuthorities(); |
|
|
|
// credentials(주로 비밀번호)을 가져옴 |
|
Object getCredentials(); |
|
|
|
Object getDetails(); |
|
|
|
// Principal 객체를 가져옴 |
|
Object getPrincipal(); |
|
|
|
// 인증 여부를 가져옴 |
|
boolean isAuthenticated(); |
|
|
|
// 인증 여부를 설정함 |
|
void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException; |
|
|
|
} |
UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken은 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로, User의 ID가 Principal 역할을 하고, Password가 Credential의 역할을 한다. UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두번째는 인증이 완료된 객체를 생성한다.
|
public abstract class AbstractAuthenticationToken implements Authentication, CredentialsContainer { |
|
} |
|
|
|
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken { |
|
|
|
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; |
|
|
|
// 주로 사용자의 ID에 해당 |
|
private final Object principal; |
|
|
|
// 주로 사용자의 PW에 해당 |
|
private Object credentials; |
|
|
|
// 인증 완료 전의 객체 생성 |
|
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) { |
|
super(null); |
|
this.principal = principal; |
|
this.credentials = credentials; |
|
setAuthenticated(false); |
|
} |
|
|
|
// 인증 완료 후의 객체 생성 |
|
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, |
|
Collection<? extends GrantedAuthority> authorities) { |
|
super(authorities); |
|
this.principal = principal; |
|
this.credentials = credentials; |
|
super.setAuthenticated(true); // must use super, as we override |
|
} |
|
} |
AuthenticationManager
인증에 대한 부분은 AuthenticationManager를 통해서 처리하게 되는데, 실질적으로는 AuthenticationManager에등록된 AuthenticationProvider에 의해 처리된다. 인증에 성공하면 두번째 생성자를 이용해 객체를 생성하여 SecurityContext에 저장한다.
|
public interface AuthenticationManager { |
|
|
|
Authentication authenticate(Authentication authentication) throws AuthenticationException; |
|
|
|
} |
AuthenticationProvider
AuthenticationProvider에서는 실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할을 한다. 아래와 같은 인터페이스를 구현해 Custom한 AuthenticationProvider를 작성하고 AuthenticationManager에 등록하면 된다.
|
public interface AuthenticationProvider { |
|
|
|
Authentication authenticate(Authentication authentication) throws AuthenticationException; |
|
|
|
boolean supports(Class<?> authentication); |
|
|
|
} |
ProviderManager
AuthenticationManager를 implements한 ProviderManager는 AuthenticationProvider를 구성하는 목록을 갖는다.
|
public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean { |
|
|
|
public List<AuthenticationProvider> getProviders() { |
|
return this.providers; |
|
} |
|
|
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException { |
|
Class<? extends Authentication> toTest = authentication.getClass(); |
|
AuthenticationException lastException = null; |
|
AuthenticationException parentException = null; |
|
Authentication result = null; |
|
Authentication parentResult = null; |
|
int currentPosition = 0; |
|
int size = this.providers.size(); |
|
|
|
// for문으로 모든 provider를 순회하여 처리하고 result가 나올때까지 반복한다. |
|
for (AuthenticationProvider provider : getProviders()) { ... } |
|
} |
|
} |
UserDetailsService
UserDetailsService는 UserDetails 객체를 반환하는 하나의 메소드만을 가지고 있는데, 일반적으로 이를 implements한 클래스에 UserRepository를 주입받아 DB와 연결하여 처리한다.
|
public interface UserDetailsService { |
|
|
|
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; |
|
|
|
} |
UserDetails
인증에 성공하여 생성된 UserDetails 객체는 Authentication객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다. UserDetails를 implements하여 처리할 수 있다.
|
public interface UserDetails extends Serializable { |
|
|
|
// 권한 목록 |
|
Collection<? extends GrantedAuthority> getAuthorities(); |
|
|
|
String getPassword(); |
|
|
|
String getUsername(); |
|
|
|
// 계정 만료 여부 |
|
boolean isAccountNonExpired(); |
|
|
|
// 계정 잠김 여부 |
|
boolean isAccountNonLocked(); |
|
|
|
// 비밀번호 만료 여부 |
|
boolean isCredentialsNonExpired(); |
|
|
|
// 사용자 활성화 여부 |
|
boolean isEnabled(); |
|
|
|
} |
SecurityContextHolder
SecurityContextHolder는 보안 주체의 세부 정보를 포함하여 응용프로그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다.
SecurityContext
Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication을 저장하거나 꺼내올 수 있다.
|
SecurityContextHolder.getContext().setAuthentication(authentication); |
|
SecurityContextHolder.getContext().getAuthentication(authentication); |
GrantedAuthority
GrantedAuthority는 현재 사용자(Principal)가 가지고 있는 권한을 의미하며, ROLE_ADMIN이나 ROLE_USER와 같이 ROLE_*의 형태로 사용한다. GrantedAuthority 객체는 UserDetailsService에 의해 불러올 수 있고, 특정 자원에 대한 권한이 있는지를 검사하여 접근 허용 여부를 결정한다.
출처: https://dev-coco.tistory.com/174 [슬기로운 개발생활:티스토리]
'SPRING-SECURITY' 카테고리의 다른 글
JWT AccessToken, RefreshToken의 흐름 (0) | 2024.01.17 |
---|---|
JWT + OAuth2 구현 - (5) (0) | 2023.12.14 |
JWT + OAuth 구현 - (4) (0) | 2023.12.14 |
JWT + OAuth2 구현 - (3) (0) | 2023.12.13 |
JWT + OAuth2 구현 - (2) (0) | 2023.12.13 |