前言
刚写代码不就,还不能做深层次安全措施,今天研究了一下基本的防止接口多次恶意请求的方法。
思路
1:设置同一IP,一个时间段内允许访问的最大次数
2:记录所有IP单位时间内访问的次数
3:将所有被限制IP存到存储器
4:通过IP过滤访问请求
该demo只有后台Java代码,没有前端
代码
首先是获取IP的工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Ipsettings {
public static String getRemoteHost(HttpServletRequest request) {
String ipAddress = null;
//ipAddress = request.getRemoteAddr();
ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
其次是监听器以及IP存储器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebListener
public class MyApplicationListener implements ServletContextListener {
private Logger logger = LoggerFactory.getLogger(MyApplicationListener.class);
@Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("liting: contextInitialized");
System.err.println("初始化成功");
ServletContext context = sce.getServletContext();
// IP存储器
Map
context.setAttribute("ipMap", ipMap);
// 限制IP存储器:存储被限制的IP信息
Map
context.setAttribute("limitedIpMap", limitedIpMap);
logger.info("ipmap:"+ipMap.toString()+";limitedIpMap:"+limitedIpMap.toString()+"初始化成功。。。。。");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
最后是具体规则设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
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;
@WebFilter(urlPatterns="/*")
public class IpFilter implements Filter{
/**
* 默认限制时间(单位:ms)
*/
private static final long LIMITED_TIME_MILLIS = 5 * 2 * 1000;
/**
* 用户连续访问最高阀值,超过该值则认定为恶意操作的IP,进行限制
*/
private static final int LIMIT_NUMBER = 2;
/**
* 用户访问最小安全时间,在该时间内如果访问次数大于阀值,则记录为恶意IP,否则视为正常访问
*/
private static final int MIN_SAFE_TIME = 5000;
private FilterConfig config;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig; //设置属性filterConfig
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@SuppressWarnings("unchecked")
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
ServletContext context = config.getServletContext();
// 获取限制IP存储器:存储被限制的IP信息
Map
// 过滤受限的IP
filterLimitedIpMap(limitedIpMap);
// 获取用户IP
String ip = Ipsettings.getRemoteHost(request);
System.err.println("ip:"+ip);
//以下是处理限制IP的规则,可以自己写
// 判断是否是被限制的IP,如果是则跳到异常页面
if (isLimitedIP(limitedIpMap, ip)) {
long limitedTime = limitedIpMap.get(ip) - System.currentTimeMillis();
// 剩余限制时间(用为从毫秒到秒转化的一定会存在些许误差,但基本可以忽略不计)
request.setAttribute("remainingTime", ((limitedTime / 1000) + (limitedTime % 1000 > 0 ? 1 : 0)));
//request.getRequestDispatcher("/error/overLimitIP").forward(request, response);
System.err.println("ip访问过于频繁:"+ip);
return;
}
// 获取IP存储器
Map
// 判断存储器中是否存在当前IP,如果没有则为初次访问,初始化该ip
// 如果存在当前ip,则验证当前ip的访问次数
// 如果大于限制阀值,判断达到阀值的时间,如果不大于[用户访问最小安全时间]则视为恶意访问,跳转到异常页面
if (ipMap.containsKey(ip)) {
Long[] ipInfo = ipMap.get(ip);
ipInfo[0] = ipInfo[0] + 1;
System.out.println("当前第[" + (ipInfo[0]) + "]次访问");
if (ipInfo[0] > LIMIT_NUMBER) {
Long ipAccessTime = ipInfo[1];
Long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - ipAccessTime <= MIN_SAFE_TIME) {
limitedIpMap.put(ip, currentTimeMillis + LIMITED_TIME_MILLIS);
request.setAttribute("remainingTime", LIMITED_TIME_MILLIS);
System.err.println("ip访问过于频繁:"+ip);
request.getRequestDispatcher("/error/overLimitIP").forward(request, response);
return;
} else {
initIpVisitsNumber(ipMap, ip);
}
}
} else {
initIpVisitsNumber(ipMap, ip);
System.out.println("您首次访问该网站");
}
context.setAttribute("ipMap", ipMap);
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @Description 过滤受限的IP,剔除已经到期的限制IP
* @param limitedIpMap
*/
private void filterLimitedIpMap(Map
if (limitedIpMap == null) {
return;
}
Set
Iterator
long currentTimeMillis = System.currentTimeMillis();
while (keyIt.hasNext()) {
long expireTimeMillis = limitedIpMap.get(keyIt.next());
if (expireTimeMillis <= currentTimeMillis) {
keyIt.remove();
}
}
}
/**
* @Description 是否是被限制的IP
* @param limitedIpMap
* @param ip
* @return true : 被限制 | false : 正常
*/
private boolean isLimitedIP(Map
if (limitedIpMap == null || ip == null) {
// 没有被限制
return false;
}
Set
Iterator
while (keyIt.hasNext()) {
String key = keyIt.next();
if (key.equals(ip)) {
// 被限制的IP
return true;
}
}
return false;
}
/**
* 初始化用户访问次数和访问时间
*
* @param ipMap
* @param ip
*/
private void initIpVisitsNumber(Map
Long[] ipInfo = new Long[2];
ipInfo[0] = 0L;// 访问次数
ipInfo[1] = System.currentTimeMillis();// 初次访问时间
ipMap.put(ip, ipInfo);
}
}
然后再在启动类上加上注解扫描配置包
1
@ServletComponentScan(basePackages="扫描刚才的MyApplicationListener")
补充:springboot和redis控制单位时间内同个ip访问同个接口的次数
注:本文中的修改于网上一个错误的例子,不知道为什么一个错误的例子还被人疯狂转载,还都标着原创。。。具体是那个这里就不指出了!