Springboot防CSRF攻击

下面展示一些 内联代码片

import java.io.IOException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.util.StrUtil;

public class CSRFFilter implements Filter {
	private FilterConfig filterConfig = null;
	
	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("==进入CSRF过滤器===");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 从http头中获取Referer
		String referer = req.getHeader("Referer");
		// 系统配置的referer头信息
		String myReferer = filterConfig.getInitParameter("referer");
		myReferer = StrUtil.formatNull(myReferer);// 判空
		int count = 0;
		if (myReferer.trim().length() > 0) {
			String[] myReferers = myReferer.split(";");
			for (int i = 0; i < myReferers.length; i++) {
				if (referer != null && !referer.trim().startsWith(myReferers[i])) {
					count++;
				} else {
					chain.doFilter(request, response);
					break;
				}
			}
			if (count == myReferers.length) {
				System.out.println("检测到您发送的请求可能为跨站伪造请求1:" + HttpServletResponse.SC_BAD_REQUEST);
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}
		}
		System.out.println("==结束CSRF过滤器===");
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
}
import java.util.Map;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.collect.Maps;
import com.filter.CSRFFilter;

@Configuration
public class FilterConfig {
		@Bean
		public FilterRegistrationBean csrfFilterRegistrationBean() {
			FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
			filterRegistrationBean.setFilter(new CSRFFilter());
			filterRegistrationBean.setOrder(2);
			filterRegistrationBean.setEnabled(true);
			filterRegistrationBean.addUrlPatterns("/*");
			Map initParameters = Maps.newHashMap();
			initParameters.put("referer", "http://localhost:8080");
			/* initParameters.put("isIncludeRichText", "true"); */
			filterRegistrationBean.setInitParameters(initParameters);
			return filterRegistrationBean;
		}
	}
public class StrUtil {
		/**
		 * 功能:格式化空字符串
		 * 
		 * @param str
		 * @return String
		 */
		public static String formatNull(Object str) {
			return null == str || "null".equals(str) ? "" : str.toString();
		}
	}

你可能感兴趣的:(springboot)