配置pom.xml
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
默认工具配置:KaptchaConfig
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 图片边框
properties.setProperty("kaptcha.border", "yes");
// 边框颜色
properties.setProperty("kaptcha.border.color", "105,179,90");
// 字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "red");
// 图片宽
properties.setProperty("kaptcha.image.width", "100");
// 图片高
properties.setProperty("kaptcha.image.height", "34");
// 字体大小
properties.setProperty("kaptcha.textproducer.font.size", "30");
// session key
properties.setProperty("kaptcha.session.key", "code");
// 验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
// 字体
properties.setProperty("kaptcha.textproducer.font.names", "Consolas");
// 设置字符串范围
properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
登录页面种植Cookie
// 获取种植的cookie
String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
LOGGER.info("login cookieValue : {}", cookieValue);
if(cookieValue == null) {
// 给前端种植一个cookie,用于图片验证码校验
response.addCookie(new Cookie(imgCookieName, UUID.randomUUID().toString()));
}
生成图片API
/**
* 验证码工具
*/
@Autowired
DefaultKaptcha defaultKaptcha;
/**
* redis缓存数据
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 获取图片验证码
* @throws IOException
*/
@GetMapping("/verify")
public void verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取种植的cookie
String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
LOGGER.info("verify cookieValue : {}", cookieValue);
// 生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
LOGGER.info("verify createText : {}", createText);
// 缓存图片验证码到redis,设置超时时间1分钟
redisTemplate.opsForValue().set(cookieValue, createText, 60, TimeUnit.SECONDS);
// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
// 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
LOGGER.info("verify end ... ");
}