Spring Security란?
Spring Security: Spring MVC 기반 애플리케이션의 인증(Authentication)과 인가(Authorization or 권한 부여) 기능을 지원하는 보안 프레임워크. Spring 기반 애플리케이션 보안을 위한 사실상의 표준이다.
Authentication(인증): 해당 사용자가 본인이 맞는지 확인하는 절차
- 인증을 정상적으로 수행하기 위해 사용자를 식별하기 위한 정보가 필요하다. 이를 Credential이라 부른다.
- ex) 신분증
Authorization (인가, 권한 부여): 인증된 사용자가 요청된 자원에 접근가능한가를 결정하는 절차
- 반드시 인증 과정 이후에 수행되어야 한다. 권한은 일반적으로 역할(Role)형태로 부여된다.
- ex) 사원증, 사무실에 들어갈 수 있는 권한
Spring Security는 이러한 인증과 인가를 위해 Principal(주체)을 아이디로, Credential을 비밀번호로 사용하는 Credentail 기반의 인증 방식을 사용한다.
Spring Security를 애플리케이션에 적용하면 다음과 같은 일들을 할 수 있다.
- 다양한 유형(폼 로그인 인증, 토큰 기반 인증, OAuth2 기반 인증, LDAP 인증)의 사용자 인증 기능 적용
- 애플리케이션 사용자의 역할(Role)에 따른 권한 레벨 적용
- 애플리케이션에서 제공하는 리소스에 대한 접근 제어
- 민감한 정보에 대한 데이터 암호화
- SSL 적용
- 일반적으로 알려진 웹 보안 공격 차단
Authentication, Authorizationdp에 대한 부분을 Filter 흐름에 따라 처리한다. Filter가 무엇인지는 해당 블로깅 참고
https://memodayoungee.tistory.com/114
[Spring] Filter, Interceptor, AOP의 차이점에 대해
AOP를 공부하게 되면 뒤따로오는 개념인 필터와 인터셉터. 인터셉터를 오늘 처음으로 어떤 것인지에 대해 공부하게 됐는데, AOP와 비슷하다 생각했다. 그래서 AOP와 인터셉터의 차이점에 대해 블
memodayoungee.tistory.com
FilterChain
⭐ DelegatingFilterProxy
Spring Security는 DelegatingFilterProxy 라는 필터를 만들어 메인 Filter Chain에 끼워넣는다. 때문에 DelegatingFilterProxy 가 Bean으로 등록된 Spring Security의 필터를 사용하는 시작점이 된다.
DelegatingFilterProxy는 서블릿 컨테이너 영역의 필터와 ApplicationContext에 Bean으로 등록된 필터들을 연결해 주는 브릿지 같은 역할을 해준다.
⭐ FilterChainProxy
사용자가 처음 요청을 하면 DelegatingFilterProxy가 요청을 받고 FilterChainProxy에게 요청을 위임한다. 이 위임받은 요청으로 Filter들에게 순서대로 요청을 맡긴다. 쉽게 말하면 Spring Security의 Filter를 사용하기 위한 진입점인 것이다.
@Configuration
@EnableWebSecurity(debug = true)
// public class SecurityConfiguration extends WebSecurityConfigurerAdapter { // 5.7 이전버전
public class SecurityConfiguration {
// Filter Chain 구성
@Bean
public SecurityFilterChain filterChainV3(HttpSecurity http) throws Exception {
http
.headers().frameOptions().sameOrigin()
.and()
.csrf().disable()
.formLogin()
.loginPage("/auths/login-form")
.loginProcessingUrl("/process_login")
.failureUrl("/auths/login-form?error")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.exceptionHandling().accessDeniedPage("/auths/access-denied")
.and()
.authorizeHttpRequests(authorize -> authorize
.antMatchers("/orders/**").hasRole("ADMIN")
.antMatchers("/members/my-page").hasRole("USER")
.antMatchers("/**").permitAll()
);
return http.build();
}
}
Spring Security 5.7 이전 버전에서는 WebSecurityConfigurerAdapter를 상속하는 형태의 방법을 주로 사용했지만, 5.7.0에서 Deprecated 됐다. 따라서 SecurityFilterChain을 bean으로 등록해서 사용해야 한다.
Filter의 종류
SecurityContextPersistenceFilter: SecurityContextRepository에서 SecurityContext를 가져오거나 생성
LogoutFilter: 로그아웃 요청을 처리
UsernamePasswordAuthenticationFilter: ID와 Password를 사용하는 실제 Form 기반 유저 인증을 처리
- Authentication 객체를 만들고 AuthenticationManager에게 인증처리를 맡긴다.
- AuthenticationManager는 실질적인 인증을 검증 단계를 총괄하는 AuthenticationProvider에게 인증 처리를 위임한다. 그렇게 해서 UserDetailService와 같은 서비스를 사용해서 인증을 검증할 수 있는 것이다.
ConcurrentSessionFilter: 동시 세션과 관련된 필터(이중 로그인)
RememberMeAuthenticationFilter: 세션이 사라지거나 만료 되더라도, 쿠키 또는 DB를 사용하여 저장된 토큰 기반으로 인증을 처리
AnonymousAuthenticationFilter: 사용자 정보가 인증되지 않았다면 익명 사용자 토큰을 반환
SessionManagementFilter: 로그인 후 Session과 관련된 작업을 처리
ExceptionTranslationFilter: 필터 체인 내에서 발생되는 인증, 인가 예외를 처리
FilterSecurityInterceptor: 권한 부여와 관련한 결정을 AccessDecisionManager에게 위임해 권한부여 결정 및 접근 제어를 처리
HeaderWriterFilter: Request의 HTTP 헤더를 검사해 Header를 추가하거나 빼주는 필터
CorsFilter: 허가된 사이트나 클라이언트의 요청인지 검사
CsrfFilter: CSRF Tocken을 사용하여 Csrf공격을 막아주는 기능을 제공
더 자세한 Filter 목록은 해당 링크를 참고
https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-security-filters
Architecture :: Spring Security
Spring Security’s Servlet support is based on Servlet Filters, so it is helpful to look at the role of Filters generally first. The following image shows the typical layering of the handlers for a single HTTP request. The client sends a request to the ap
docs.spring.io
Reference
코드스테이츠 학습 자료
'Spring > 개념' 카테고리의 다른 글
[Spring] 스프링 AOP (0) | 2023.05.11 |
---|---|
[Spring Security] 스프링 시큐리티의 동작 구조 (0) | 2023.05.11 |
[Spring] Spring 기초 및 모듈 구성, Sprig VS SpringBoot (0) | 2023.05.02 |
[Spring] Filter, Interceptor, AOP의 차이점에 대해 (0) | 2023.04.10 |
[Spring] 스프링(Spring Framework)의 정의와 특징 (0) | 2023.04.02 |