filter

๊ธฐ๋ณธ์ ์ธ ํ•„ํ„ฐ๊ตฌํ˜„์— ๊ด€ํ•œ ๋‚ด์šฉ

์•„๋ž˜์ฒ˜๋Ÿผ ํ•„ํ„ฐ๋ฅผ ๊ตฌํ˜„ํ•˜๋ฉด doFilter ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œํ•œ๋‹ค.

ํ•„ํ„ฐ์— ๊ฑธ๋ ค์„œ ํ”„๋กœ๊ทธ๋žจ์ด ๋๋‚˜์ง€ ์•Š๋„๋ก filterChain.doFilter ๋กœ ๋ฆฌํ€˜์ŠคํŠธ์™€ ๋ฆฌ์ŠคํŽ€์Šค๋ฅผ ๋„˜๊ฒจ์ฃผ์–ด์•ผํ•œ๋‹ค.

import javax.servlet.*;
import java.io.IOException;

public class myfilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) 
            throws IOException, ServletException {
        System.out.println("filter");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

ํ•ด๋‹น ํ•„ํ„ฐ๋ฅผ ์‹œํ๋ฆฌํ‹ฐ์—๋„ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๋“ฑ๋กํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
   return http
         .addFilterBefore(new myfilter(), BasicAuthenticationFilter.class)
         //ํ•„ํ„ฐ ๋“ฑ๋กํ•˜์˜€์Œ, BasicAuthenticationFilter๋ณด๋‹ค ๋จผ์ € ๋™์ž‘ํ•˜๋„๋ก ์„ค์ •ํ•œ๊ฒƒ์ž„

๋”ฐ๋กœ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด์„œ ํ•„ํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

์•„๋ž˜์ฒ˜๋Ÿผ ํ•„ํ„ฐ์˜ ์ˆœ์„œ๋ฅผ ์ •ํ•˜์—ฌ ์—ฌ๋Ÿฌ๊ฐœ๋กœ ๋“ฑ๋ก์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<myfilter> filter(){
        FilterRegistrationBean<myfilter> bean = new FilterRegistrationBean<>(new myfilter());
        bean.addUrlPatterns("/*");
        bean.setOrder(0); //๋‚ฎ์€ ๋ฒˆํ˜ธ๊ฐ€ ํ•„ํ„ฐ์ค‘์—์„œ ๊ฐ€์žฅ๋จผ์ € ์‹คํ–‰๋จ
        return bean;
    }
}

๋‹ค๋งŒ, FilterConfig๋Š” ์‹œํ๋ฆฌํ‹ฐ์— ๊ฑด ํ•„ํ„ฐ๋ณด๋‹ค ์ดํ›„์— ์‹คํ–‰๋œ๋‹ค.

์›๋ž˜ ์ผ๋ฐ˜์ ์ธ ์›นํ™˜๊ฒฝ์—์„œ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์„œ๋ฒ„์—๊ฒŒ ์š”์ฒญ์„ ๋ณด๋‚ด๋ฉด DispatcherServlet์ด ์š”์ฒญ์„ ๋ฐ›๊ธฐ ์ด์ „์— ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ๋ฅผ ๊ฑฐ์น˜๊ฒŒ ๋œ๋‹ค. ์Šคํ”„๋ง ์‹œํ๋ฆฌํ‹ฐ๋„ ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ๋กœ ์ž‘๋™ํ•˜์—ฌ ์ธ์ฆ,๊ถŒํ•œ์ฒ˜๋ฆฌ๋ฅผ ์ง„ํ–‰ํ•œ๋‹ค.

์‹œํ๋ฆฌํ‹ฐ์™€ ๊ด€๋ จํ•œ ์„œ๋ธ”๋ฆฟ ํ•„ํ„ฐ๋Š” ์‹ค์ œ๋กœ ์—ฐ๊ฒฐ๋œ ์—ฌ๋Ÿฌ ํ•„ํ„ฐ๋“ค๋กœ ๊ตฌ์„ฑ๋˜์–ด์žˆ์–ด ์ด๋Ÿฐ ๋ชจ์Šต๋•Œ๋ฌธ์— ์ฒด์ธ์ด๋ผ๋Š” ํ‘œํ˜„์„ ์“ด๋‹ค. ํ•ด๋‹น ํ•„ํ„ฐ์˜ ์—ญํ• ๊ณผ ํ๋ฆ„์„ ์•Œ์•„์•ผ ํ•„ํ„ฐ๋ฅผ ์ปค์Šคํ„ฐ ๋งˆ์ด์ง• ๊ฐ€๋Šฅํ•˜๋‹ค.

SecurityFilterChain ์˜ ๊ตฌ์กฐ https://siyoon210.tistory.com/32

Last updated