【安全检测】Java后台项目的过滤器:用户是否登录、头攻击、会话重放等
package fhm;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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 javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
//@Order(2)
@Component
@WebFilter(filterName = "myFilter", urlPatterns = {"/*"})
public class myFilter implements Filter {
private static Logger log = LoggerFactory.getLogger(myFilter.class);
@Autowired
private TestWhiteListUtil whiteUtils;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final Integer EXPIRE_TIME = Integer.valueOf(30);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
JSONObject jsonObject = new JSONObject();
PrintWriter pw = null;
String authorizeState = "error message..";
// 1.头攻击检测:Host
String host= httpRequest.getHeader("host");
if (host!= null && !whiteUtils.isWhiteHost(host)) {
httpResponse.setStatus(403);
log.warn("头攻击 requestHost:" + host);
authorizeState = "Head attack in progress...";
try {
jsonObject.put("resultHint", authorizeState);
jsonObject.put("successful", false);
jsonObject.put("resultValue", "");
jsonObject.put("type", "error");
pw = httpResponse.getWriter();
pw.write(jsonObject.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
pw.flush();
pw.close();
}
return;
}
// 2.Origin跨域访问检测
String Origin= httpRequest.getHeader("Origin");
//...省略
// 3.对数据请求中的referer值进行验证,防止CSRF风险
String Referer= httpRequest.getHeader("Referer");
//...省略
// 4.时间戳判断
String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
if ((url.startsWith("/")) && (url.length() > 1)) {
url = url.substring(1).split("/")[0];
}
String cl_token_id = httpRequest.getParameter("QW");
//...省略
// 5. 判断用户是否登录及失效
String iscUserId = httpRequest.getParameter("userId");
if ((iscUserId == null) || ("".equals(iscUserId) || ("undefined".equals(iscUserId)))) {
System.out.println("没有登录,请联系管理员");
httpResponse.setStatus(403);
authorizeState = "userId is null";
try {
jsonObject.put("resultHint", authorizeState);
jsonObject.put("successful", false);
jsonObject.put("resultValue", "");
jsonObject.put("type", "error");
pw = httpResponse.getWriter();
pw.write(jsonObject.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
pw.flush();
pw.close();
}
return;
}
Boolean hasKey = this.redisTemplate.hasKey(iscUserId);
if (!hasKey.booleanValue()) {
System.out.println("用户信息失效");
httpResponse.setStatus(403);
authorizeState = "userInfo is null";
try {
jsonObject.put("resultHint", authorizeState);
jsonObject.put("successful", false);
jsonObject.put("resultValue", "");
jsonObject.put("type", "error");
pw = httpResponse.getWriter();
pw.write(jsonObject.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
pw.flush();
pw.close();
}
return;
}
this.redisTemplate.expire(iscUserId, EXPIRE_TIME.intValue(), TimeUnit.MINUTES);
chain.doFilter(httpRequest, httpResponse);
}
@Override
public void destroy() {
}
}
package fhm;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 服务器白名单列表
*/
@Component
public class TestWhiteListUtil {
@Value("${Host.whiteList}")
private String hostWhiteList;
private static Logger log = LoggerFactory.getLogger(TestWhiteListUtil.class);
/**
* 判断当前host是否在白名单内
* @param host 待查host
*/
public boolean isWhiteHost(String host) {
String[] whiteList = hostWhiteList.split(",");
if (whiteList == null || whiteList.length == 0) {
return true;
}
for (Object str : whiteList) {
if (str != null && str.equals(host)) {
return true;
}
}
return false;
}
/**
* Origin跨域访问
* @param Origin
* @return
*/
public boolean isWhiteOrigin(String Origin) {
//...省略
return false;
}
/**
* 对数据请求中的referer值进行验证,防止CSRF风险
* @param Referer
* @return
*/
public boolean isWhiteReferer(String Referer) {
//...省略
return false;
}
}