-
Kaptcha 介绍
验证码(CAPTCHA):是 Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。
作用:可以防止 恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。
这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答 CAPTCHA 的问题,所以回答出问题的用户就可以被认为是人类。
Kaptcha 是谷歌放在 github 上的一个验证码 jar 包,是一个基于 SimpleCaptcha 的验证码开源项目,我们可以简单配置属性就可以实现验证码的验证功能。
kaptcha 官网地址:https://www.mvnjar.com/com.github.penggle/kaptcha/2.3.2/detail.html
-
在 SpringBoot 中使用 Kaptcha 步骤
1、可以到官网下载 kaptcha 的 jar 包,或者在 pom.xml 中配置 maven 依赖
<!--验证码生成工具-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2、添加 kaptcha 的图片配置,创建 bean 并注册(springboot 有两种注册方式,xml 配置和 java 代码注解配置)
2.1、java 代码注解配置(推荐使用),创建一个配置类,代码如下:
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* kaptcha验证码生成器配置
* @author lwf
* @date 2019/8/21 16:10
*/
@Configuration
public class KaptchaConfig {
/**
* 配置生成图片的bean
* @return
*/
@Bean(name = "kaptchaProducer")
public DefaultKaptcha getKaptchaBean() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
properties.setProperty("kaptcha.border", "no");
properties.setProperty("kaptcha.textproducer.font.color", "black");
properties.setProperty("kaptcha.textproducer.char.space", "4");
properties.setProperty("kaptcha.textproducer.char.length", "4");
properties.setProperty("kaptcha.textproducer.char.string", "123456789