spring security关于URL中包含双斜杠被权限拦截的处理

今天测试提了个bug,说某个接口被权限拦截了,无法调用成功,但是接口明明已经过滤拦截了,postman亲测无问题,问什么还会导致被拦截呢,然后检查后发现,接口URL中包含一个双斜杠导致出现这个问题。(就像这样的 localhost:8080//api/a/people/1这种 8080后面有两个斜杠)

public class StrictHttpFirewall implements HttpFirewall {

		/**
			省略甚多东西
		*/
/**
	 * Checks whether a path is normalized (doesn't contain path traversal
	 * sequences like "./", "/../" or "/.")
	 *
	 * @param path
	 *            the path to test
	 * @return true if the path doesn't contain any path-traversal character
	 *         sequences.
	 */
 private static boolean isNormalized(String path) {
		if (path == null) {
			return true;
		}
		//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//就是此处 注意看 就是他给返回了false
		if (path.indexOf("//") > -1) {
			return false;
		}

		for (int j = path.length(); j > 0;) {
			int i = path.lastIndexOf('/', j - 1);
			int gap = j - i;

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

			j = i;
		}

		return true;
	}
}

上面那段代码中在验证url中包含双//会直接返回验证失败。

怎么解决这个问题呢,想了一个偷巧的办法,在过滤器最前面增加一个HttpRequest的wrapper。

@Component("uriFormatFilter")
public class UriFormatFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String uri = httpServletRequest.getRequestURI();
        String newUri = uri.replace("//","/");
        httpServletRequest = new HttpServletRequestWrapper(httpServletRequest){
            @Override
            public String getRequestURI() {
                return newUri;
            }
        };

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
@Component("permitAllSecurityConfig")
public class PermitAllSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private Filter uriFormatFilter;

    @Bean
    public FilterRegistrationBean setFilter() {
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(uriFormatFilter);
        filterBean.setName("uriFormatFilter");
        filterBean.addUrlPatterns("/*");
        filterBean.setOrder(-10000);
        return filterBean;
    }

}
问题华丽丽的解决
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值