SpringBoot配置Kaptcha驗(yàn)證碼

SpringBoot配置Kaptcha驗(yàn)證碼

簡介

驗(yàn)證碼的作用其實(shí)就是通過人為操作來防止暴力破解、機(jī)器人等。

本文通過SprinBoot +Kaptcha實(shí)現(xiàn)圖片驗(yàn)證碼生成功能,驗(yàn)證碼的保存一般使用緩存,可以選擇使用Redis或者一些Java的緩存實(shí)現(xiàn)(例如,EhCache,guava cache等),如果分布式系統(tǒng)請使用Redis,這里簡單Demo使用EhCache實(shí)現(xiàn)驗(yàn)證碼緩存,具體實(shí)現(xiàn)如下:

Maven依賴

可以通過Spring Initializr實(shí)現(xiàn)初始化:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

啟動緩存

@Configuration
@EnableCaching
public class EhCacheConfiguration {}

配置驗(yàn)證碼圖片生成

@Configuration
public class KaptchaConfiguration {

    /**
     * 默認(rèn)生成圖形驗(yàn)證碼寬度
     */
    private static final String DEFAULT_IMAGE_WIDTH = "100";

    /**
     * 默認(rèn)生成圖像驗(yàn)證碼高度
     */
    private static final String DEFAULT_IMAGE_HEIGHT = "40";

    /**
     * 默認(rèn)生成圖形驗(yàn)證碼長度
     */
    private static final String DEFAULT_IMAGE_LENGTH = "4";

    /**
     * 顏色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
     */
    private static final String DEFAULT_COLOR_FONT = "black";

    /**
     * 圖片邊框
     */
    private static final String DEFAULT_IMAGE_BORDER = "no";

    /**
     * 默認(rèn)圖片間隔
     */
    private static final String DEFAULT_CHAR_SPACE = "5";

    /**
     * 驗(yàn)證碼文字大小
     */
    private static final String DEFAULT_IMAGE_FONT_SIZE = "30";

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put(Constants.KAPTCHA_BORDER, DEFAULT_IMAGE_BORDER);
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, DEFAULT_COLOR_FONT);
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE, DEFAULT_CHAR_SPACE);
        properties.put(Constants.KAPTCHA_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH);
        properties.put(Constants.KAPTCHA_IMAGE_HEIGHT, DEFAULT_IMAGE_HEIGHT);
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, DEFAULT_IMAGE_FONT_SIZE);
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, DEFAULT_IMAGE_LENGTH);
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

配置Ehcache

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="true"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="kaptcha"
            eternal="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="180"
            memoryStoreEvictionPolicy="LRU"/>

</ehcache>

SpringBoot application.properties 配置

spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:/ehcache.xml

測試

  • 啟動一個(gè)Controller
@Controller
@RequestMapping("/api/v1/kaptcha")
@Slf4j
public class KaptchaController {

    @Autowired
    private Producer producer;

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/code")
    public void generation(HttpServletResponse response) {

        String text = RandomStringUtils.randomAlphanumeric(4);

        log.info("生成驗(yàn)證碼:{}", text);

        BufferedImage image = producer.createImage(text);

        //緩存驗(yàn)證碼
        cacheManager.getCache("kaptcha").put(text, text);

        //set content type
        response.setContentType(MediaType.IMAGE_JPEG.getType());
        try {
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpeg", os);
            os.writeTo(response.getOutputStream());
        } catch (IOException e) {
            log.error("驗(yàn)證碼處理失?。簕}", e.getMessage(), e);
            throw new RuntimeException("驗(yàn)證碼獲取失敗", e);
        }

    }
}
  • 啟動工程
@SpringBootApplication
public class KaptchaDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(KaptchaDemoApplication.class, args);
    }
}

  • 運(yùn)行,瀏覽器訪問:http://localhost:8080/api/v1/kaptcha/code

總結(jié)

  • 使用圖片驗(yàn)證碼一般會設(shè)置過期時(shí)間
  • 大部分驗(yàn)證碼都是大小寫忽略(Demo中是大小寫敏感)
  • 分布式環(huán)境緩存需要統(tǒng)一,例如使用Redis
  • 結(jié)合Spring Security的時(shí)候記得把驗(yàn)證碼的URL權(quán)限放開
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容