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

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>

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;
    }
}

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;
}

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;
}

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

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor