SpringBoot 中使用 Kaptcha 验证码生成器

  • Kaptcha 介绍

验证码(CAPTCHA):是 Completely Automated Public Turing test to tell Computers and Humans Apart(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。

作用:可以防止 恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能。

这个问题可以由计算机生成并评判,但是必须只有人类才能解答。由于计算机无法解答 CAPTCHA 的问题,所以回答出问题的用户就可以被认为是人类。

Kaptcha 是谷歌放在 github 上的一个验证码 jar 包,是一个基于 SimpleCaptcha 的验证码开源项目,我们可以简单配置属性就可以实现验证码的验证功能。

kaptcha 官网地址:https://www.mvnjar.com/com.github.penggle/kaptcha/2.3.2/detail.html

  • 在 SpringBoot 中使用 Kaptcha 步骤

1、可以到官网下载 kaptcha 的 jar 包,或者在 pom.xml 中配置 maven 依赖 



   com.github.penggle
   kaptcha
   2.3.2

 2、添加 kaptcha 的图片配置,创建 bean 并注册(springboot 有两种注册方式,xml 配置和 java 代码注解配置)

2.1、java 代码注解配置(推荐使用),创建一个配置类,代码如下:

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;

/**
 * kaptcha验证码生成器配置
 * @author lwf
 * @date 2019/8/21 16:10
 */
@Configuration
public class KaptchaConfig {

    /**
     * 配置生成图片的bean
     * @return
     */
    @Bean(name = "kaptchaProducer")
    public DefaultKaptcha getKaptchaBean() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        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);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

2.2、xml 配置,在 resources 下创建 kaptchaConfig.xml 文件



    
    
        
            
                
                    
                        no
                        black
                        4
                        4
                        123456789
                    
                
            
        
    

 然后在启动类Application中加载 kaptchaConfig.xml 配置

@SpringBootApplication
@ImportResource(locations = {"classpath:kaptchaConfig.xml"})
public class ManageResourcesApplication {
   public static void main(String[] args) {
      SpringApplication.run(ManageResourcesApplication.class, args);
   }
}

3、创建 Controller 并注入 bean,添加请求方法调用 bean 返回图片

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.manage.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 * @author lwf
 * @date 2019/8/21 13:51
 */
@Controller
public class SysLoginController {

    @Autowired
    private Producer kaptchaProducer;

    /**
     * 获取图形验证码
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        
        //生成文字验证码
        String text = kaptchaProducer.createText();
        //生成图片验证码
        BufferedImage image = kaptchaProducer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

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

}

 4、前端页面请求得到验证码图片并显示(使用 vue.js)

html 页面代码:

如果看不清楚,请单击图片刷新!

点击刷新验证码 js 代码: 

refreshCode: function () {
    this.src = "captcha.jpg?t=" + $.now();
}

 5、验证输入的验证码是否正确

@ResponseBody
@RequestMapping(value = "/login", method = RequestMethod.POST)
public R login(String captcha) {
    try {
        String kaptcha = ShiroUtils.getSessionAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
        ShiroUtils.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return R.error("验证码不正确");
        }
    } catch (Exception e) {
        return R.error("验证码已失效");
    }
    //处理登录逻辑
}
  • Kaptcha 参数设置说明

Constant

描述

默认值

合法值

kaptcha.border

图片边框

yes

yes , no

kaptcha.border.color

边框颜色

black

 r,g,b (and optional alpha)

或者 white,black,blue.

kaptcha.border.thickness

边框厚度

1

>0

kaptcha.image.width

图片宽

200

 

kaptcha.image.height

图片高

50

 

kaptcha.producer.impl

图片实现类

com.google.code.kaptcha

.impl.DefaultKaptcha

 

kaptcha.textproducer.impl

文本实现类

com.google.code.kaptcha.text

.impl.DefaultTextCreator

 

kaptcha.textproducer.char.string

文本集合,验证码值从此集合中获取

abcde2345678gfynmnpwx

 

kaptcha.textproducer.char.length

验证码长度

5

 

kaptcha.textproducer.font.names

字体

Arial, Courier

 

kaptcha.textproducer.font.size

字体大小

40px

 

kaptcha.textproducer.font.color

字体颜色

black

 r,g,b  

或者 white,black,blue.

kaptcha.textproducer.char.space

文字间隔

2

 

kaptcha.noise.impl

干扰实现类

com.google.code.kaptcha

.impl.DefaultNoise

 

kaptcha.noise.color

干扰颜色

black

 r,g,b

或者 white,black,blue.

kaptcha.obscurificator.impl

图片样式

com.google.code.kaptcha

.impl.WaterRipple

水纹 com.google.code.kaptcha

.impl.WaterRipple

鱼眼 com.google.code.kaptcha

.impl.FishEyeGimpy

阴影 com.google.code.kaptcha

.impl.ShadowGimpy

kaptcha.background.impl

背景实现类

com.google.code.kaptcha

.impl.DefaultBackground

 

kaptcha.background.clear.from

背景颜色渐变,开始颜色

light grey

 

kaptcha.background.clear.to

背景颜色渐变,结束颜色

 

white

 

kaptcha.word.impl

文字渲染器

com.google.code.kaptcha.text

.impl.DefaultWordRenderer

 

kaptcha.session.key

session key

KAPTCHA_SESSION_KEY

 

kaptcha.session.date

session date

KAPTCHA_SESSION_DATE

 

你可能感兴趣的:(Java,后端)