ip黑白名单是网络安全管理中常见的策略工具,用于控制网络访问权限,根据业务场景的不同,其应用范围广泛

方式一:
添加一个简单的白名单,然后只有白名单上面的 ip 才能访问网站,否则不能访问这是只是一个很简单的实现方法
首先:在 application.yml 配置 ip 白名单
my:
iplist:
- 192.168.3.3
- 192.168.2.12
- 192.168.5.24
- 152.63.54.26
想要引用到配置文件里面的 string 数组,如果使用普通的 @value 是不行的,必须使用其他方法
步骤一:创建一个实体类
@component
@configurationproperties(prefix = "my") // 这里是对应的配置文件里面自定义的 my
public class my {
private string[] iplist;
public my(string[] iplist) {
this.iplist = iplist;
}
public string[] getiplist() {
return iplist;
}
public void setiplist(string[] iplist) {
this.iplist = iplist;
}
}
这样配置文件的信息就保存在了这个实体类里面
在 controller 里面比对 ip
@controller
public class logincontroller {
@autowired
private my myiplist;
@postmapping("/login")
@responsebody
public string login(@requestbody loginform loginform, httpservletrequest request) {
string [] iplist = myiplist.getiplist();
string ipaddress = loginform.getipaddress();
// 如果前端传递过来的 ip 在白名单里面,就返回 ok,如果不在,就返回 error
for (string s : iplist) {
if (s.equals(ipaddress)) {
return "ok";
}
}
return "error";
}
}
方式二:限制 ip 访问的次数
这个是利用了 aop 的切面编程,如果同一个 ip 访问一个地址一分钟之内超过10次,就会把这个 ip 拉入黑名单,在自定义的时间内是不能再次访问这个网站的。
第一步,在 application.yml 中配置 redis 相关设置
spring:
redis:
# 超时时间
timeout: 10000ms
# 服务器地址
host: 192.168.1.1
# 服务器端口
port: 6379
# 数据库
database: 0
# 密码
password: xxxxxxx
lettuce:
pool:
# 最大连接数,默认为 8
max-active: 1024
# 最大连接阻塞等待时间,默认 -1
max-wait: 10000ms
# 最大空闲连接
max-idle: 200
# 最小空闲连接
min-idle: 5
第一步,自定义一个注解
@retention(retentionpolicy.runtime)
@target(elementtype.method)
@documented
@order(ordered.highest_precedence)
public @interface requestlimit {
/**
* 允许访问的最大次数
*/
int count() default integer.max_value;
/**
* 时间段,单位为毫秒,默认值一分钟
*/
long time() default 60000;
}
第二步:序列化 redis 类
@configuration
@slf4j
public class redisconfiguration {
@bean
@conditionalonmissingbean
public redistemplate redistemplate(redisconnectionfactory connectionfactory) {
system.err.println("调用了 redis 配置类");
redistemplate<string, object> redistemplate = new redistemplate<>();
// string 类型 key 序列器
redistemplate.setkeyserializer(new stringredisserializer());
// string 类型 value 序列器
redistemplate.setvalueserializer(new genericjackson2jsonredisserializer());
// hash 类型 value 序列器
redistemplate.sethashkeyserializer(new stringredisserializer());
// hash 类型 value 序列器
redistemplate.sethashvalueserializer(new genericjackson2jsonredisserializer());
redistemplate.setconnectionfactory(connectionfactory);
return redistemplate;
}
}
第三步:创建一个切面类
@aspect
@component
@slf4j
public class requestlimitcontract {
private static final logger logger = loggerfactory.getlogger("requestlimitlogger");
@autowired
private redistemplate<string, object> redistemplate;
@autowired
private objectmapper objectmapper;
@before("within(@org.springframework.stereotype.controller *) && @annotation(limit)")
public void requestlimit(final joinpoint joinpoint , requestlimit limit) throws requestlimitexception {
try {
loginform loginform = new loginform();
object[] args = joinpoint.getargs();
httpservletrequest request = null;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof httpservletrequest) {
request = (httpservletrequest) args[i];
break;
} else if (args[i] instanceof loginform) {
loginform = (loginform) args[i];
}
}
if (request == null) {
throw new requestlimitexception("方法中缺失httpservletrequest参数");
}
//获取请求中的ip与url链接参数 用于拼接key存放redis中
string ip = loginform.getipaddress();
string url = request.getrequesturl().tostring();
long interview_time = new date().gettime();
string key = "req_limit_".concat(url).concat("---").concat(ip);
system.err.println("准备保存在redis中的数据为-->");
map<string, long> form = new hashmap<>();
form.put("size", 1l);
form.put("saveredistime", interview_time);
if (redistemplate.opsforvalue().get(key) == null) {
system.err.println(form);
redistemplate.opsforvalue().set(key, form);
} else {
//用于进行ip访问的计数
map<string, long> result = (map<string, long>) redistemplate.opsforvalue().get(key);
system.err.println("从redis取到的数据(内部)");
system.out.println(result);
assert result != null;
result.put("size", result.get("size") + 1);
redistemplate.opsforvalue().set(key, result);
if (result.get("size") > 10) {
logger.info("用户ip[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
throw new requestlimitexception();
}
// 如果访问次数小于 10 次,那么一分钟过后就直接删除这个节点
if (result.get("size") <= limit.count()) {
//创建一个定时器
timer timer = new timer();
timertask timertask = new timertask() {
@override
public void run() {
redistemplate.delete(key);
}
};
//这个定时器设定在time规定的时间之后会执行上面的remove方法,也就是说在这个时间后它可以重新访问
timer.schedule(timertask, limit.time());
}
}
}catch (requestlimitexception e){
throw e;
}catch (exception e){
logger.error("发生异常",e);
}
}
}
第四步,创建一个定时器
记住要在启动类上面开启启动定时器注解
@component
public class scheduledtask {
@autowired
private redistemplate<string, object> redistemplate;
// @value("${properties.continuetime}")
private final long continuetime = 120; // 这是是黑名单的保存时间,在这个时间内,同一个ip将不能继续访问
// @scheduled(cron = "0 0 0 * * ?") // 每天凌晨触发一次
@scheduled(fixedrate = 1000000) // 每 30s 执行一次
public void deletedatascheduled() {
set<string> keys = redistemplate.keys("*");
if (keys == null || keys.size() == 0) {
return;
}
system.out.println("redis里面所有的key为:" + keys.tostring());
long now_time = new date().gettime();
for (string key : keys) {
map<string, long> result = (map<string, long>) redistemplate.opsforvalue().get(key);
assert result != null;
system.err.println(result);
// 计算出时间差
long createtime = result.get("saveredistime");
system.err.println("创建时间为:" + createtime);
long l = (now_time - createtime) / 1000l;
system.err.println("时间差为:" + l);
if (l > continuetime) {
system.out.println("禁止时间结束,解除时间限制!!!");
redistemplate.delete(key);
return;
}
int s = math.tointexact(result.get("size"));
system.out.println("s===>" + s + " l===>" + l);
if (s <= 10) {
if (l > 60) {
system.out.println("一分钟结束,删除节点,重新计时");
redistemplate.delete(key);
}
}
}
}
}
第五步:在需要的类上使用自己自定义的注解
@postmapping("/login")
@requestlimit(count=10,time=60000) // 这个注解就是开启ip限制的注解,这个注解的业务都是自己写的
@responsebody
public string login(@requestbody loginform loginform, httpservletrequest request) {
system.out.println("执行登录代码");
string name = loginform.getusername();
string ipaddress = loginform.getipaddress();
string timestamp = string.valueof(new date().gettime());
string info = arrays.tostring(iplist);
request.setattribute("username", name);
request.setattribute("ipaddress", ipaddress);
return "ok1";
}
总结:在这里针对 ip 的限制就结束了,总而言之还是比较简单的,没有什么特别难的点
到此这篇关于springboot 限制ip访问指定的网址实现的文章就介绍到这了,更多相关springboot 限制ip访问指定网址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论