验证码-kaptcha

常见的验证码方案有 kaptcha 等。本篇记录 kaptcha 用法

kaptcha

引入依赖

<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

配置验证码

    @Bean
    Producer verifyCode() {
        Properties properties = new Properties();
//        默认图片样式
        properties.put("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.FishEyeGimpy");
//        图片边框
        properties.put("kaptcha.border", "yes");
//        文字颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
        properties.put("kaptcha.textproducer.font.color", "blue");
//        默认图片间隔
        properties.put("kaptcha.textproducer.char.space", "5");
//        默认生成图形验证码宽度
        properties.put("kaptcha.image.width", "120");
//        默认生成图像验证码高度
        properties.put("kaptcha.image.height", "50");
//        验证码文字大小
        properties.put("kaptcha.textproducer.font.size", "30");
//        指定字符集
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
//        指定验证码长度
        properties.put("kaptcha.textproducer.char.length", "4");
//        干扰颜色,合法值: r,g,b 或者 white,black,blue
        properties.put("kaptcha.noise.color", "blue");

        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

生成验证码

@Autowired
private CodeService codeService;

@GetMapping("/getCode")
public void code(HttpServletResponse resp) throws IOException {
//    MediaType.IMAGE_JPEG_VALUE
    resp.setContentType("image/jpeg");
    try (ServletOutputStream out = resp.getOutputStream()) {
        ImageIO.write(producer.createImage(producer.createText()), "jpg", out);
    }
}

参考

  1. SpringSecurity 自定义认证逻辑的两种方式(高级玩法)
  2. 验证码 KAPTCHA 参数详解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值