preface

Google’s Kaptcha framework is a highly configurable utility for generating captchas.

Kaptcha is a captcha library that extends Simplecaptcha and is a very useful captcha generation tool for Java programming. We can use this tool to generate various styles of captchas because it is configurable and can be customized to our needs


Import the Kaptcha dependency package

<! -- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
 <dependency>
     <groupId>com.github.penggle</groupId>
     <artifactId>kaptcha</artifactId>
     <version>2.32.</version>
 </dependency>
Copy the code

Two, the use of steps

1. Verification code configuration classes

/ * * *@description: KaptCHA verification code configuration class *@author: DT
 * @date: 2021/5/19 "*@version: v1.0 * /
@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha defaultKaptcha(a) {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        / / font
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Song Style, Regular script, Microsoft Yahei");
        properties.setProperty(Constants.KAPTCHA_BORDER, "no");

        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        returndefaultKaptcha; }}Copy the code

2. Obtain the verification code interface

/ * * *@description: Log in to the controller *@author: DT
 * @date: 2021/5/19 makest *@version: v1.0 * /
@RestController
@RequestMapping("/api")
@CrossOrigin  // Resolve cross-domain
public class LoginController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/verification")
    public void createImageCode(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control"."no-store, no-cache");
        response.setContentType("image/jpeg");
        // Generate a literal captcha
        String text = defaultKaptcha.createText();
        // Generate image captcha
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out); out.flush(); out.close(); }}Copy the code

3. Vue page

<el-form ref="loginForm" class="dt_form" label-position="left" label-width="0px">
     <el-form-item prop="username">
         <el-input v-model="userForm.password" placeholder="Please enter your account number" auto-complete="off" prefix-icon="el-icon-user">
         </el-input>
     </el-form-item>
     <el-form-item prop="password">
         <el-input type="password" v-model="userForm.password" placeholder="Please enter your password" auto-complete="off" prefix-icon="el-icon-lock">
         </el-input>
     </el-form-item>
     <el-form-item prop="code">
         <el-col :span="12">
             <el-input v-model="userForm.code" placeholder="Verification code" auto-complete="off" prefix-icon="el-icon-refresh"></el-input>
         </el-col>
         <el-col :span="12">
             <! -- Load captcha -->
             <img width="160px" onclick="this.src='http://localhost:8081/api/verification? d='+new Date()*1" src="http://localhost:8081/api/verification" alt="Verification code"/>
         </el-col>
     </el-form-item>
     <el-form-item>
         <el-button type="button" class="dt_button">Login system</el-button>
     </el-form-item>
 </el-form>
Copy the code

4. Remove the background

As you can see, this is the default background, which is ugly. Let’s get rid of the background now:

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha defaultKaptcha(a) {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // Whether the verification code has the border No
        properties.setProperty("kaptcha.border"."no");
        // Captcha font color
        properties.setProperty("kaptcha.textproducer.font.color"."blue");
        // The overall width of the verification code
        properties.setProperty("kaptcha.image.width"."300");
        // The overall height of the verification code
        properties.setProperty("kaptcha.image.height"."75");
        // Number of characters
        properties.setProperty("kaptcha.textproducer.char.length"."4");
        // Text size
        properties.setProperty("kaptcha.textproducer.font.size"."50");
        // Text random font
        properties.setProperty("kaptcha.textproducer.font.names"."Song Style, Regular script, Microsoft Yahei");
        // Text distance
        properties.setProperty("kaptcha.textproducer.char.space"."16");
        // Interference line color
        properties.setProperty("kaptcha.noise.color"."blue");
        // Custom captcha background
        properties.setProperty("kaptcha.background.impl"."com.dt.springbootdemo.config.kaptcha.NoKaptchaBackhround");
        Config config=new Config(properties);
        defaultKaptcha.setConfig(config);
        returndefaultKaptcha; }}Copy the code

Remove style background class:

/ * * *@description: Removes the background color * of the verification code@author: DT
 * @date: 2021/5/19 22:54
 * @version: v1.0 * /
public class NoKaptchaBackhround extends Configurable implements BackgroundProducer {

    public NoKaptchaBackhround(a){}@Override
    public BufferedImage addBackground(BufferedImage bufferedImage) {
        int width = 400;
        int height = 125;
        BufferedImage imageWithBackground = new BufferedImage(width, height, 1);
        Graphics2D graph = (Graphics2D)imageWithBackground.getGraphics();
        graph.fill(new Rectangle2D.Double(0.0 D.0.0 D, (double)width, (double)height));
        graph.drawImage(bufferedImage, 0.0.null);
        returnimageWithBackground; }}Copy the code

