SpringBoot整合kaptcha生成验证码

再web开发中,登录页通常需要进行辅助验证,通常的验证方法有短信验证、验证码验证、拼图验证等。本文记录了验证码验证的验证码生成过程。

验证码生成的方式有多种,比较呆板的方式就是在前端生成,不过这种方式实在太麻烦,后来接触到了kaptcha,感觉是真的很简单。

kaptcha生成验证码在后端运行,下面直接上代码:

项目结构:

pom文件引入必要依赖(lombok为非必要依赖,只是习惯使用了):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hongke.security</groupId>
    <artifactId>securityApplication</artifactId>
    <version>1.0</version>
    <description>this is spring security demo</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.report.outputEncoding>UTF-8</project.report.outputEncoding>
        <java.version>1.8</java.version>
        <kaptcha.version>0.0.9</kaptcha.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.12.RELEASE</version>
    </parent>

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

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>${kaptcha.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

kaptcha配置类:

package com.hongke.security.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 chengjunyu
 * @classname KaptchaConfig
 * @description 验证码配置
 * @date 2020/7/21 15:16
 */
@Configuration
public class KaptchaConfig {

    /**
     * @description 获取一个验证码
     * @author chengjunyu
     * @date 2020/7/21 15:50
     * @param
     * @return com.google.code.kaptcha.impl.DefaultKaptcha
     **/
    @Bean
    public DefaultKaptcha  getDefalutKaptcha() {
        Properties properties = new Properties();
        //不带边框
        properties.put("kaptcha.border", "no");
        //字符颜色
        properties.put("kaptcha.textproducer.font.color", "black");
        //字符间距
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

LoginController控制器:

package com.hongke.security.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * @author chengjunyu
 * @classname LoginController
 * @description 登录相关controller层
 * @date 2020/7/21 15:52
 */
@RestController
@Slf4j
@RequestMapping("/login")
public class LoginController {

    @Resource
    private Producer producer;

    @GetMapping("/getCode")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //这里的text即为kaptcha生成的验证码中的文字,生成后放入session中,客户端请求登录时再取出进行比对
        String text = producer.createText();
        log.info("生成验证码:{}", text);
        request.getSession().setAttribute("code", text);
        BufferedImage image = producer.createImage(text);
        OutputStream os =  response.getOutputStream();
        ImageIO.write(image, "jpg", os);
        IOUtils.closeQuietly(os);

    }

    @GetMapping("/in")
    public String login(String code, HttpServletRequest request) {
        String text = request.getSession().getAttribute("code").toString();
        if(code == null || code == "") {
            return "验证码不能为空";
        }
        if(text.toLowerCase().equals(code.toLowerCase())) {
            return "验证码校验通过";
        }
        return "验证码校验不通过";
    }
}

application.yml:

server:
  port: 8001

启动类:

package com.hongke.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author chengjunyu
 * @classname SecurityApplication
 * @description 启动类
 * @date 2020/7/21 15:14
 */
@SpringBootApplication
public class SecurityApplication {

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

Postman测试结果:

验证码正确时:

验证码为空时:

验证码错误时:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中整合Kaptcha,你可以按照以下步骤进行操作: 步骤1:添加Kaptcha依赖 在你的Spring Boot项目的pom.xml文件中,添加Kaptcha的依赖: ```xml <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 步骤2:配置Kaptcha 在application.properties(或application.yml)文件中,添加以下配置: ```properties # Kaptcha Configurations kaptcha.border = no kaptcha.border.color = black kaptcha.textproducer.font.color = black kaptcha.image.width = 150 kaptcha.image.height = 50 kaptcha.textproducer.char.string = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 kaptcha.textproducer.char.length = 4 kaptcha.noise.impl = com.google.code.kaptcha.impl.NoNoise kaptcha.background.clear.from = white kaptcha.background.clear.to = white kaptcha.textproducer.font.size = 40 ``` 步骤3:创建验证码接口 在你的控制器中创建一个用于生成验证码图片的接口,例如: ```java @RestController public class CaptchaController { @GetMapping("/captcha") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) { // 创建DefaultKaptcha对象并配置参数 DefaultKaptcha kaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "no"); properties.setProperty("kaptcha.textproducer.font.color", "black"); kaptcha.setConfig(new Config(properties)); // 生成验证码文本 String text = kaptcha.createText(); // 将验证码文本保存到session中 request.getSession().setAttribute("captcha", text); // 创建验证码图片并输出到response中 BufferedImage image = kaptcha.createImage(text); try { OutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); } catch (IOException e) { e.printStackTrace();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值