Home > Database > Redis > How to use Springboot +redis+Kaptcha to implement the image verification code function

How to use Springboot +redis+Kaptcha to implement the image verification code function

WBOY
Release: 2023-05-27 15:05:47
forward
1094 people have browsed it

Background

  • Registration-Login-Change password generally requires sending a verification code, but it is easy to be attacked and maliciously called

  • What is SMS -Mailbox bomber

  • Mobile SMS bomber is a method of sending unlimited SMS registration verification codes for various websites to mobile phones in batches and cycles.

  • Loss caused by the company

  • One text message costs 5 cents. If it is swiped by a thief, everyone will calculate the email notification for free. Big theft, bandwidth, connections, etc. are all occupied, making it impossible to use normally.

  • How to prevent your website from becoming a "broiler" or being brushed

  • Add graphic verification code (developer)

  • Limit the number of single IP requests (developer)

  • Restrict number sending (generally provided by SMS Chamber of Commerce)

  • There are always offenses and defenses, but it only increases the cost of the attacker. If the ROI is not enough, it is natural to give up

Kaptcha Framework Introduction

A highly configurable and practical verification code generation tool open source by Google

  • Verification code font/size/color

  • Range of verification code content (numbers, letters, Chinese characters!)

  • Verification code picture size, border, border thickness, border color

  • The style of the verification code's interference line verification code (fisheye style, 3D, normal blur)

Add dependency

<!--kaptcha依赖包-->
<dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>kaptcha-spring-bootstarter</artifactId>
 <version>1.0.0</version>
 </dependency>
Copy after login

Configuration Class

/**
 * 图像验证码的配置文件
 * @author : look-word
 * @date : 2022-01-28 17:10
 **/
@Configuration
public class CaptchaConfig {
    /**
     * 验证码配置
     * Kaptcha配置类名
     *
     * @return
     */
    @Bean
    @Qualifier("captchaProducer")
    public DefaultKaptcha kaptcha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        //验证码个数
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        //字体间隔
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE,"8");
        //⼲扰线颜⾊

        //⼲扰实现类
        properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
        //图⽚样式
        properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL,
                "com.google.code.kaptcha.impl.WaterRipple");
        //⽂字来源
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789");
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}
Copy after login

Practical

My configuration class

Tool class for getting access to IP and generating MD5

public class CommonUtil {
    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String
    getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("xforwarded-for");
            if (ipAddress == null ||
                    ipAddress.length() == 0 ||
                    "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress =
                        request.getHeader("Proxy-Client-IP");
            }
                        request.getHeader("WL-Proxy-Client-IP");
                        request.getRemoteAddr();
                if
                (ipAddress.equals("127.0.0.1")) {
                    // 根据⽹卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet =
                                InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress =
                            inet.getHostAddress();
                }
            // 对于通过多个代理的情况,第⼀个IP为客户端真实IP,多个IP按照&#39;,&#39;分割
            if (ipAddress != null &&
                    ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0)
                {
                            ipAddress.substring(0, ipAddress.indexOf(","));
        } catch (Exception e) {
            ipAddress="";
        }
        return ipAddress;
    }
    public static String MD5(String data) {
            java.security.MessageDigest md =
                    MessageDigest.getInstance("MD5");
            byte[] array =
                    md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new
                    StringBuilder();
            for (byte item : array) {

                sb.append(Integer.toHexString((item & 0xFF) |
                        0x100).substring(1, 3));
            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        return null;
}
Copy after login

Interface development

@RestController
@RequestMapping("/api/v1/captcha")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    private Producer producer;
    @RequestMapping("get_captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        String captchaText = producer.createText();
        String key = getCaptchaKey(request);
        // 十分钟过期
        stringRedisTemplate.opsForValue().set(key,captchaText,10, TimeUnit.MINUTES);
        BufferedImage image = producer.createImage(captchaText);
        ServletOutputStream outputStream=null;
        try {
            outputStream= response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 生成redis验证码模块的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        // 请求头
        String userAgent=request.getHeader("user-Agent");
        String key="user_service:captcha:"+CommonUtil.MD5(ipAddr+userAgent);
        return key;
}
Copy after login

Configuration file

server:
  port: 8080
spring:
  redis:
    host: redis锁在的ip
    password: redis的密码
    port: 端口号
    lettuce:
      pool:
        # 连接池最⼤连接数(使⽤负值表示没有限制)
        max-idle: 10
        # 连接池中的最⼤空闲连接
        max-active: 10
        # 连接池中的最⼩空闲连接
        min-idle: 0
        # 连接池最⼤阻塞等待时间(使⽤负值表示没有限制)
        max-wait: -1ms
Copy after login

Result

How to use Springboot +redis+Kaptcha to implement the image verification code function

The above is the detailed content of How to use Springboot +redis+Kaptcha to implement the image verification code function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template