Springboot中使用Google 的Kaptcha工具实现验证码校验

一般官网用户登录的时候需要输入一个临时验证码,防止网站被脚本或者工具恶意刷页面,这个验证码可以通过谷歌开源的Kaptcha工具来实现,步骤如下:
1、maven集成:

   <!--验证码生成工具-->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

2、添加属性配置类,这里可以通过设置背景颜色,字体大小,以及验证码的数字范围:

@Configuration
public class KaptchaConfig {
    
    

    @Bean
    public Config config(){
    
    
        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");
        Config config = new Config(properties);
        return config;
    }

    @Bean
    public Producer producer(Config config){
    
    
        DefaultKaptcha producer = new DefaultKaptcha();
        producer.setConfig(config);
        return producer;
    }
}

3、在controller里面写个接口给前端调用,直接生成照片返回去给前端展示即可:


    @Autowired
    private Producer producer;


    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
    
    
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
//        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

4、使用postman调用接口,既可以看到结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_46589575/article/details/115177801