解決springboot URL帶有斜杠的轉義字符百分之2F導致的400錯誤

springboot URL帶有斜杠的轉義字符百分之2F導致的400錯誤

今天項目上出現一個問題,是前端的GET請求url中帶有路徑參數,這個參數中有/這個特殊字符,前端已經轉移成瞭%2F,後端用的是springboot,並沒有收到這個請求,直接返回瞭400的錯誤

原因

據說是tomcat默認是不支持轉義的,需要手動設置一下轉化,這個搜索tomcat的設置可以找到,但是這個是springboot,有內置的tomcat,但是在yml中找不到相關的配置。

解決方式

修改一下啟動類,加一個系統參數,重寫WebMvcConfigurerAdapter的configurePathMatch方法

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
    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);
    }
}

springboot 1.x 2.x tomcat支持特殊字符

URL中有{}[]等報400

現象

正常訪問一個get請求,頁面返回400: 在這裡插入圖片描述

後臺日志報錯:

2018-08-09 21:39:28.915  INFO 6750 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor   : Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:479) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:684) ~[tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_111]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_111]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.32.jar:8.5.32]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]

稍微百度一下就可以知道這是URL中有特殊字符,新版本的Tomcat嚴格按照RFC 3986規范進行訪問解析,而 RFC 3986規范規定Url中隻允許包含英文字母(a-zA-Z)、數字(0-9)、-_.~4個特殊字符以及所有保留字符(RFC3986/7320中指定瞭以下字符為保留字符:! * ‘ ( ) ; : @ & = + $ , / ? # [ ]) 。

3.2.6. Field Value Components Most HTTP header field values are defined using common syntax components (token, quoted-string, and comment) separated by whitespace or specific delimiting characters. Delimiters are chosen from the set of US-ASCII visual characters not allowed in a token (DQUOTE and “(),/:;<=>?@[]{}”).

所以這個問題特別容易出現在升級spring boot版本的時候,spring boot內嵌的tomcat也會升級,老版的tomcat運行正常,新版的tomcat就會出錯。而深究特殊字符來源,一般是get請求中包含json字符串、搜索特殊字符關鍵字等。

解決方案

如果是在開發新業務過程中出現這個問題,可以選擇新的方案,避免在GET請求中使用! * ‘ ( ) ; : @ & = + $ , / ? # [ ])等字符,畢竟符合規范是最好的出路。

如果是升級,可以使用下面的方式來解決:

sprintboot 1.x(1.5.21測試有效)

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * Create by IntelliJ IDEA
 *
 * @author chenlei
 * @dateTime 2019/5/23 18:09
 * @description TomcatConfig
 */
@Configuration
public class TomcatConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new MyCustomizer();
    }
    private static class MyCustomizer implements EmbeddedServletContainerCustomizer {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer factory) {
            if (factory instanceof TomcatEmbeddedServletContainerFactory) {
                customizeTomcat((TomcatEmbeddedServletContainerFactory) factory);
            }
        }
        void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
            factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
                connector.setAttribute("relaxedPathChars", "<>[\\]^`{|}");
                connector.setAttribute("relaxedQueryChars", "<>[\\]^`{|}");
            });
        }
    }
}

springboot 2.x(2.1.3測試有效)

import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * Create by IntelliJ IDEA
 *
 * @author chenlei
 * @dateTime 2019/5/23 18:09
 * @description TomcatConfig
 */
@Configuration
public class TomcatConfig {
    @Bean
    public ServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
        fa.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
        return fa;
    }
}

總結

這次問題出現的原因是升級springboot導致的,因為之前使用的較低版本的springboot(1.5.10.RELEASE),升級到1.5.21.RELEASE後出現瞭該問題。因為之前在springboot 2.x上遇到過這個問題,因此知道問題所在,但springboot 1.x和2.x的解決方案有一點差異,這裡記錄一下。

後續

後面再做瞭一次Tomcat升級,從9.0.21升級到9.0.31,突然又出現這個問題,問題原因是一樣的,tomcat對非法字符的控制更加嚴格瞭,嚴格遵循最新的RFC7230,我們除瞭把所有的非法字符全部加到relaxedQueryChars以外,還添加瞭另一項配置rejectIllegalHeader:

@Configuration
public class TomcatConfig {
    @Bean
    public ServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
        fa.addConnectorCustomizers(connector -> {
            connector.setProperty("relaxedQueryChars", "(),/:;<=>?@[\\]{}");
            connector.setProperty("rejectIllegalHeader", "false");
        });
        return fa;
    }
}

關於這個配置的解釋參考:tomcat-9.0-doc

rejectIllegalHeader

If an HTTP request is received that contains an illegal header name or value (e.g. the header name is not a token) this setting determines if the request will be rejected with a 400 response (true) or if the illegal header be ignored (false). The default value is true which will cause the request to be rejected.

這樣配置後(1.x的配置類似),大部分URI和Header都可以兼容,但是正如文檔裡所說的,rejectIllegalHeader會導致非法的header忽略,即header信息將不會被服務器接收。

所以一旦Header裡面有非法字符,對應的Header項將被忽略,服務器不會報400,但會跳過這個header項,比如升級過程中我們發現有API在header裡傳輸中文,導致服務啟報錯,加瞭rejectIllegalHeader=false後,不報400,但程序找不到對應的Header,最後不得不刪除這些不規范的header。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet.

推薦閱讀: