配置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");
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
String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
LOGGER.info("login cookieValue : {}", cookieValue);
if(cookieValue == null) {
response.addCookie(new Cookie(imgCookieName, UUID.randomUUID().toString()));
}
生成图片API
@Autowired
DefaultKaptcha defaultKaptcha;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@GetMapping("/verify")
public void verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
String cookieValue = IpUtils.getCookieValue(request, imgCookieName);
LOGGER.info("verify cookieValue : {}", cookieValue);
String createText = defaultKaptcha.createText();
LOGGER.info("verify createText : {}", createText);
redisTemplate.opsForValue().set(cookieValue, createText, 60, TimeUnit.SECONDS);
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
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 ... ");
}