This is the 18th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

First, why use captcha

CAPTCHA stands for “Completely Automated Public Turing Test to tell Computers and Humans Apart.” It is a public automatic program that distinguishes between a computer and a human user. Can prevent: malicious crack password, brush ticket, forum flooding, effectively prevent a hacker to a specific registered user with a specific program to crack the way to continue to try to land, in fact, with verification code is now a lot of websites popular way, we use a relatively simple way to achieve this function. Kaptcha is Google’s open source utility class. This article uses a jar package packaged by a third party. Because it is a separate project from the front and back end, the verification code cannot be stored in the session scope. This article also needs to store the verification code in the database for login verification.

Second, the use of

1. Reference maven coordinate dependencies

<dependency> <groupId>com.github. Axet </groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency>Copy the code

2. Verification code database table implementation

CREATE TABLE `sys_captcha` (
  `uuid` char(36) NOT NULL COMMENT 'uuid',
  `code` varchar(6) NOT NULL COMMENT 'Captcha',
  `expire_time` datetime DEFAULT NULL COMMENT 'Expiration time'.PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='System Verification Code';
Copy the code

3. Generate and verify the core code code

The service layer

    // Inject the beans generated by the captcha
    @Autowired
    private Producer producer;
    /** * Verification code generated *@param uuid
     * @return* /
    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("Uuid cannot be empty");
        }
        //1. Generate a text verification code
        String code = producer.createText();

        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //2. Set the expiration time to 5 minutes
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        this.save(captchaEntity);

        return producer.createImage(code);
    }

    /** * Verification code *@param uuid uuid
     * @paramCode Indicates the verification code *@return* /
    @Override
    public boolean validate(String uuid, String code) {
        SysCaptchaEntity captchaEntity = this.getOne(new QueryWrapper<SysCaptchaEntity>().eq("uuid", uuid));
        if(captchaEntity == null) {return false;
        }

        // Delete the verification code, regardless of whether the verification is successful or not, the verification code is invalid, the verification code is one-time, so it can be deleted to reduce garbage data
        this.removeById(uuid);

        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }
Copy the code

The Controller layer

	/** * Verification code */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control"."no-store, no-cache");
		response.setContentType("image/jpeg");
		// Get the image verification code
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}
Copy the code

Specific code can refer to: ==github.com/Dr-Water/ra…

4. Use ideas

  1. Each time the front end requests a new verification code, it carries a DIFFERENT UUID
  2. The backend uses this UUID as the unique identifier of the captcha to generate a captcha in the database and return the captcha image to the front-end
  3. When the front-end performs login authentication, it sends the UUID generated by the verification code to the back-end, which queries the database according to the UUID and verifies whether the verification code is correct

Some excellent reference links

www.jianshu.com/p/a3525990c… Javaweb- Google kaptcha image captcha integration using springboot