我正在使用Java配置,并知道我可以添加这样的自定义过滤器:
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
filter.setServletContext(servletContext);
filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
servletContext.addFilter("corsFilter", CorsFilter.class).addMappingForUrlPatterns(null, false, "/*");
servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, true, "/*");
}
这很好用,但感觉就像我在春天的边缘乱砍。
我想要做的是将我的CORS过滤器添加到DelegationFilterProxy。
在我的root配置中,我添加了:
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public Filter CorsFilter() {
return new CorsFilter();
}
并删除了在onStartup中添加自定义过滤器。现在它根本不起作用。
如何将bean添加到我的过滤器链并确保首先调用它?
答案 0 :(得分:3)
您可以像在onStartUp()方法中添加springSecurityFilteChain
一样添加它,例如......
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
DelegatingFilterProxy filter1 = new DelegatingFilterProxy("springSecurityFilterChain");
filter1.setServletContext(servletContext);
filter1.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
DelegatingFilterProxy filter2 = new DelegatingFilterProxy("corsFilter");
servletContext.addFilter("springSecurityFilterChain", filter1).addMappingForUrlPatterns(null, true, "/*");
servletContext.addFilter("corsFilter",filter2).addMappingForUrlPatterns(null, false, "/*");
}
答案 1 :(得分:0)
要使用Java配置简单地全局启用CORS过滤器,请尝试:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}