首页 > 其他分享 >防止接口恶意刷新和暴力请求

防止接口恶意刷新和暴力请求

时间:2022-10-22 11:58:30浏览次数:79  
标签:return String org 接口 恶意 刷新 import ipAddress public

在实际项目使用中,必须要考虑服务的安全性,当服务部署到互联网以后,就要考虑服务被恶意请求和暴力攻击的情况,下面的教程,通过intercept和redis针对url+ip在一定时间内访问的次数来将ip禁用,可以根据自己的需求进行相应的修改,来打打自己的目的;首先创建一个自定义的拦截器类,也是最核心的代码;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Slf4j
public class IpUrlLimitInterceptor implements HandlerInterceptor {

private RedisUtil getRedisUtil() {
return SpringContextUtil.getBean(RedisUtil.class);
}
private static final String LOCK_IP_URL_KEY="lock_ip_";
private static final String IP_URL_REQ_TIME="ip_url_times_";
private static final long LIMIT_TIMES=5;
private static final int IP_LOCK_TIME=60;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//log.info("request请求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAdrress(httpServletRequest));
if (ipIsLock(IpAdrressUtil.getIpAdrress(httpServletRequest))){
log.info("ip访问被禁止={}",IpAdrressUtil.getIpAdrress(httpServletRequest));
/*ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
returnJson(httpServletResponse, JSON.toJSONString(result));*/
return false;
}
if(!addRequestTime(IpAdrressUtil.getIpAdrress(httpServletRequest),httpServletRequest.getRequestURI())){
log.info("请求次数超禁止={}",IpAdrressUtil.getIpAdrress(httpServletRequest));
/*ApiResult result = new ApiResult(ResultEnum.LOCK_IP);
returnJson(httpServletResponse, JSON.toJSONString(result));*/
return false;
}
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { }

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { }
/**
* @Description: 判断ip是否被禁用
*/
private Boolean ipIsLock(String ip){
RedisUtil redisUtil=getRedisUtil();
if(redisUtil.hasKey(LOCK_IP_URL_KEY+ip)){
return true;
}
return false;
}
/**
* @Description: 记录请求次数
*/
private Boolean addRequestTime(String ip,String uri){
String key=IP_URL_REQ_TIME+ip+uri;
RedisUtil redisUtil=getRedisUtil();
if (redisUtil.hasKey(key)){
long time=redisUtil.incr(key,1);
return time < LIMIT_TIMES;
}else {
redisUtil.getLock(key,"1",1);
}
return true;
}

private void returnJson(HttpServletResponse response, String json) throws Exception {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/json; charset=utf-8");
try {
writer = response.getWriter();
((PrintWriter) writer).print(json);
} catch (IOException e) {
log.error("LoginInterceptor response error ---> {}", e.getMessage(), e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
获取IP地址的工具类
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* @ClassName IpAdrressUtil
* @Description 获取IP地址的工具类
*/
public class IpAdrressUtil {

/**
* 获取IP地址
*/
public static String getIpAdrress(HttpServletRequest request){
String 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") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
}
if (inet.getHostAddress() != null) {
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;
}
}

获取Redis工具类
import com.gssdgsfit.constant.RedisfMessageConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class RedisUtil {

private static final String SUCCESS = "1L";

@Autowired
private RedisTemplate<String, String> redisTemplate;

// * 获取锁
//* @param expireTime:单位-秒
/*
public boolean getLock(String lockKey, Object value, int expireTime) {
try {
log.info("添加分布式锁key={},expireTime={}",lockKey,expireTime);
String script = "if redis.call('setNx',KEYS[1],ARGV[1]) " +
"then if redis.call('get',KEYS[1])==ARGV[1] " +
"then return redis.call('expire',KEYS[1],ARGV[2]) " +
"else return 0 end end";

RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);

String result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);

if (SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}*/
/**
* 加锁
* @param key
* @param value
* @param timeout 过期时间
*/
public boolean getLock(String key, String value, Integer timeout){
Boolean b = redisTemplate.opsForValue().setIfAbsent(key, value,timeout, TimeUnit.SECONDS);
if(b){
return true;
}else{
log.info("lock err!");
}
return false;
}

/**
* 释放锁
* @param lockKey
* @param value
* @return
*/
public boolean releaseLock(String lockKey, String value) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
if (SUCCESS.equals(result)) {
return true;
}
return false;
}

public boolean hasKey(String key){
Object o = redisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(key) ){
return true;
}
return false;
}

public long incr(String key, long l) {
String s = redisTemplate.opsForValue().get(key);
redisTemplate.opsForValue().set(key,String.valueOf(Long.parseLong(s)+l));
return Long.parseLong(s)+l;
}
}
SpringContextUtil工具类
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

// 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}

public static Object getBean(String name)
throws BeansException {
return applicationContext.getBean(name);
}

public static Object getBean(String name, Class<?> requiredType)
throws BeansException {

return applicationContext.getBean(name, requiredType);
}

public static <T> T getBean(Class<T> clazz)
throws BeansException {
return applicationContext.getBean(clazz);
}

public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}

public static boolean isSingleton(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}

public static Class<?> getType(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}

public static String[] getAliases(String name)
throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}

