• 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());
    ....
    }
    

    至此,问题解决。

  • 相关阅读:
    python 自动化之路 day 10 协程、异步IO、队列、缓存
    MySQ binlog三种模式
    文件存储之-内存文件系统tmpfs
    Linux 系统结构详解
    服务端高性能数据库优化演变细节案例
    滴滴研发笔记题,亮灯问题
    linux screen 命令详解
    Linux之在CentOS上一次艰难的木马查杀过程
    python 自动化之路 day 09 进程、线程、协程篇
    redis
  • 原文地址:https://www.cnblogs.com/lanxuan826/p/10997641.html
Copyright © 2020-2023  润新知