SpringBoot整合升級Spring Security 報錯 【The request was rejected because the URL was not normalized】


前言

最近LZ給項目框架升級, 從Spring1.x升級到Spring2.x, 在這里就不多贅述兩個版本之間的區別以及升級的原因。

關於升級過程中踩的坑,在其他博文中會做比較詳細的記錄,以便給讀者參考,不要掉進同樣的坑里。 這里我們討論一個關於URL中包含雙斜杠被攔截的問題。

發現問題

升級框架之后,測試一個功能時,發現報錯Http 500, 第一時間懷疑是后台功能報錯。打印后台錯誤日志,發現報錯信息:The request was rejected because the URL was not normalized。

之后與升級前相同環境對比發現,相同的功能, 升級之后,URL中包含雙斜杠。

分析問題

經過對比不同和錯誤信息,初步定位問題出在URL上。查詢資料得知,Spring Security 在高版本中增加了StrictHttpFirewall類,對URL校驗更加嚴格。於是查看源碼:

private static boolean isNormalized(String path) {
    if (path == null) {
        return true;
    } else if (path.indexOf("//") > -1) {
        return false;
    } else {
        int i;
        for(int j = path.length(); j > 0; j = i) {
            i = path.lastIndexOf(47, j - 1);
            int gap = j - i;
            if (gap == 2 && path.charAt(i + 1) == '.') {
                return false;
            }

            if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }
        }

        return true;
    }
}

解決問題

方法一:修改項目中出現“//”雙斜杠的URL路徑,哈哈

方法二:自定義FireWall方式允許URL出現雙斜杠“//”

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

https://stackoverflow.com/questions/48453980/spring-5-0-3-requestrejectedexception-the-request-was-rejected-because-the-url/49116274

  1. 創建允許在URL中使用斜線的自定義防火牆。
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    StrictHttpFirewall firewall = new StrictHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);    
    return firewall;
}

2.在WebSecurity中配置這個bean。

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

至此,問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM