转载

spring-security的过滤器链

每次在项目中使用spring-security都想调试其内部逻辑,在这里记录一下调试的入口点,以防忘记。

正文

调试的入口在 org.springframework.security.web.DefaultSecurityFilterChain#DefaultSecurityFilterChain(org.springframework.security.web.util.matcher.RequestMatcher, java.util.List<javax.servlet.Filter>)

public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {
	logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
	this.requestMatcher = requestMatcher;
	this.filters = new ArrayList<>(filters); // 在这里加断点就能看到整个过滤器链了
}

另外记住一点:当spring-mvc中配有CORS,并且在spring-security配置中没有将 CorsConfigurationSource 明确配置到 corsFilter 这个 Bean 上时,spring-security会“借用”spring-mvc中的CORS配置,切勿配置多余的CORS,关于这个行为可从调试 org.springframework.web.filter.CorsFilter 得知(另外官方文档上也明确写了这个行为了)

...
        // https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors
        private CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowedOrigins(Arrays.asList(webConfigurationProperties.getCors().getAllowedOrigins()));
            corsConfiguration.setAllowedMethods(Arrays.asList(webConfigurationProperties.getCors().getAllowedMethods()));
            corsConfiguration.setAllowedHeaders(Arrays.asList(webConfigurationProperties.getCors().getAllowedHeaders()));
            corsConfiguration.setExposedHeaders(Arrays.asList(webConfigurationProperties.getCors().getExposedHeaders()));
            corsConfiguration.setAllowCredentials(webConfigurationProperties.getCors().getAllowCredentials());
            corsConfiguration.setMaxAge(webConfigurationProperties.getCors().getMaxAge());
            UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
            urlBasedCorsConfigurationSource.registerCorsConfiguration(webConfigurationProperties.getCors().getMapping(), corsConfiguration);
            return urlBasedCorsConfigurationSource;
        }
        
        @Bean
        public CorsFilter corsFilter() {
            return new CorsFilter(corsConfigurationSource());
        }
...
原文  https://since1986.github.io/blog/4c9ae68d.html
正文到此结束
Loading...