第一种

在这里插入图片描述
maven

		<properties>
		<whvcse.version>1.6.2</whvcse.version>
		</properties>
		<dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>${whvcse.version}</version>
        </dependency>

获取验证码

	@AnonymousAccess
    @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    public Result<Object> getCode() {
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算,默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue() + "";
        } catch (Exception e) {
            result = captcha.text();
        }
        //自定义redis Key  常量字符串+UUID
        String uuid = properties.getCodeKey() +":"+ IdUtil.simpleUUID();
        // 保存验证码运算结果到redis
        redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResultBuilder.success(imgResult);
    }

登录验证验证码

		// 查询验证码
        String code = (String) redisUtils.get(authUser.getUuid());
        // 清除验证码
        redisUtils.del(authUser.getUuid());
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("验证码错误");
        }

第二种:

实现验证码登录
在这里插入图片描述

1.获取验证码图片接口

controller

	@GetMapping("/kaptcha")
    public MessageBean defaultKaptcha() {
        return sysAuthenticationService.defaultKaptcha();
    }

service

public MessageBean defaultKaptcha() {
        MessageBean result = new MessageBean();
        VerificationCodeDO verificationCodeDO = new VerificationCodeDO();
        try {
            //设置长宽
            VerifyCode verifyCode = VerifyCodeUtils.generate(80, 28);
            String code = verifyCode.getCode();
            String id = UUID.randomUUID().toString();
            //将生成的唯一id和验证码存到redis并设置到期时间
            redisUtil.set(id, code, 300);
            verificationCodeDO.setId(id);
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(verifyCode.getImgBytes());
            verificationCodeDO.setValue(encode);
            result.setData(verificationCodeDO);
        } catch (IllegalArgumentException e) {
            logger.error(ErrorInfoUtil.getErrorInfo(e));
        }
        return result;
    }

entity

import lombok.Data;

@Data
public class VerificationCodeDO {
    private String id;

    private String value;
}
import lombok.Data;

@Data
public class VerifyCode {
    private String code;

    private byte[] imgBytes;

    private long expireTime;
}

VerifyCodeUtils

import com.guangyi.project.model.system.VerifyCode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class VerifyCodeUtils {

    private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };

    private static final int VALICATE_CODE_LENGTH = 4;

    /**
     * 设置背景颜色及大小,干扰线
     *
     * @param graphics
     * @param width
     * @param height
     */
    private static void fillBackground(Graphics graphics, int width, int height) {
        // 填充背景
        graphics.setColor(Color.WHITE);
        //设置矩形坐标x y 为0
        graphics.fillRect(0, 0, width, height);

        // 加入干扰线条
        for (int i = 0; i < 8; i++) {
            //设置随机颜色算法参数
            graphics.setColor(RandomUtils.randomColor(40, 150));
            Random random = new Random();
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            graphics.drawLine(x, y, x1, y1);
        }
    }

    /**
     * 生成随机字符
     *
     * @param width
     * @param height
     * @param os
     * @return
     * @throws IOException
     */
    public static String generate(int width, int height, OutputStream os) throws IOException {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        fillBackground(graphics, width, height);
        String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
        createCharacter(graphics, randomStr);
        graphics.dispose();
        //设置JPEG格式
        ImageIO.write(image, "JPEG", os);
        return randomStr;
    }
    /**
     * 验证码生成
     *
     * @param width
     * @param height
     * @return
     */
    public static VerifyCode generate(int width, int height) {
        VerifyCode verifyCode = null;
        try (
            //将流的初始化放到这里就不需要手动关闭流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ) {
            String code = generate(width, height, baos);
            verifyCode = new VerifyCode();
            verifyCode.setCode(code);
            verifyCode.setImgBytes(baos.toByteArray());
        } catch (IOException e) {
            e.getMessage();
            verifyCode = null;
        }
        return verifyCode;
    }

    /**
     * 设置字符颜色大小
     *
     * @param g
     * @param randomStr
     */
    private static void createCharacter(Graphics g, String randomStr) {
        char[] charArray = randomStr.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            //设置RGB颜色算法参数
            g.setColor(new Color(50 + RandomUtils.nextInt(100),
                    50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
            //设置字体大小,类型
            g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
            //设置x y 坐标
            g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
        }
    }

}

RandomUtils

import java.awt.*;
import java.util.Random;

public class RandomUtils extends org.apache.commons.lang3.RandomUtils {

    private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

    private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

    private static Random random = new Random();

    public static String randomString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
        }
        return sb.toString();
    }

    public static String randomNumberString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
        }
        return sb.toString();
    }

    public static Color randomColor(int fc, int bc) {
        int f = fc;
        int b = bc;
        Random random = new Random();
        if (f > 255) {
            f = 255;
        }
        if (b > 255) {
            b = 255;
        }
        return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
    }

    public static int nextInt(int bound) {
        return random.nextInt(bound);
    }
}

2.在登录的时候验证验证码

		if (StringUtils.isEmpty(model.getValue()) && StringUtils.isEmpty(model.getCodeId())){
            throw new BDException("验证码参数不能为空");
        }
        //用前端传过来的唯一id在redis中查value(如果查出来的验证码和用户输入的验证码一致则验证通过)
        String value = redisUtil.get(model.getCodeId()).toString();
        //区分验证码大小写用equals不区分大小写用equalsIgnoreCase
        boolean equals = model.getValue().equalsIgnoreCase(value);
        if (StringUtils.isEmpty(value) || !equals){
            throw new BDException("验证码不正确");
        }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