Using graphic verification code Kaptcha in Java Web project

Keywords: Java Redis Google Session

1, Verification code introduction

The main way of generation:

1. Use Java Native mode, including the use of Servlet, AWT and ImageIO;

2. Use open source libraries, such as Jcaptcha, Kaptcha;

(open source library of each graphic verification code: http://www.oschina.net/project/tag/248/captcha?lang=19)

In addition, the generated code can be saved in Session or Cookie, or in cache (for example, Redis);

When it needs to be verified, it needs to take it out of Session or cache and verify it with the requested verification code;

2, Use verification code in project

In this project, the open source library of Google - Kaptcha is used; note: Spring MVC is used in this project;

1. Introduce Maven

<dependency>
    <groupId>com.google.code</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

2.Spring configuration Bean

For more Kaptcha configurations, please move to the bottom information;

    <!--Graphic verification code-->
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <value>
                        kaptcha.border=yes
                    </value>
                </constructor-arg>
            </bean>
        </property>
    </bean>

3. Code implementation in controller

@RestController
@RequestMapping(value = "/verify", name = "Picture verification code")
public class ValidateCoderController {

    private Logger logger = LoggerFactory.getLogger(ValidateCoderController.class);

    @Autowired
    private Producer captchaProducer;

    @RequestMapping(value = "/code", method = RequestMethod.GET, name = "Picture verification code")
    public void code(HttpServletResponse response,
                     @RequestParam(value = "mobilePhone", required = true) String mobilePhone,
                     @RequestParam(value = "captchaType", required = true) Integer captchaType) {
        if (!StrUtils.isPhoneNumber(mobilePhone)) {
            return;
        }
        CaptchaType type = getCaptchaTypeByCode(captchaType);
        if (isTooOften(mobilePhone, type.getValue())) {
            logger.info("number{}Obtain{}Frequent picture verification codes", mobilePhone, type.getBundleKey());
            return;
        }

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        try (ServletOutputStream out = response.getOutputStream()) {
            String capText = captchaProducer.createText().substring(0, 4);
            BufferedImage bi = captchaProducer.createImage(capText);
            ImageIO.write(bi, "jpg", out);
            //Set verification code
            RedisConnector.save(mobilePhone, capText, type.getValue());
            
            /*The mobile terminal needs to return after base64 processing, and then the Headers of the response do not need to be configured;
              ByteArrayOutputStream is required here
            BASE64Encoder encoder = new BASE64Encoder();
            String base64String = encoder.encode(out.toByteArray());
            */
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("number{}Obtain{}Picture verification code failed", mobilePhone, type.getBundleKey());
        }
    }

    private boolean isTooOften(String mobilePhone, String loginPre) {
        String key = KeyUtils.getLimitKey(mobilePhone, loginPre);
        if (RedisConnector.exists(key)) {
            String countStr = RedisConnector.getData(key);
            int count = Integer.parseInt(countStr);
            if (count >= 30) {
                return true;
            }
        }
        return false;
    }
}

4. Verification code verification

Take the verification from Redis where you need to use it. Here you need to pay attention to:

1) the generation tool class KeysUtils of Redis's Keys;

2) tools for Redis operation and effective time of Code;

3) if the verification code is successful, it needs to be invalidated;

 

Java native mode:

http://tedhacker.top/2016/11/07/Java%E7%94%9F%E6%88%90%E9%AA%8C%E8%AF%81%E7%A0%81%E7%AE%80%E8%AE%B0/

https://www.jianshu.com/p/05409731abb8

Using Kaptcha:

https://www.jianshu.com/p/3a695783c5c1

http://blog.csdn.net/rambo_china/article/details/7720181

Posted by gin on Thu, 02 Apr 2020 10:26:13 -0700