Kaptcha

  • Kaptcha,是Google开源的一个可高度配置的实用验证码生成工具。

1.在Springboot中导入:

1
2
3
4
5
 <dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>

2.添加Kaptcha的配置规则

  • 可用xml也可以Class (此处采用Class配置)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package kid1999.upload.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.Properties;

/**
* @desc: Kaptcha 配置类
* @auther: kid1999
* @date: 2019/12/21 12:19
**/

@Service
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.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", "120");
// 图片高
properties.setProperty("kaptcha.image.height", "40");
// 字体大小
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", "宋体,楷体,微软雅黑");

properties.setProperty("kaptcha.noise.color", "35,37,38");

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

return defaultKaptcha;
}
}

3.配置验证码的生成和核对

  • 新建一个Controller
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    package kid1999.upload.controller;

    import com.google.code.kaptcha.impl.DefaultKaptcha;
    import kid1999.upload.dto.Result;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;

    import javax.imageio.ImageIO;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.awt.image.BufferedImage;

    /**
    * @desc:
    * @auther: kid1999
    * @date: 2019/12/21 12:20
    **/
    @Slf4j
    @Controller
    @RequestMapping("/api/kaptcha")
    public class KaptchaController {
    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
    * 生成验证码
    * @throws Exception
    */
    @RequestMapping("/vrifyCode")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.info("生成验证码");
    HttpSession session = request.getSession();
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");
    // 获取KAPTCHA验证的随机文本
    String capText = defaultKaptcha.createText();
    // 将生成好的图片放入会话中
    session.setAttribute("vrifyCode", capText);
    // create the image with the text
    BufferedImage bi = defaultKaptcha.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(bi, "jpg", out);
    try {
    out.flush();
    } finally {
    out.close();//关闭
    }
    return null;
    }

    /**
    * 校对验证码
    * @return
    */
    public Result checkVerificationCode(String vrifyCode, HttpServletRequest request) {
    String verificationCodeIn = (String) request.getSession().getAttribute("vrifyCode");
    request.getSession().removeAttribute("vrifyCode");
    if (StringUtils.isEmpty(verificationCodeIn) || !verificationCodeIn.equals(vrifyCode)) {
    return Result.fail(400,"验证码错误,或已失效");
    }
    return Result.success("验证通过");
    }
    }

4.前端的配置

  • 此处以登录的验证码为例
1
2
3
4
5
6
7
8
<div class="form-group">
<div class="input-group" style="float: left;width: 195px;">
<label>验证码: </label>
<input type="text" name="code" id="code" class="form-control" style="width: 150px" maxlength="5" placeholder="验证码" autocomplete="off">&nbsp;
</div>
<img id="captcha-img" style="width: 120px;height: 40px;display: inline-block;float: right" src="/api/kaptcha/vrifyCode" onclick="this.src='/api/kaptcha/vrifyCode?d='+ new Date()*1" title="看不清?换一张" />
<div class="clearfix"></div>
</div>

5.核对

  • 在生成验证码图片的时候,已经将验证码写入session中了
  • 所以此时只需要从session中获取code验证回传的code即可
1
2
3
4
5
6
7
8
9
10
/** 验证码验证
*/
public Boolean checkVerificationCode(String vrifyCode, HttpServletRequest request) {
String verificationCodeIn = (String) request.getSession().getAttribute("vrifyCode");
request.getSession().removeAttribute("vrifyCode");
if (StringUtils.isEmpty(verificationCodeIn) || !verificationCodeIn.equals(vrifyCode)) {
return false;
}
return true;
}

效果如下: