今天测试提了个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;
}
}
问题华丽丽的解决