Spring Boot应用中限制localhost:8080/.与localhost:8080/..访问权限的配置问题
解决Spring Boot中/.和/..路径的权限限制问题
嘿,我来帮你搞定这个问题!目前你的Spring Boot应用会把/.和/..重定向到/,而/在你的Security配置里是公开路径,所以这两个路径也间接对匿名用户开放了。要限制它们的访问权限,我们可以从Spring Security拦截规则和Spring MVC路径解析两方面入手,下面是具体的解决方案:
方案一:直接在Spring Security中拦截原始路径
Spring Security的过滤器链是在Spring MVC的DispatcherServlet之前执行的,所以我们可以先针对/.和/..这两个原始请求路径设置权限规则,阻止匿名用户访问:
修改你的configure(HttpSecurity http)方法,在公开路径规则之前添加需要认证的规则:
@Override protected void configure(HttpSecurity http) throws Exception { CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceEncoding(true); http.addFilterBefore(encodingFilter, CsrfFilter.class); http.csrf().disable(); http .authorizeRequests() // 先针对/.和/..设置权限:要求用户必须认证才能访问,也可以用denyAll()直接拒绝 .antMatchers("/.", "/..").authenticated() // 再保留原有的公开路径规则 .antMatchers(publicMatchers()).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.html") .defaultSuccessUrl("/advertise.html") .failureUrl("/login.html?error").permitAll() .and() .logout() .permitAll() .and() .rememberMe() .key("uniqueAndSecret"); }
这样配置后,当用户访问localhost:8080/.或localhost:8080/..时,Security会直接拦截这个请求,要求用户登录,而不会触发后续的Spring MVC重定向。
方案二:调整Spring MVC的路径解析行为(可选)
如果你希望彻底禁用Spring MVC对/.和/..的自动重定向,可以添加一个WebMvc配置类,修改路径解析规则:
@Configuration public class CustomWebMvcConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); // 关闭自动移除路径中的点号内容,让/.和/..被当作真实路径处理 urlPathHelper.setRemoveSemicolonContent(false); // 禁止URL解码,避免路径被篡改 urlPathHelper.setUrlDecode(false); configurer.setUrlPathHelper(urlPathHelper); } }
配置完这个之后,/.和/..就不会被自动重定向到/了,此时你只需要确保这两个路径不在你的publicMatchers数组里,它们就会自动应用anyRequest().authenticated()的规则,要求用户认证。
注意事项
- 如果你选择方案一,不需要修改MVC配置,因为Security会在重定向之前拦截请求,足够解决你的问题。
- 对于
/...路径,它本身不会被Spring MVC重定向,所以现在已经被要求认证了,符合你的预期。
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

