问题描述:在上篇文章中,SpringSecurity拦截 // 导致报错 url 请求不合规范问题通过修改Security源码已解决,
但是又因为许多静态文件也带有 // 进行请求:test//test.css等,导致重定向次数过多
问题解决:使用拦截器对所有请求进行拦截,对 request 请求中的 url 进行重写
此处参考 spring security关于URL中包含双斜杠被权限拦截的处理
添加拦截器配置
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.stereotype.Component;
@Component("permitAllSecurityConfig")
public class UrlConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Autowired
private Filter uriFormatFilter;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean setFilter() {
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(uriFormatFilter);
filterBean.setName("uriFormatFilter");
filterBean.addUrlPatterns("/*");
filterBean.setOrder(-10000);
return filterBean;
}
}
拦截器
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component("uriFormatFilter")
// OncePerRequestFilter,它能够确保在一次请求中只通过一次filter
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("//","/");
// 使用HttpServletRequestWrapper重写Request请求参数
httpServletRequest = new HttpServletRequestWrapper(httpServletRequest){
@Override
public String getRequestURI() {
return newUri;
}
};
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
与之前写的一个没有成功的拦截器进行比较:
httpRequest.getRequestDispatcher(path).forward(request,response);
之前拦截器是服务器内部跳转,相当于重新发送了一次请求,我理解为break,退出当前循环进行下一次循环,而当前拦截器是对当前Request内容进行重写,
然后使用filterChain.doFilter进入其他拦截器,相当于继续当前请求的工作,继续执行