스프링/스프링 시큐리티

스프링 시큐리티-아키텍처

coffee. 2023. 8. 23. 14:45

스프링 시큐리티를 프로젝트에 등록하면 다음과 같은 서블릿 필터들이 생성 됩니다.

필터체인

클라이언트가 서버로 요청을 보내면 그아래 수많은 필터들에 의해 인증이 진행 됩니다.

 

하지만 서블릿 필터는 서블릿 컨테이너에서 관리를합니다.

따라서 필터에서 스프링의 빈을 사용할 수는 없는 것입니다.

 

DelegatingFilterProxy

스프링은 delegatingfilterProxy라는 필터를 제공합니다.

이 필터는 서블릿 컨테이너와 스프링 컨테이너 사이의 다리 역할을 합니다.

DelegatingFilterProxy

SecurityFilterChain

SecurityFilterChain은 FilterChainProxy에 의해 호출됩니다.

securityFilterChain은 빈 입니다.

이것은 모든 스프링 시큐리티 지원의 시작점입니다.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(Customizer.withDefaults())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }

}

시큐리티의 필터체인을 설정 할때는 다음과같은 빈을 등록 합니다.

 

필터 추가하기 예제

MyFilter.java

public class MyFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		System.out.println("hello filter");
		chain.doFilter(request, response);
	}

}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
	
	@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http
        .addFilterBefore(new MyFilter(), AuthorizationFilter.class); 
        return http.build();
    }
	
}

이제 localhost:8080으로 요청을 보내면 "hello filter"가 출력 된다.!