5, custom background and captcha random rules

@Bean
public DefaultKaptcha defaultKaptcha(a) {
    DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
    Properties properties = new Properties();
    // Image border
    properties.setProperty("kaptcha.border"."yes");
    // Border color
    properties.setProperty("kaptcha.border.color"."105179, living");
    // Font color
    properties.setProperty("kaptcha.textproducer.font.color"."red");
    // The overall width of the verification code
    properties.setProperty("kaptcha.image.width"."300");
    // The overall height of the verification code
    properties.setProperty("kaptcha.image.height"."75");
    // Number of characters
    properties.setProperty("kaptcha.textproducer.char.length"."4");
    // Text size
    properties.setProperty("kaptcha.textproducer.font.size"."50");
    // Text random font
    properties.setProperty("kaptcha.textproducer.font.names"."Song Style, Regular script, Microsoft Yahei");
    // Text distance
    properties.setProperty("kaptcha.textproducer.char.space"."16");
    // Interference line color
    properties.setProperty("kaptcha.noise.color"."blue");
    // Custom captcha background
    //properties.setProperty("kaptcha.background.impl","com.dt.springbootdemo.config.kaptcha.NoKaptchaBackhround");
    Config config=new Config(properties);
    defaultKaptcha.setConfig(config);
    return defaultKaptcha;
}
Copy the code

Captcha rule tool class:

/ * * *@description: captcha Util class *@author: DT
 * @date: * 2021/5/19 brake@version: v1.0 * /
public class VerifyCodeUtils {

    /** ** width and height can be passed as arguments */
    private static final int WIDTH = 300;
    private static final int HEIGHT = 75;

    /** * Pass in the BufferedImage object and save the generated verification code to BufferedImage *@param bufferedImage
     * @return* /
    public static String drawRandomText(BufferedImage bufferedImage) {
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        // Set the brush color - captcha background color
        graphics.setColor(Color.WHITE);
        // Fill the background
        graphics.fillRect(0.0, WIDTH, HEIGHT);
        graphics.setFont(new Font("Song Style, Regular script, Microsoft Yahei", Font.BOLD, 40));

        // A combination of numbers and letters
        String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

        StringBuilder builder = new StringBuilder();
        // Rotate the x coordinate of the origin
        int x = 10;
        String ch;
        Random random = new Random();

        for (int i = 0; i < 4; i++) {
            graphics.setColor(getRandomColor());

            // Set the font rotation Angle to less than 30 degrees
            int degree = random.nextInt() % 30;
            int dot = random.nextInt(baseNumLetter.length());

            ch = baseNumLetter.charAt(dot) + "";
            builder.append(ch);

            // Forward rotation
            graphics.rotate(degree * Math.PI / 180, x, 45);
            graphics.drawString(ch, x, 45);

            // Reverse rotation
            graphics.rotate(-degree * Math.PI / 180, x, 45);
            x += 48;
        }

        // Draw interference lines
        for (int i = 0; i < 6; i++) {
            // Set a random color
            graphics.setColor(getRandomColor());

            // Draw random lines
            graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
                    random.nextInt(WIDTH), random.nextInt(HEIGHT));

        }

        // Add noise
        for (int i = 0; i < 30; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);

            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2.2);
        }
        return builder.toString();
    }

    /** ** random color */
    private static Color getRandomColor(a) {
        Random ran = new Random();
        return new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256)); }}Copy the code

Interface implementation:

@GetMapping("/verification")
public void createImageCode(HttpServletResponse response) throws IOException {
    // Disable caching
    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");
    // Set the response format to PNG image
    response.setContentType("image/png");
    // Generate image captcha
    BufferedImage image = new BufferedImage(300.75, BufferedImage.TYPE_INT_RGB);
    String randomText = VerifyCodeUtils.drawRandomText(image);
    System.out.println("Verification code ->>>"+randomText);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "png", out); out.flush(); out.close(); }}Copy the code

Testing: At this time to get the verification code, we can save in Redis, next we will realize how to save in Redis, and how to verify.

conclusion

This post refers to some major articles and makes some changes, but is interested in the verification code, and how to check and join Redis cache to set the expiration time is the focus, the next post we will talk about our implementation.