Captcha Implementation
Captcha Implementation in Spring boot.
Join the DZone community and get the full member experience.
Join For FreeCAPTCHA helps protect you from spam and password decryption by asking you to complete a simple test that proves you are human and not a computer trying to break into a password-protected account.
We can implement a captcha in Spring boot where a user can get an encoded image, and the corresponding readable captcha can be stored in the Database.
We can add simplecaptcha
in the pom file to include inside the dependencies.
<dependency>
<groupId>cn.apiclub.tool</groupId>
<artifactId>simplecaptcha</artifactId>
<!-- we have to manage version here -->
<version>1.2.2</version>
</dependency>
We can create the captcha by providing the height and width for the same and inside the create captcha we can add the text, background-color, and gimp as well like FishEyeGimpyRenderer
Captcha captcha = createCaptcha(240, 70);
String readableImage = encodeCaptcha(captcha);
public static Captcha createCaptcha(Integer width, Integer height) {
return new Captcha.Builder(width, height).addBackground(new GradiatedBackgroundProducer())
.addText(new DefaultTextProducer(6, DEFAULT_CHARS), new DefaultWordRenderer()).gimp(new FishEyeGimpyRenderer()).addNoise()
.build();
}
We can also use encode Captcha method by passing the encoded captcha to Base64, getEncoder method
public static String encodeCaptcha(Captcha captcha) {
String image = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(captcha.getImage(), "jpg", bos);
byte[] byteArray = Base64.getEncoder().encode(bos.toByteArray());
image = new String(byteArray);
} catch (Exception e) {
System.out.println(e.toString());
}
return image;
}
When we have the readable captcha, we can store it in DB or cache to validate whether the user has used the correct captcha or not.
Happy Coding!
Opinions expressed by DZone contributors are their own.
Comments