" />

欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 防止接口惡意刷新和暴力請(qǐng)求的實(shí)現(xiàn)

 更新時(shí)間:2022年06月06日 12:29:38   作者:wang_shuyu  
本文主要介紹了Spring Boot 防止接口惡意刷新和暴力請(qǐng)求的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

在實(shí)際項(xiàng)目使用中,必須要考慮服務(wù)的安全性,當(dāng)服務(wù)部署到互聯(lián)網(wǎng)以后,就要考慮服務(wù)被惡意請(qǐng)求和暴力攻擊的情況,下面的教程,通過(guò)intercept和redis針對(duì)url+ip在一定時(shí)間內(nèi)訪問(wèn)的次數(shù)來(lái)將ip禁用,可以根據(jù)自己的需求進(jìn)行相應(yīng)的修改,來(lái)打打自己的目的;

首先工程為springboot框架搭建,不再詳細(xì)敘述。直接上核心代碼。

首先創(chuàng)建一個(gè)自定義的攔截器類(lèi),也是最核心的代碼;

/**
 * @package: com.technicalinterest.group.interceptor
 * @className: IpUrlLimitInterceptor
 * @description: ip+url重復(fù)請(qǐng)求現(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請(qǐng)求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAdrress(httpServletRequest));
        if (ipIsLock(IpAdrressUtil.getIpAdrress(httpServletRequest))){
            log.info("ip訪問(wèn)被禁止={}",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: 記錄請(qǐng)求次數(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的使用的是分布式鎖的形式,這樣可以最大程度保證線程安全和功能的實(shí)現(xiàn)效果。代碼中設(shè)置的是1S內(nèi)同一個(gè)接口通過(guò)同一個(gè)ip訪問(wèn)5次,就將該ip禁用1個(gè)小時(shí),根據(jù)自己項(xiàng)目需求可以自己適當(dāng)修改,實(shí)現(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:?jiǎn)挝?秒
?? ? * @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;
?? ?}
?
}

最后將上面自定義的攔截器通過(guò)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);
    }
}

自己可以寫(xiě)一個(gè)for循環(huán)來(lái)測(cè)試方面的功能,這里就不詳細(xì)介紹了;

到此這篇關(guān)于Spring Boot 防止接口惡意刷新和暴力請(qǐng)求的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Spring Boot 防止接口惡意刷新和暴力請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中redisTemplate注入失敗NullPointerException異常問(wèn)題解決

    Java中redisTemplate注入失敗NullPointerException異常問(wèn)題解決

    這篇文章主要介紹了Java中redisTemplate注入失敗NullPointerException異常問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2023-08-08
  • Java語(yǔ)言描述MD5加密工具類(lèi)實(shí)例代碼

    Java語(yǔ)言描述MD5加密工具類(lèi)實(shí)例代碼

    這篇文章主要介紹了Java語(yǔ)言描述MD5加密工具類(lèi)實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Spark操作之a(chǎn)ggregate、aggregateByKey詳解

    Spark操作之a(chǎn)ggregate、aggregateByKey詳解

    這篇文章主要介紹了Spark操作之a(chǎn)ggregate、aggregateByKey詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • 淺談java運(yùn)用注解實(shí)現(xiàn)對(duì)類(lèi)中的方法檢測(cè)的工具

    淺談java運(yùn)用注解實(shí)現(xiàn)對(duì)類(lèi)中的方法檢測(cè)的工具

    這篇文章主要介紹了淺談java運(yùn)用注解實(shí)現(xiàn)對(duì)類(lèi)中的方法檢測(cè)的工具,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Springboot讀取配置文件及自定義配置文件的方法

    Springboot讀取配置文件及自定義配置文件的方法

    這篇文章主要介紹了Springboot讀取配置文件及自定義配置文件的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-12-12
  • Spring簡(jiǎn)明分析Bean作用域

    Spring簡(jiǎn)明分析Bean作用域

    scope用來(lái)聲明容器中的對(duì)象所應(yīng)該處的限定場(chǎng)景或者說(shuō)該對(duì)象的存活時(shí)間,即容器在對(duì)象進(jìn)入其 相應(yīng)的scope之前,生成并裝配這些對(duì)象,在該對(duì)象不再處于這些scope的限定之后,容器通常會(huì)銷(xiāo)毀這些對(duì)象,這篇文章主要介紹了Spring中的Bean作用域,需要的朋友可以參考下
    2022-07-07
  • 解決Maven項(xiàng)目本地公共common包緩存問(wèn)題

    解決Maven項(xiàng)目本地公共common包緩存問(wèn)題

    這篇文章主要介紹了解決Maven項(xiàng)目本地公共common包緩存問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Spring根據(jù)XML配置文件 p名稱(chēng)空間注入屬性的實(shí)例

    Spring根據(jù)XML配置文件 p名稱(chēng)空間注入屬性的實(shí)例

    下面小編就為大家分享一篇Spring根據(jù)XML配置文件 p名稱(chēng)空間注入屬性的實(shí)例,具有很好的參考價(jià)值。希望對(duì)大家有所幫助
    2017-11-11
  • Java實(shí)現(xiàn)多人聊天室的原理與源碼

    Java實(shí)現(xiàn)多人聊天室的原理與源碼

    這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)多人聊天室的原理與源碼的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • SpringMVC中的@RequestMapping注解解析

    SpringMVC中的@RequestMapping注解解析

    這篇文章主要介紹了SpringMVC中的@RequestMapping注解解析,SpringMVC使用@RequestMapping注解為控制器指定可以處理哪些?URL?請(qǐng)求,在控制器的類(lèi)定義及方法定義處都可標(biāo)注@RequestMapping,需要的朋友可以參考下
    2023-12-12

最新評(píng)論