实现ip白名单功能-作为JAR包方式
一、新建白名单拦截类 IPWhiteListUtil.java
1.1、代码如下
public class IPWhiteListUtil {
private static Pattern pattern = Pattern.compile("(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\.(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\.(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\.(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})");
public IPWhiteListUtil() {
}
private static Set<String> getAvaliIpList(String allowIp) {
Set<String> ipList = new HashSet();
String[] var2 = allowIp.replaceAll("\\s", "").split(";");
int var3 = var2.length;
for(int var4 = 0; var4 < var3; ++var4) {
String allow = var2[var4];
if (allow.indexOf("*") <= -1) {
if (validate(allow)) {
ipList.add(allow);
}
} else {
String[] ips = allow.split("\\.");
String[] from = new String[]{"0", "0", "0", "0"};
String[] end = new String[]{"255", "255", "255", "255"};
List<String> tem = new ArrayList();
for(int i = 0; i < ips.length; ++i) {
if (ips[i].indexOf("*") > -1) {
tem = complete(ips[i]);
from[i] = null;
end[i] = null;
} else {
from[i] = ips[i];
end[i] = ips[i];
}
}
StringBuffer fromIP = new StringBuffer();
StringBuffer endIP = new StringBuffer();
for(int i = 0; i < 4; ++i) {
if (from[i] != null) {
fromIP.append(from[i]).append(".");
endIP.append(end[i]).append(".");
} else {
fromIP.append("[*].");
endIP.append("[*].");
}
}
fromIP.deleteCharAt(fromIP.length() - 1);
endIP.deleteCharAt(endIP.length() - 1);
Iterator var16 = ((List)tem).iterator();
while(var16.hasNext()) {
String s = (String)var16.next();
String ip = fromIP.toString().replace("[*]", s.split(";")[0]) + "-" + endIP.toString().replace("[*]", s.split(";")[1]);
if (validate(ip)) {
ipList.add(ip);
}
}
}
}
return ipList;
}
private static Set<String> getAvaliIpList(Set<String> ipSet) {
Set<String> ipList = new HashSet();
Iterator var2 = ipSet.iterator();
while(true) {
while(var2.hasNext()) {
String allow = (String)var2.next();
if (allow.indexOf("*") > -1) {
String[] ips = allow.split("\\.");
String[] from = new String[]{"0", "0", "0", "0"};
String[] end = new String[]{"255", "255", "255", "255"};
List<String> tem = new ArrayList();
for(int i = 0; i < ips.length; ++i) {
if (ips[i].indexOf("*") > -1) {
tem = complete(ips[i]);
from[i] = null;
end[i] = null;
} else {
from[i] = ips[i];
end[i] = ips[i];
}
}
StringBuffer fromIP = new StringBuffer();
StringBuffer endIP = new StringBuffer();
for(int i = 0; i < 4; ++i) {
if (from[i] != null) {
fromIP.append(from[i]).append(".");
endIP.append(end[i]).append(".");
} else {
fromIP.append("[*].");
endIP.append("[*].");
}
}
fromIP.deleteCharAt(fromIP.length() - 1);
endIP.deleteCharAt(endIP.length() - 1);
Iterator var14 = ((List)tem).iterator();
while(var14.hasNext()) {
String s = (String)var14.next();
String ip = fromIP.toString().replace("[*]", s.split(";")[0]) + "-" + endIP.toString().replace("[*]", s.split(";")[1]);
if (validate(ip)) {
ipList.add(ip);
}
}
} else if (validate(allow)) {
ipList.add(allow);
}
}
return ipList;
}
}
private static List<String> complete(String arg) {
List<String> com = new ArrayList();
if (arg.length() == 1) {
com.add("0;255");
} else {
String s1;
if (arg.length() == 2) {
s1 = complete(arg, 1);
if (s1 != null) {
com.add(s1);
}
String s2 = complete(arg, 2);
if (s2 != null) {
com.add(s2);
}
} else {
s1 = complete(arg, 1);
if (s1 != null) {
com.add(s1);
}
}
}
return com;
}
private static String complete(String arg, int length) {
String from = "";
String end = "";
if (length == 1) {
from = arg.replace("*", "0");
end = arg.replace("*", "9");
} else {
from = arg.replace("*", "00");
end = arg.replace("*", "99");
}
if (Integer.valueOf(from) > 255) {
return null;
} else {
if (Integer.valueOf(end) > 255) {
end = "255";
}
return from + ";" + end;
}
}
private static boolean validate(String ip) {
String[] var1 = ip.split("-");
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
String s = var1[var3];
if (!pattern.matcher(s).matches()) {
return false;
}
}
return true;
}
private static boolean checkLoginIP(String ip, Set<String> ipList) {
if (ipList.contains(ip)) {
return true;
} else {
Iterator var2 = ipList.iterator();
boolean check;
do {
String allow;
do {
if (!var2.hasNext()) {
return false;
}
allow = (String)var2.next();
} while(allow.indexOf("-") <= -1);
String[] from = allow.split("-")[0].split("\\.");
String[] end = allow.split("-")[1].split("\\.");
String[] tag = ip.split("\\.");
check = true;
for(int i = 0; i < 4; ++i) {
int s = Integer.valueOf(from[i]);
int t = Integer.valueOf(tag[i]);
int e = Integer.valueOf(end[i]);
if (s > t || t > e) {
check = false;
break;
}
}
} while(!check);
return true;
}
}
public static boolean checkLoginIP(String ip, String ipWhiteConfig) {
Set<String> ipList = getAvaliIpList(ipWhiteConfig);
return checkLoginIP(ip, ipList);
}
public static boolean checkIpList(String ip, List<String> ipList) {
Set<String> ipSet = new HashSet();
Iterator var3 = ipList.iterator();
while(var3.hasNext()) {
String ipStr = (String)var3.next();
if (!ipStr.trim().startsWith("#")) {
ipSet.add(ipStr.trim());
}
}
Set<String> ipSet = getAvaliIpList((Set)ipSet);
return checkLoginIP(ip, ipSet);
}
}
1.2、打包成jar文件
1.2.1、首先打开Project Structure,File–>Project Structure…
1.2.2、左上侧列表中选择Artifacts选项。
1.2.3、单击加号“+”,选择JAR–>Empty
1.2.4、填写导出jar包的文件名和导出路径
1.2.5、双击工程下的文件
1.2.6、点击OK
1.2.7、在菜单栏找到Build选项,选择Build Artifacts…
1.2.8、屏幕中间会出现一个选项框,选择相应的Artifact并选择Build。
1.2.9、导出完成,我们可以去刚刚设置的路径下找到这个文件。
二、新建 helloworld 项目
代码结构如下
2.1、导入上面生成的ipwhite.jar包
2.1.1、首先打开Project Structure,File–>Project Structure…
2.1.2、在左侧列表中选择Modules。
2.1.3、单击右侧加号“+”,选择JAR or …
2.1.4、找到刚刚导出的jar包,选中,OK。
2.1.5、然后再点击OK,完成导入。
2.2、创建IPLimitInterceptor类实现HandlerInterceptorAdapter类
public class IPLimitInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String ip = getIpAddr(request);
//读取ip白名单配置文件ipwhite.properties
Properties properties = PropertiesLoaderUtils.loadAllProperties("ipwhite.properties");
String ipWhilte = properties.getProperty("ipWhilte");
System.out.println(ipWhilte);
//判断请求ip地址 是否在白名单呢
if(IPWhiteListUtil.checkLoginIP(ip,ipWhilte)) {
return super.preHandle(request, response, handler);
}
throw new Exception("IP非法访问!");
}
/**
* 获取访问的ip地址
*
* @param request
* @return
*/
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
2.3、创建WebAppConfigurer类实现WebMvcConfigurer接口 ,重写 addInterceptors 方法
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPLimitInterceptor()).addPathPatterns("/**");
}
}
2.3、HelloWorldController
@RestController
public class HelloWorldController {
@RequestMapping("/sayHello")
public String sayHello(){
return "HELLO WORLD";
}
}
2.4、扫描包
@ComponentScan("com.example.helloworld.demo.*")
2.5、添加白名单配置:ipwhite.properties
ipWhilte=192.168.2.105;127.0.0.1
三、 验证
3.1、访问成功:http://127.0.0.1:8080/sayHello
3.2、访问失败:http://192.168.2.101:8080/sayHello
3.2、修改ipwhite.properties,添加 192.168.2.101
ipWhilte=192.168.2.105;127.0.0.1;192.168.2.101
访问成功:http://192.168.2.101:8080/sayHello