最后将上面自定义的拦截器通过registry.addInterceptor添加一下,就生效了;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@Slf4j
public class MyWebAppConfig extends WebMvcConfigurerAdapter {
@Bean
IpUrlLimitInterceptor getIpUrlLimitInterceptor(){
return new IpUrlLimitInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}











标签:return,String,org,接口,恶意,刷新,import,ipAddress,public
From: https://www.cnblogs.com/yswsxf/p/16815738.html

相关文章

  • apipost动态获取登录token,其他接口同步调用
    1、新增登录接口,接口返回值包含token信息接口信息   返回值   2、在登录接口的后执行脚本,添加环境变量 apt.environment.set("accessToken",response.js......
  • 测试项目(五):数据分页查询(后端接口)
    好家伙, 这里我们必须考虑:当数据库表单数据过多时,我们必须增加分页展示想想上百条数据一页展示完,那么可能找不到我要的那条数据了 我们前后端分开处理:本篇介绍完成后......
  • robotframework自动化测试框架实战教程:创建及使用监听器(listener)接口
    RobotFramework提供了一个监听器(listener)接口可以用来接收测试执行过程中的通知. 监听器通过在命令行中设置选项 --listener 来启用,和导入测试库类似,你也可以指定......
  • drf接口文档
    接口文档接口编写已经写完了,需要编写接口文档,给前端的人使用-请求地址-请求方式-支持的编码格式-请求参数(get,post参数)-返回格式示例在公司的写法1)直接使用word......
  • 网络工程知识(二)VLAN的基础和配置:802.1q帧;Access、Trunk、Hybrid接口工作模式过程与配
    介绍-VLANVLAN(VirtualLocalAreaNetwork)即虚拟局域网,工作在数据链路层。交换机将通过:接口、MAC、基于子网、协议划分(IPv4和IPv6)、基于策略的方式划分VLAN的方式,将接......
  • nginx 配置一个网站多个接口
    vue一个前端但是后端接口多个,在nginx中配置:server{listen10001;server_nameshare_pingtai;location/{root......
  • 2022年十大接口测试工具合集《建议.收藏》
    接口测试的全称是应用程序编程接口(API)测试,从原理上来说,接口测试是模拟客户端向服务器端发送请求,然后检查能否获得正确的返回信息。接口测试用于测试RESTfulAPI、SOAPWeb服......
  • Linux 文件操作接口
    目录Linux文件操作接口C语言文件操作接口C语言文件描述fopen()r模式打开文件w模式打开文件a模式打开文件其他模式类似fclose()fwrite()fread()系统文件操作接口文件描述符......
  • 接口
    什么是接口接口的作用1.约束2.定义一些方法,让不同的人实现3.接口中默认的方法:publicabstract4.接口中默认的长乐:publicstaticfinal5.接口不能被实例化,接口中......
  • 接口文档所需内容
    文档的存储说明:可以使用第三方的管理文档工具,也可以根据当前自己公司的所需所采用的方式都可以,管理工具:eolinker网站链接:​​https://www.eolinker.com/#/invite/?invit......