Spring Boot反爬虫、接口防盗刷

概述

kk-anti-reptile 是适用于基于 spring-boot 开发的分布式系统的开源反爬虫接口防刷组件。本文采用kk-anti-reptile。

系统要求

  • 基于 spring-boot 开发(spring-boot1.x, spring-boot2.x 均可)
  • 需要使用 redis

工作流程

kk-anti-reptile 使用 SpringMVC拦截器 对请求进行过滤,通过 spring-boot 的扩展点机制,实例化一个Spring HandlerInterceptor Bean,通过 Spring 注入到 Servlet 容器中,从而实现对请求的过滤

在 kk-anti-reptile 的过滤 Interceptor 内部,又通过责任链模式,将各种不同的过滤规则织入,并提供抽象接口,可由调用方进行规则扩展

Interceptor 调用则链进行请求过滤,如过滤不通过,则拦截请求,返回状态码509,并输出验证码输入页面,输出验证码正确后,调用过滤规则链对规则进行重置

目前规则链中有如下两个规则

ip-rule

ip-rule 通过时间窗口统计当前时间窗口内请求数,小于规定的最大请求数则可通过,否则不通过。时间窗口、最大请求数、ip 白名单等均可配置

ua-rule

ua-rule 通过判断请求携带的 User-Agent,得到操作系统、设备信息、浏览器信息等,可配置各种维度对请求进行过滤

验证码页面

命中爬虫和防盗刷规则后,会阻断请求,并生成接除阻断的验证码,验证码有多种组合方式,如果客户端可以正确输入验证码,则可以继续访问

image

验证码有中文、英文字母+数字、简单算术三种形式,每种形式又有静态图片和 GIF 动图两种图片格式,即目前共有如下六种,所有类型的验证码会随机出现,也就是每次出现的验证码不一定是什么形式,目前技术手段识别难度极高,可有效阻止防止爬虫大规模爬取数据

image
image
image
image
image
image

接入使用

接入非常简单,只需要引用 kk-anti-reptile 的 maven 依赖,并配置启用 kk-anti-reptile 即可, 需要有Redis服务可用。

1. 加入 maven 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.erbadagang.springboot.anti.reptile</groupId>
    <artifactId>anti-reptile</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>anti-reptile</name>
    <description>反爬虫组件 project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!--    anti-reptile-->
        <dependency>
            <groupId>cn.keking.project</groupId>
            <artifactId>kk-anti-reptile</artifactId>
            <version>1.0.0-RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.11.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--MySQL数据库连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. 配置启用 kk-anti-reptile

在spring-boot的application.properties配置文件中加入如下配置 anti.reptile.manager.enabled

anti.reptile.manager.enabled = true

3. 配置需要反爬的接口

配置反爬接口有如下两种方式,两种方式可以同时使用

  1. 使用的application.properties配置文件

在spring-boot配置文件中加入如下配置项anti.reptile.manager.include-urls,值为反爬的接口URI(如:/client/list),支持正则表达式匹配(如:^/admin/.*$),多项用,分隔

anti.reptile.manager.include-urls = /client/list,/user/list,^/admin/.*$

  1. 使用注解

在需要反爬的接口Controller对象对应的接口上加上@AntiReptile注解即可,示例如下

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @AntiReptile
    @GetMapping("selectOne")
    public Optional<UsersEntity> findById(Integer id) {
        return this.usersService.findById(id);
    }

4. 前端统一处理验证码页面

前端需要在统一发送请求的 ajax 处加入拦截,拦截到请求返回状态码509后弹出一个新页面,并把响应内容转出到页面中,然后向页面中传入后端接口baseUrl参数即可,以使用 axios 请求为例:

import axios from 'axios';
import {baseUrl} from './config';

axios.interceptors.response.use(
 data => {
 return data;
 },
 error => {
 if (error.response.status === 509) {
 let html = error.response.data;
 let verifyWindow = window.open("","_blank","height=400,width=560");
 verifyWindow.document.write(html);
 verifyWindow.document.getElementById("baseUrl").value = baseUrl;
 }
 }
);

export default axios;

注意

  1. apollo-client 需启用 bootstrap

使用 apollo 配置中心的用户,由于组件内部用到@ConditionalOnProperty,要在 application.properties/bootstrap.properties 中加入如下样例配置,(apollo-client 需要 0.10.0 及以上版本)详见apollo bootstrap 说明

apollo.bootstrap.enabled = true

  1. 需要有 Redisson 连接

如果项目中有用到 Redisson,kk-anti-reptile 会自动获取 RedissonClient 实例对象; 如果没用到,需要在配置文件加入如下 Redisson 连接相关配置

spring.redisson.address = redis://192.168.1.204:6379
spring.redisson.password = xxx

配置一览表

在 spring-boot 中,所有配置在配置文件都会有自动提示和说明,如下图:
配置自动提示及说明

所有配置都以anti.reptile.manager为前缀,如下为所有配置项及说明:

NAME 描述 默认值 示例
enabled 是否启用反爬虫插件 true true
globalFilterMode 是否启用全局拦截模式 false true
include-urls 局部拦截时,需要反爬的接口列表,以','分隔,支持正则匹配。全局拦截模式下无需配置 /client,/user,^/admin/.*$
ip-rule.enabled 是否启用 IP Rule true true
ip-rule.expiration-time 时间窗口长度(ms) 5000 5000
ip-rule.request-max-size 单个时间窗口内,最大请求数 20 20
ip-rule.lock-expire 命中规则后自动解除时间(单位:s) 10天 20
ip-rule.ignore-ip IP 白名单,支持后缀'*'通配,以','分隔 192.168.*,127.0.0.1
ua-rule.enabled 是否启用 User-Agent Rule true true
ua-rule.allowed-linux 是否允许 Linux 系统访问 false false
ua-rule.allowed-mobile 是否允许移动端设备访问 true true
ua-rule.allowed-pc 是否允许移 PC 设备访问 true true
ua-rule.allowed-iot 是否允许物联网设备访问 false false
ua-rule.allowed-proxy 是否允许代理访问 false false

测试

启动Springboot应用。

依据我们配置的规则,5秒内访问5次就拦截:

anti.reptile.manager.ip-rule.expiration-time=5000
anti.reptile.manager.ip-rule.request-max-size=5

浏览器访问URL:http://localhost:8080/users/selectOne?id=5
正常访问的时候顺利返回json数据:{"id":5,"username":"26d29bbd-d38f-4ae1-8ff8-bfbf6afc23bc","password":"guoxiuzhi","createTime":"2020-07-14T04:46:40.000+00:00","deleted":1}
快速访问会弹出验证码页面:

验证码页面

验证码的样式是数字、汉字还是动静态都是随机的,增加机器识别难度。

验证码输入正确并提交以后,再次访问URL:http://localhost:8080/users/selectOne?id=5恢复正常的返回json数据。

底线


本文源代码使用 Apache License 2.0开源许可协议,本文完整代码可如下地址通过git clone命令下载到本地或者通过浏览器方式查看源代码。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,440评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,814评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,427评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,710评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,625评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,511评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,162评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,311评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,262评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,278评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,989评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,583评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,664评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,904评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,274评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,856评论 2 339