SpringBoot整合升级Spring Security 报错 【The request was rejected because the URL was not normalized】

前言

最近LZ给项目框架升级, 从Spring1.x升级到Spring2.x, 在这里就很少赘述两个版本之间的区别以及升级的缘由。java

关于升级过程当中踩的坑,在其余博文中会作比较详细的记录,以便给读者参考,不要掉进一样的坑里。 这里咱们讨论一个关于URL中包含双斜杠被拦截的问题。web

发现问题

升级框架以后,测试一个功能时,发现报错Http 500, 第一时间怀疑是后台功能报错。打印后台错误日志,发现报错信息:The request was rejected because the URL was not normalized。spring

以后与升级前相同环境对比发现,相同的功能, 升级以后,URL中包含双斜杠。框架

分析问题

通过对比不一样和错误信息,初步定位问题出在URL上。查询资料得知,Spring Security 在高版本中增长了StrictHttpFirewall类,对URL校验更加严格。因而查看源码:ide

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出现双斜杠“//”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/49116274code

  1. 建立容许在URL中使用斜线的自定义防火墙。
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    StrictHttpFirewall firewall = new StrictHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);    
    return firewall;
}

2.在WebSecurity中配置这个bean。orm

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

至此,问题解决。

相关文章
相关标签/搜索