The understanding of verification code in java: the integration of springboot and kaptch

Background

1. In recent projects, we need to replace the verification code with kaptch and springboot, which is also convenient to operate. We have made many detours, and specially wrote down this method for your reference. Let's explain it next.

II. Project structure

III. detailed configuration

1.pom.xml

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

2.config

2.1.KaptchaConfig.java

@Component
public class KaptchaConfig {
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "no");
        properties.setProperty("kaptcha.border.color", "blue");
        properties.setProperty("kaptcha.textproducer.font.color", "black");
        properties.setProperty("kaptcha.image.width", "160");
        properties.setProperty("kaptcha.image.height", "50");
        properties.setProperty("kaptcha.textproducer.font.size", "40");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.noise.color", "white");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "Song style,Regular script,Microsoft YaHei");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

3.controller

3.1. Interface for generating verification code (CreateCode.java)

@Controller
@RequestMapping(value = "/createCode")
public class CreateCode {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping(value="/testdemo", method= RequestMethod.GET)
    public void createCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //Production verification code string and save to session
            String createText = defaultKaptcha.createText();
            //Given a unique ID to prevent reuse of verification code
            httpServletRequest.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, createText);
            //redisCache.set(RedisCache.prefix, coldFlag, createText);
            //Returns a BufferedImage object using the produced captcha string and writes it to the byte array as byte
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //Define the response output type as image/jpeg, and use the response output stream to output the byte array of pictures.
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}

3.2. Generate verification code through postman test

3.3. Pre check controller

@Controller
@RequestMapping(value = "/preCheckCode")
@Slf4j
public class PreCheckController {
    //Verification code verification
    @PostMapping("/checkCode")
    @ResponseBody
    public String imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,@RequestBody JSONObject data){
        String captchaId = (String) httpServletRequest.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String code = data.getString("code");
        log.info("Session  vrifyCode ---->"+captchaId+"---- form code --->"+code);
        if (!captchaId.equals(code)) {
            log.info("Bad verification code");
            return "fail";
        } else {
            return "success";
        }
    }
}

3.4. Simulated front end postman test

IV. check the backend log

1. The logs entered by the front end are consistent with those saved in the session.

Five, summary

1. This completes the generation and verification of the verification code, hoping to help you, encourage!

Keywords: Session Google Java SpringBoot

Added by tvance929 on Sat, 26 Oct 2019 20:58:29 +0300