Encoded slash (/) with Spring RequestMapping path param gives HTTP 400

前端 未结 9 796
陌清茗
陌清茗 2020-12-05 00:10

This is not a duplicate referenced question, because it is Spring specific. Whoever added that (3 years after the fact!) didn\'t bother to read the question or comment

9条回答
  •  星月不相逢
    2020-12-05 00:30

    2019 Update for Spring Boot 2+ / Spring (Security) 5+ / Java 8+:

    As my edit to iamiddy's answer was rejected I want to also provide the complete solution for Spring Boot 2 + as an separate answer.

    The WebMvcConfigurerAdapter is deprecated with Spring5 / Java8 and can be replaced directly with the Interface WebMvcConfigurer ending up with:

    @SpringBootApplication
    public class Application extends WebMvcConfigurer {
    
        public static void main(String[] args) throws Exception {
            System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            UrlPathHelper urlPathHelper = new UrlPathHelper();
            urlPathHelper.setUrlDecode(false);
            configurer.setUrlPathHelper(urlPathHelper);
        }
    }
    

    Plus you also need to configure Spring's (Strict)HttpFirewall to avoid the blocking of encoded slashes with the error message The request was rejected because the URL contained a potentially malicious String "%2F"

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);    
        return firewall;
    }
    

    Spring Boot will use the above HttpFirewall Bean when available - otherwise it might be necessary to configure the WebSecurity as mentioned here:

提交回复
热议问题