验证码功能的思路和做法

验证码登录的思路和流程

验证码功能的思路和做法_第1张图片

步骤

1.导入依赖


    com.github.axet
    kaptcha
    0.0.9

2.写一个验证码的配置类

package com.lzy.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
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;

@Configuration
public class KaptchaConfig {
   @Bean
   public DefaultKaptcha producer() {
      //验证码长宽高
      Properties properties = new Properties();
      properties.put("kaptcha.border", "no");
      properties.put("kaptcha.textproducer.font.color", "black");
      properties.put("kaptcha.textproducer.char.space", "4");
      properties.put("kaptcha.image.height", "40");
      properties.put("kaptcha.image.width", "120");
      properties.put("kaptcha.textproducer.font.size", "30");
      Config config = new Config(properties);
      DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
      defaultKaptcha.setConfig(config);
      return defaultKaptcha;
   }
}

3.使用这个类,创建一个uuid作为key,并得到一个随机验证码,再将验证码转化为图片,再转化为base64进制,并且按上对应的前缀

package com.lzy.controller;

import cn.hutool.json.JSONObject;
import com.lzy.common.lang.Result;
import com.lzy.util.Constants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

@RestController
public class CaptureController extends BaseController {

    @GetMapping("/captcha")
    public Result captcha() {
        // 生成uuid作为验证码的唯一标识
        UUID uuid = UUID.randomUUID();
        // 生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        String base64Image = convertImageToBase64(image);
        // 将验证码存入redis
        redisUtil.hset(Constants.CAPTURE , uuid.toString(), text, 120);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("token", uuid.toString());
        jsonObject.set("captchaImg", base64Image);
        return Result.success(jsonObject);
    }
    private String convertImageToBase64(BufferedImage image) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            return "data:image/png;base64," + base64Image;
        } catch (IOException e) {
            throw new RuntimeException("Error converting image to Base64", e);
        }
    }
}

你可能感兴趣的:(kaptcha,从0开始做一个前后端分离项目,java,java,后端,kaptcha)