Spring Boot 防止接口惡意刷新和暴力請求的實現(xiàn)
在實際項目使用中,必須要考慮服務(wù)的安全性,當(dāng)服務(wù)部署到互聯(lián)網(wǎng)以后,就要考慮服務(wù)被惡意請求和暴力攻擊的情況,下面的教程,通過intercept和redis針對url+ip在一定時間內(nèi)訪問的次數(shù)來將ip禁用,可以根據(jù)自己的需求進行相應(yīng)的修改,來打打自己的目的;
首先工程為springboot框架搭建,不再詳細敘述。直接上核心代碼。
首先創(chuàng)建一個自定義的攔截器類,也是最核心的代碼;
/**
* @package: com.technicalinterest.group.interceptor
* @className: IpUrlLimitInterceptor
* @description: ip+url重復(fù)請求現(xiàn)在攔截器
* @author: Shuyu.Wang
* @date: 2019-10-12 12:34
* @since: 0.1
**/
@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())){
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是否被禁用
* @author: shuyu.wang
* @date: 2019-10-12 13:08
* @param ip
* @return java.lang.Boolean
*/
private Boolean ipIsLock(String ip){
RedisUtil redisUtil=getRedisUtil();
if(redisUtil.hasKey(LOCK_IP_URL_KEY+ip)){
return true;
}
return false;
}
/**
* @Description: 記錄請求次數(shù)
* @author: shuyu.wang
* @date: 2019-10-12 17:18
* @param ip
* @param uri
* @return java.lang.Boolean
*/
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,(long)1);
if (time>=LIMIT_TIMES){
redisUtil.getLock(LOCK_IP_URL_KEY+ip,ip,IP_LOCK_TIME);
return false;
}
}else {
redisUtil.getLock(key,(long)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();
writer.print(json);
} catch (IOException e) {
log.error("LoginInterceptor response error ---> {}", e.getMessage(), e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
代碼中redis的使用的是分布式鎖的形式,這樣可以最大程度保證線程安全和功能的實現(xiàn)效果。代碼中設(shè)置的是1S內(nèi)同一個接口通過同一個ip訪問5次,就將該ip禁用1個小時,根據(jù)自己項目需求可以自己適當(dāng)修改,實現(xiàn)自己想要的功能;
redis分布式鎖的關(guān)鍵代碼:
/**
?* @package: com.shuyu.blog.util
?* @className: RedisUtil
?* @description:
?* @author: Shuyu.Wang
?* @date: 2019-07-14 14:42
?* @since: 0.1
?**/
@Component
@Slf4j
public class RedisUtil {
?
?? ?private static final Long SUCCESS = 1L;
?
?? ?@Autowired
?? ?private RedisTemplate<String, Object> redisTemplate;
?? ?// =============================common============================
?
?? ?
?
?? ?/**
?? ? * 獲取鎖
?? ? * @param lockKey
?? ? * @param value
?? ? * @param expireTime:單位-秒
?? ? * @return
?? ? */
?? ?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);
?? ??? ??? ?Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
?? ??? ??? ?if (SUCCESS.equals(result)) {
?? ??? ??? ??? ?return true;
?? ??? ??? ?}
?? ??? ?} catch (Exception e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ??? ?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;
?? ?}
?
}最后將上面自定義的攔截器通過registry.addInterceptor添加一下,就生效了;
@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);
}
}
自己可以寫一個for循環(huán)來測試方面的功能,這里就不詳細介紹了;
到此這篇關(guān)于Spring Boot 防止接口惡意刷新和暴力請求的實現(xiàn)的文章就介紹到這了,更多相關(guān)Spring Boot 防止接口惡意刷新和暴力請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot搭建go-cqhttp機器人的方法實現(xiàn)
本文主要介紹了SpringBoot搭建go-cqhttp機器人的方法實現(xiàn)2021-12-12
Java技巧分享之利用RxJava打造可觀測數(shù)據(jù)RxLiveData
這篇文章主要來和大家分享一個Java技巧,那就是利用RxJava打造可觀測數(shù)據(jù)RxLiveData,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-06-06
從零實現(xiàn)一個簡單的Spring Bean容器的代碼案例
Spring是一個非常流行的Java?Web開發(fā)框架,它提供了強大的依賴注入、面向切面編程、聲明式事務(wù)管理等功能,為開發(fā)者提供了高效、快速地構(gòu)建Web應(yīng)用程序的工具,在這篇文章中,咱們將一步一步地構(gòu)建一個簡單的SpringBean容器,需要的朋友可以參考下2023-06-06
SpringBoot Redis實現(xiàn)接口冪等性校驗方法詳細講解
這篇文章主要介紹了SpringBoot Redis實現(xiàn)接口冪等性校驗方法,近期一個老項目出現(xiàn)了接口冪等性校驗問題,前端加了按鈕置灰,依然被人拉著接口參數(shù)一頓輸出,還是重復(fù)調(diào)用了接口,通過復(fù)制粘貼,完成了后端接口冪等性調(diào)用校驗2022-11-11
SpringBoot集成WebServlet出現(xiàn)自定義servlet請求失敗的問題解決方案
SpringBoot中以Bean方式注冊Servlet時遇到的問題,通過了解DispatcherServlet的原理,發(fā)現(xiàn)默認路徑?jīng)_突是主要原因,本文介紹SpringBoot集成WebServlet出現(xiàn)自定義servlet請求失敗的問題解決方案,感興趣的朋友一起看看吧2025-03-03
SpringBoot項目刪除Bean或者不加載Bean的問題解決
文章介紹了在Spring Boot項目中如何使用@ComponentScan注解和自定義過濾器實現(xiàn)不加載某些Bean的方法,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-01-01
Java并發(fā)J.U.C并發(fā)容器類list set queue
這篇文章主要為大家介紹了Java并發(fā),J.U.C并發(fā)容器類list set queue,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06

