728x90
반응형
SMALL
Spring Security란?
- 스프링 프레임워크의 보안 모듈로, 애플리케이션의 인증(Authentication)과 인가/권한 부여(Authorization)를 담당합니다. 이는 웹 애플리케이션 및 서비스의 보안을 강화하고, 다양한 보안 기능을 쉽게 구현할 수 있도록 돕습니다.
필터
- 필터의 흐름
HTTP 요청 -> WAS -> 필터 -> 서블릿 -> 컨트롤러 - 필터체인
HTTP 요청 -> WAS -> 필터1 -> 필터2 ->필터3... -> 서블릿 -> 컨트롤러
의존성 추가
dependencies {
implementation "org.springframework.boot:spring-boot-starter-security"
}
동작원리
- 클라이언트로부터 요청이 들어오면 DelegatingFilterProxy가 이를 가로챕니다.
- DelegatingFilterProxy는 요청을 FilterChainProxy로 위임합니다.
- FilterChainProxy는 요청 URL에 맞는 SecurityFilterChain을 찾습니다.
- 해당 SecurityFilterChain의 필터들이 순차적으로 실행됩니다.
- 각 필터는 인증, 권한 부여, CSRF 보호 등의 보안 기능을 수행합니다.
SecurityFilterChain 등록
- spring security 의존성 추가시에 기본적인 DefaultSecurityFilterChain 하나가 등록된다.
- 내가 원하는 SecurityFilterChain을 등록하기 위해서는 SecurityFilterChain을 리턴하는 @Bean 메소드를 등록하면 된다.
//커스텀 시큐리티필터체인 등록
//여러개 등록가능
//SecurityFilterChain에 대한 경로 매핑 securityMatchers
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChainA(HttpSecurity http) throws Exception {
http
.securityMatchers((auth) -> auth.requestMatchers("/user"));
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/user").permitAll());
return http.build();
}
@Bean
public SecurityFilterChain filterChainB(HttpSecurity http) throws Exception {
http
.securityMatchers((auth) -> auth.requestMatchers("/admin"));
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/admin").authenticated());
return http.build();
}
}
- securityMatchers 가 없을 경우 예시
- /admin으로 요청이 들어올 경우
- securityMatchers 가 없으면 인가작업 매핑이 이뤄지지 않아
- filterChainA가 선택 되어 오류가 발생
- 특정 요청은 필터를 거치지 않도록 처리
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().requestMatchers("/img/**");
}
용어설명
- DelegatingFilterProxy
스프링 Bean을 찾아 요청을 넘겨주는 서블릿 필터
- FilterChainProxy
스프링 시큐리티 의존성을 추가하면 DelegatingFilterProxy에 의해 호출되는 SecurityFilterChain들을 들고 있는 Bean
- SecurityFilterChain
스프링 시큐리티 필터들의 묶음으로 실제 시큐리티 로직이 처리되는 부분, FilterChainProxy가 SecurityFilterChain들을 들고 있다.
내부구조
- 좌: 기본 spring security 의존성 등록 우: 커스텀Config 추가
SecurityContextHolder
- 역할
SecurityFilterChain 내부에 존재하는 각각의 필터가 시큐리티 관련 작업을 진행한다.
모든 작업은 기능 단위로 분업하여 진행함으로 앞에서 한 작업을 뒤 필터가 알기 위한 저장소 개념이 필요하다.
사용자의 보안 정보를 저장하고 접근하기 위해 사용되는 클래스입니다.
이를 통해 애플리케이션 전반에서 인증 및 권한 부여 관련 정보를 쉽게 관리할 수 있습니다. - Authentication 구성요소
- principal: 사용자를 식별합니다. 사용자 이름/암호로 인증할 때 이는 종종 .의 인스턴스입니다 UserDetails.
- credentials: 종종 비밀번호입니다. 많은 경우, 이는 사용자가 인증된 후 지워져서 누출되지 않도록 합니다.
- authorities: GrantedAuthority인스턴스는 사용자에게 부여된 상위 수준 권한입니다. 두 가지 예로는 역할과 범위가 있습니다.
GenericFilterBean vs OncePerRequestFilter
- 모든 필터들은 GenericFilterBean 또는 OncePerRequestFilter 두가지의 추상클래스를 기반으로 구현 된다.
- 두 추상클래스 차이점
- GenericFilterBean
- 내부적으로 동일한 필터를 여러 번 통과하더라도 통과한 수 만큼 내부 로직이 실행된다.
- doFilter 메서드를 오버라이드하여 필터링 로직을 구현합니다.
public class CustomFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 필터 로직 구현 chain.doFilter(request, response); } }
- OncePerRequestFilter
- 내부적으로 동일한 필터를 여러 번 통과하더라도 첫 한 번만 내부 로직이 실행된다.
- doFilterInternal 메서드를 오버라이드하여 필터링 로직을 구현합니다.
public class CustomOncePerRequestFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 필터 로직 구현 filterChain.doFilter(request, response); } }
- GenericFilterBean
- 커스텀필터를 만들경우 해당 차이점을 파악하여 상속받아서 커스텀필터 작성
728x90
반응형
LIST
'Spring' 카테고리의 다른 글
Undertow (1) | 2025.01.02 |
---|---|
Spring Security 내부 필터 (1) | 2024.10.24 |
Querydsl 기본 사용법 (2) | 2024.09.30 |
Spring Data JPA (1) | 2024.09.30 |
Spring JPA (2) (0) | 2024.09.30 |