Spring Boot整合Kaptcha实现验证码功能

一、前言

kaptcha 是一个很有用的验证码生成工具,由于它有许多可配置项,所以用它可以简单快捷的生成各式各样的验证码。

1.Kaptcha 简介

Kaptcha谷歌验证码) 是一个可高度配置的实用验证码生成工具,可自由配置的选项如:

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线
  • 验证码的样式(鱼眼样式、3D、普通模糊、…)

2.Kaptcha 详细配置表

在这里插入图片描述

二、实现

实现思路:
1.整合kaptcha,创建kaptcha的工具类
2.编写接口,在接口中使用 kaptcha 工具类来生成验证码图片(验证码信息)并返回
3.登录时从 session 中获取验证码进行校验
4.测试获取验证码图片(验证码信息)接口

1.整合kaptcha,创建kaptcha的工具类

1.1 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--谷歌 验证码-->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

1.2 创建KaptchaConfig工具类

package com.example.validationcodedemo.config;

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;

/**
 * 谷歌验证码配置文件
 * @author qzz
 */
@Configuration
public class KaptchaConfig {
    
    


    @Bean(name = "kaptchaProducer")
    public DefaultKaptcha getKaptchaBean(){
    
    
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

        Properties properties = new Properties();
        //是否有边框 默认true 也可以自己设置yes,no
        properties.setProperty("kaptcha.border", "no");
        //验证码文本字符颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        // 验证码图片宽度 默认为200
        properties.setProperty("kaptcha.image.width", "160");
        // 验证码图片高度 默认为50
        properties.setProperty("kaptcha.image.height", "60");
        // 验证码文本字符大小 默认为40
        properties.setProperty("kaptcha.textproducer.font.size", "38");
        //存储在session中值的key
        properties.setProperty("kaptcha.session.key", "kaptchaCode");
        // 验证码文本字符长度 默认为5
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");
        // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");

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

    }

    @Bean(name = "kaptchaProducerMath")
    public DefaultKaptcha getKaptchaBeanMath(){
    
    
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

        Properties properties = new Properties();
        //是否有边框 默认true 也可以自己设置yes,no
        properties.setProperty("kaptcha.border", "yes");
        //边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        //验证码文本字符颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        // 验证码图片宽度 默认为200
        properties.setProperty("kaptcha.image.width", "160");
        // 验证码图片高度 默认为50
        properties.setProperty("kaptcha.image.height", "60");
        // 验证码文本字符大小 默认为40
        properties.setProperty("kaptcha.textproducer.font.size", "38");
        //存储在session中值的key
        properties.setProperty("kaptcha.session.key", "kaptchaCodeMath");
        //验证码文本生成器
        properties.setProperty("kaptcha.textproducer.impl","com.tonglei.config.KaptchaTextCreator");
        // 验证码文本字符间距 默认为2
        properties.setProperty("kaptcha.textproducer.char.space", "3");
        // 验证码文本字符长度 默认为5
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");
        // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        // 验证码噪点颜色 默认为Color.BLACK
        properties.setProperty("kaptcha.noise.color", "black");
        // 干扰实现类  DefaultNoise\NoNoise
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");

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

    }
}

2 编写接口,在接口中使用 kaptcha 工具类来生成验证码图片(验证码信息)并返回

编写获取验证码图片或者验证码信息功能接口:

package com.example.validationcodedemo.controller;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 * @author qzz
 */
@RestController
public class ValidationCodeController {
    
    

    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private Producer kaptchaProducerMath;

    /**
     * 生成验证码图片
     * @param request
     * @param response
     */
    @RequestMapping("/createKaptchaCodeImg")
    public void createKaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        response.setHeader("Cache-Control","no-store");
        response.setContentType("image/jpeg");

        //文本验证码
        String text = kaptchaProducer.createText();
        //图片验证码
        BufferedImage image = kaptchaProducer.createImage(text);
        //保存验证码到session
        request.getSession().setAttribute("kaptchaCode",text);

        ServletOutputStream outputStream = response.getOutputStream();
        //设置写出图片的格式
        ImageIO.write(image,"jpg",outputStream);
        //关闭输出流
        IOUtils.closeQuietly(outputStream);
    }

    /**
     * 生成验证码图片(有边框)
     * @param request
     * @param response
     */
    @RequestMapping("/createKaptchaCodeImg2")
    public void createKaptchaCode2(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        response.setHeader("Cache-Control","no-store");
        response.setContentType("image/jpeg");

        //文本验证码
        String text = kaptchaProducer.createText();
        //图片验证码
        BufferedImage image = kaptchaProducerMath.createImage(text);
        //保存验证码到session
        request.getSession().setAttribute("kaptchaCodeMath",text);

        ServletOutputStream outputStream = response.getOutputStream();
        //设置写出图片的格式
        ImageIO.write(image,"jpg",outputStream);
        //关闭输出流
        IOUtils.closeQuietly(outputStream);
    }

3 登录时从session中获取验证码进行校验

    /**
     * 用户登录 校验验证码
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginRequestJson requestJson,HttpServletRequest request){
    
    
        Result result = new Result();
        //从session中获取验证码
        String kaptchaCode = String.valueOf(request.getSession().getAttribute("kaptchaCode"));
        //用户输入和session获取的验证码进行验证
        if (!requestJson.getCode().equals(kaptchaCode)){
    
    
            //验证码验证失败
            return Result.fail(10910,"验证码不正确,请重新输入");
        }
        //登录流程...(省略)
        return Result.success();
    }

注意:从session中获取验证码时,key值一定要和前面生成验证码时存储的key保持一致。

4.测试

4.1 测试获取验证码图片的接口

在这里插入图片描述

4.2 登录接口(校验验证码)

验证码输入错误:
在这里插入图片描述

验证码输入正确:
在这里插入图片描述

三、完整代码

可点击此处下载

猜你喜欢

转载自blog.csdn.net/qq_26383975/article/details/129237017