Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

前端 未结 7 594
梦谈多话
梦谈多话 2020-11-27 15:59

Not sure if this is a bug with Spring 5.0.3 or a new feature to fix things on my end.

After the upgrade, I am getting this error. Interestingly this error is only on

7条回答
  •  执念已碎
    2020-11-27 16:35

    Spring Security Documentation mentions the reason for blocking // in the request.

    For example, it could contain path-traversal sequences (like /../) or multiple forward slashes (//) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don’t. To protect against issues like these, FilterChainProxy uses an HttpFirewall strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes.

    So there are two possible solutions -

    1. remove double slash (preferred approach)
    2. Allow // in Spring Security by customizing the StrictHttpFirewall using the below code.

    Step 1 Create custom firewall that allows slash in URL.

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

    Step 2 And then configure this bean in websecurity

    @Override
    public void configure(WebSecurity web) throws Exception {
        //@formatter:off
        super.configure(web);
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    ....
    }
    

    Step 2 is an optional step, Spring Boot just needs a bean to be declared of type HttpFirewall and it will auto-configure it in filter chain.

    Spring Security 5.4 Update

    In Spring security 5.4 and above (Spring Boot >= 2.4.0), we can get rid of too many logs complaining about the request rejected by creating the below bean.

    import org.springframework.security.web.firewall.RequestRejectedHandler;
    import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;
    
    @Bean
    RequestRejectedHandler requestRejectedHandler() {
       return new HttpStatusRequestRejectedHandler();
    }
    

提交回复
热议问题