SpringBoot implements simple login verification code

After referring to some information, I completed the function of this verification code. The following is a record of the implementation process of the function.

1. Effect drawing

2. Implementation principle

The verification code image is generated in the background and sent to the front desk.
The verification code content is saved in the session in the background.
After inputting the verification code at the front desk, it is sent to the backend, where the verification code saved in the session is taken out for verification.

3. Code

1. Create a config

I created a config named KaptchaConfig

code show as below:

Here, the background of the verification code is configured with or without borders, and the font color, and the verification code is generated.

package com.example.demo.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {
    @Value("${kaptcha.border}")
    private String border;

    @Value("${kaptcha.textproducer.font.color}")
    private String fontColor;

    // 其他配置项

    @Bean
    public DefaultKaptcha captchaProducer() {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        // 配置其他属性

        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}

The data in @value(${}) above is configured in application.yml

kaptcha:
  border: "no"
  textproducer:
    font:
      color: pink

2. Return the verification code to the front end

First import two classes in the controller

@Autowired
    private DefaultKaptcha captchaProducer;

    @Autowired
    private HttpServletRequest request;

Secondly, convert the verification code into Base64 encoding in the controller and return it to the front end.

This step has stored the generated verification code text in the session.

 
@GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();

        // 将验证码文本存储在Session中
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "jpg", baos);
        byte[] captchaBytes = baos.toByteArray();

// 将字节数组转换为Base64编码
        String base64Captcha = Base64.getEncoder().encodeToString(captchaBytes);

// 返回响应
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(base64Captcha);
        writer.flush();
    }

The front end needs to convert this Base64 encoding when receiving it.

const yzm = async () => {
  let ff = await yzmAPI();
  // 解码图片数据
  const decodedData = atob(ff.toString());

// 创建一个Uint8Array来存储解码后的二进制数据
  const arrayBuffer = new Uint8Array(decodedData.length);
  for (let i = 0; i < decodedData.length; i++) {
    arrayBuffer[i] = decodedData.charCodeAt(i);
  }

// 创建一个Blob对象
  const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });

// 创建一个URL对象
  const imageUrl = URL.createObjectURL(blob);
  imgs.value = imageUrl;
}

Finally, in the login process, you can compare the verification code passed by the front end with the stored verification code.

 HttpSession session = request.getSession();
        String captcha = (String) session.getAttribute("captcha");
        if (!captcha.toString().equals(inputCaptcha.toString())) {
           //写自己的处理方式
        }

The above completes the verification code login

Guess you like

Origin blog.csdn.net/m0_55333789/article/details/132580622