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 依賴 

<!--驗證碼生成工具-->
<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
</dependency>

 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 文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- Kaptcha驗證碼生成器 -->
    <bean name="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <prop key="kaptcha.border">no</prop>
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <prop key="kaptcha.textproducer.char.space">4</prop>
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <prop key="kaptcha.textproducer.char.string">123456789</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

 然後在啓動類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 頁面代碼:

<img style="height: 32px;width: 96px;border-radius: 4px;" 
    alt="如果看不清楚,請單擊圖片刷新!" title="點擊刷新"
     class="pointer" :src="src" @click="refreshCode">

點擊刷新驗證碼 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

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章