1. 跨站点请求伪造
风险:可能会窃取或操纵客户会话和 cookie,它们可能用于模仿合法用户,从而使黑客能够以该用户身份查看或变更用户记录以及执行事务。
原因:应用程序使用的认证方法不充分。
固定值:验证“Referer”头的值,并对每个提交的表单使用 one-time-nonce。
2、配置文件添加配置
#防止Referer跨站点配置
security.csrf.excludes
3、添加Referer拦截器
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@Configuration
@WebFilter(filterName = "refererFilter", urlPatterns = "/*")
public class RefererFilter implements Filter {
public static final Logger logger = LoggerFactory.getLogger(RefererFilter.class);
/**
* 过滤器配置对象
*/
FilterConfig filterConfig = null;
/**
* 是否启用
*/
private boolean enable = true;
/**
* 忽略的URL
*/
@Value("${security.csrf.excludes}")
private String excludes;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
// TODO Auto-generated method stub
logger.error("是否启用Referer 跨站点拦截器" + enable);
HttpServletRequest request = (HttpServletRequest) servletRequest;
// 不启用或者已忽略的URL不拦截
if (!enable || isExcludeUrl(request.getServletPath())) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
String referer = request.getHeader("Referer");
String serverName = request.getServerName();
// 判断是否存在外链请求本站
if (null != referer && referer.indexOf(serverName) < 0) {
logger.error("Referer过滤器 => 服务器:{} => 当前域名:{}", serverName, referer);
servletResponse.setContentType("text/html; charset=utf-8");
servletResponse.getWriter().write("系统不支持当前域名的访问!");
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
this.filterConfig = null;
}
/**
* 判断是否为忽略的URL
*
* @param urlPath
* URL路径
* @return true-忽略,false-过滤
*/
private boolean isExcludeUrl(String url) {
if (excludes == null || excludes.isEmpty()) {
return false;
}
List<String> urls = Arrays.asList(excludes.split(","));
return urls.stream().map(pattern -> Pattern.compile("^" + pattern)).map(p -> p.matcher(url))
.anyMatch(Matcher::find);
}
}