Spring Security中如何忽略指定URL路径?Web.xml配置疑问
嘿,作为Spring Security新手碰到这个问题太正常了,我来给你掰扯清楚~
首先直接给结论:没办法通过web.xml直接实现忽略"/test"路径。原因很简单:你在web.xml里配置的DelegatingFilterProxy只是个"代理",它的作用是把请求转发给Spring容器里真正的springSecurityFilterChain bean,而哪些路径需要走安全校验、哪些要忽略,完全是由Spring Security自己的专属配置来控制的,web.xml管不了这层逻辑。
接下来给你几个可行的方案,看你项目用的是XML配置还是Java配置:
方案一:用Spring Security的XML配置(传统XML项目)
如果你的项目还是用XML来配置Spring Security,那只需要在你的security配置文件里,优先配置要忽略的路径,用<security:http pattern="/test" security="none"/>这个标签,注意一定要放在其他<http>配置的前面,因为Spring Security是按配置顺序匹配路径的。
举个完整的例子:
<!-- 先配置忽略路径,优先级最高,匹配到/test就跳过所有安全校验 --> <security:http pattern="/test" security="none"/> <!-- 然后是你的常规安全配置 --> <security:http auto-config="true"> <!-- 其他需要校验的路径规则 --> <security:intercept-url pattern="/**" access="hasRole('USER')"/> <!-- 登录、登出等其他配置 --> <security:form-login login-page="/login"/> </security:http>
方案二:用Java配置(推荐,比如Spring Boot或纯Java配置项目)
如果是用Java代码配置Spring Security,分两种情况(新版和旧版):
旧版(基于WebSecurityConfigurerAdapter,已弃用但仍有项目在使用)
继承WebSecurityConfigurerAdapter,重写configure(WebSecurity web)方法来添加忽略路径:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 配置要忽略的路径,这些路径不会进入Spring Security的过滤器链 @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/test"); } // 常规的安全规则配置 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() // 配置登录页面等 .permitAll(); } }
新版(Spring Security 5.7+,推荐使用)
现在官方推荐用SecurityFilterChain和WebSecurityCustomizer来配置,更灵活:
@Configuration @EnableWebSecurity public class SecurityConfig { // 配置核心的安全规则 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .formLogin(withDefaults()); // 启用默认登录页面 return http.build(); } // 配置要忽略的路径 @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web.ignoring().antMatchers("/test"); } }
最后再提一句:不管用哪种方案,核心都是让Spring Security的过滤器链跳过对/test路径的处理,而不是在web.xml里做文章——毕竟web.xml只是把过滤器挂到Servlet容器上,真正的规则还是Spring Security自己说了算~
内容的提问来源于stack exchange,提问作者user2108383

