谷歌开源kaptcha介绍

  • Kaptcha 框架是谷歌开源的一个可高度配置的实用验证码生成工具

    • 验证码的字体/大小/颜色
    • 验证码内容的范围(数字,字母,中文汉字!)
    • 验证码图片的大小,边框,边框粗细,边框颜色
    • 验证码的干扰线
    • 验证码的样式(鱼眼样式、3D、普通模糊)
  • Kaptcha详细配置表

Kaptcha配置表

用户微服务整合Kaptcha

  • 聚合工程依赖添加(使用国内baomidou二次封装的springboot整合starter)
1
2
3
4
5
6
<!--kaptcha依赖包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
  • 用户服务添加
1
2
3
4
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
</dependency>
  • 开发配置(任何框架和springboot整合基本都是)
    • 在用户服务的 net.xdclass.config 目录下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
* @author Rajesh Jiang
* @date 2022/7/18 8:12
*/
@Configuration
public class CaptchaConfig {

/**
* 验证码配置
* Kaptcha配置类名
*
* @return
*/
@Bean
@Qualifier("captchaProducer")
public DefaultKaptcha kaptcha() {
DefaultKaptcha kaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// properties.setProperty(Constants.KAPTCHA_BORDER, "yes");
// properties.setProperty(Constants.KAPTCHA_BORDER_COLOR, "220,220,220");
// //properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "38,29,12");
// properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, "147");
// properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, "34");
// properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "25");
// //properties.setProperty(Constants.KAPTCHA_SESSION_KEY, "code");
//验证码个数
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
// properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Courier");
//字体间隔
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE,"8");
//干扰线颜色
// properties.setProperty(Constants.KAPTCHA_NOISE_COLOR, "white");
//干扰实现类
properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
//图片样式
properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");
//文字来源
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789");
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
  • 开发一个Controller使用测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Api(tags = "通知模块")
@RestController
@RequestMapping("api/user/v1")
@Slf4j
public class NotifyController {

@Autowired
private Producer captchaProducer;

@GetMapping("/captcha")
public void getCaptcha(HttpServletResponse response) {
String producerText = captchaProducer.createText();
log.info("图形验证码:{}", producerText);

BufferedImage producerImage = captchaProducer.createImage(producerText);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
ImageIO.write(producerImage, "jpg", outputStream);
outputStream.flush();
outputStream.close();
}catch(IOException e) {
log.error("获取图形验证码错误:{}", e.getMessage());
}
}
}
  • 启动项目,使用postman请求

Postman测试

docker安装和部署容器化redis

  • Linux上docker安装步骤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 依次运行以下命令添加yum源
yum update
yum install epel-release -y
yum clean all
yum list

# 安装并运行Docker
yum install docker-io -y
systemctl start docker

# 检查安装结果
docker info

# 启动使用Docker
systemctl start docker # 运行Docker守护进程
systemctl stop docker # 停止Docker守护进程
systemctl restart docker # 重启Docker守护进程

# 修改镜像仓库
vim /etc/docker/daemon.json
# 改为下面内容,然后重启docker
{
"debug":true,"experimental":true,
"registry-mirrors":["https://pb5bklzr.mirror.aliyuncs.com","https://hub-mirror.c.163.com","https://docker.mirrors.ustc.edu.cn"]
}

# 查看信息
docker info
  • docker部署redis 并配置密码
    • 如果访问不了,记得看防火墙/网络安全组端口是否开放
    • 源码安装redis的话默认不能远程访问
    • docker安装redis可以远程访问
1
docker run -itd --name xdclass-redis -p 6379:6379 redis --requirepass 123456
  • 参数说明
1
2
3
-i  以交互模式运行容器,通常与 -t 同时使用
-t 为容器重新分配一个伪输入终端,通常与 -i 同时使用
-d 后台运行容器,并返回容器ID

图形验证码加入redis缓存

  • redis做隔离, 多集群:核心集群和非核心集群,高并发集群和非高并发集群

    • 资源隔离
    • 数据保护
    • 提高性能
    • key规范:业务划分,冒号隔离
      • user-service:captcha:xxxx
      • 长度不能过长
  • 用户服务配置redis

1
2
3
4
5
6
7
spring:
application:
name: xdclass-user-service
redis:
host: 112.74.55.160
password: 123456
port: 6379
  • 在common项目下添加redis客户端依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--redis客户端-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
  • 在common项目下,新增CommonUtil类,添加获取请求IP及MD5加密
    • 在common项目的 net.xdclass.util 目录下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@Slf4j
public class CommonUtil {

/**
* 获取ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
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")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
// "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
return ipAddress;
}

/**
* MD5加密
* @param data
* @return
*/
public static String MD5(String data) {
try {
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
} catch (Exception exception) {
log.error("MD5加密失败:{}", exception.getMessage());
}
return null;
}
}
  • 验证码接口开发
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@Api(tags = "通知模块")
@RestController
@RequestMapping("api/user/v1")
@Slf4j
public class NotifyController {

@Autowired
private Producer captchaProducer;

@Autowired
private StringRedisTemplate redisTemplate;

/**
* 临时使用10分钟测试
*/
private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

@GetMapping("/captcha")
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
String producerText = captchaProducer.createText();
log.info("图形验证码:{}", producerText);
// 生成缓存key
String cacheKey = getCaptchaKey(request);
// redis存储
redisTemplate.opsForValue()
.set(cacheKey,producerText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

BufferedImage producerImage = captchaProducer.createImage(producerText);
ServletOutputStream outputStream = null;
try {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "create_date-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
outputStream = response.getOutputStream();
ImageIO.write(producerImage, "jpg", outputStream);
outputStream.flush();
outputStream.close();
}catch(IOException e) {
log.error("获取图形验证码错误:{}", e.getMessage());
}
}

/**
* 图形验证码获取redis缓存中的值
* @param request
* @return
*/
@GetMapping("/getValue")
public String getCacheValue(HttpServletRequest request) {
String captchaKey = getCaptchaKey(request);
return redisTemplate.opsForValue().get(captchaKey);
}

/**
* 获取缓存的key
* @param request
* @return
*/
private String getCaptchaKey(HttpServletRequest request){
String ip = CommonUtil.getIpAddr(request);
String userAgent = request.getHeader("User-Agent");
return "user-service:captcha:"+CommonUtil.MD5(ip+userAgent);
}
}
  • 使用postman调用

Postman测试验证码

验证码响应

  • 使用redis工具RDM查看

RDM查看Redis