how to validate reCaptcha token in java

In this post, we are going to explain

how to validate reCaptcha token in java

using a code that you can copy and paste for verifying reCaptcha token using Google’s service.

 

To obtain your own captcha, you should be having your own reCaptcha client and server keys, issued by Google.

Technologies we will use :

  1. Java (1.8)
  2. Tomcat server
  3. Postman

Let’s discuss how to register for your own captcha secrets with Google.

Go to –> https://www.google.com/recaptcha/admin#list

Now on the input box that says, “Label”, select reCAPTCHA V2. And put your site-name and put yourcustom domain name as well.

 

Now we can see that our captcha secret is issued by Google and it visible right on the page.

If we click on the link for our client side and server side integrations we shall find detailed documentation for those.

After we have copied the keys we need to follow the below steps.

Now let’s create our backend Component class for validating the key

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Component
public class RecaptchaManagementController {

private static final Logger LOGGER = LoggerFactory.getLogger(RecaptchaManagementController.class);

public RecaptchaManagementController() {
super();
}

public @ResponseBody ResponseObject validateCaptcha(@RequestBody String captchaToken, HttpServletRequest request) throws ValidationException{

String url = "https://www.google.com/recaptcha/api/siteverify";
String secret = "YOUR_SERVER_KEY";

ResponseObject responseObject = new ResponseObject();
try {

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).queryParam("secret", secret).queryParam("response", captchaToken);
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<RecaptchaResponse>response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity,RecaptchaResponse.class);

RecaptchaResponse rs = response.getBody();

if (response.getStatusCode().value() == 200 && rs.isSuccess()) {
responseObject.setToken("Valid");
LOGGER.info("RECAPTCHA TOKEN VERIFIED SUCCESSFULLY");
}
else
{
LOGGER.error("CAPTCHA_VALIDATION_FAILED");
throw new ValidationException("CAPTCHA_VALIDATION_FAILED");
}

return responseObject;

} catch (Exception e) {
e.printStackTrace();
LOGGER.error("CAPTCHA_VALIDATION_FAILED",e);
throw new ValidationException("CAPTCHA_VALIDATION_FAILED",e);
}

}
}

Model class for RecaptchaResponse.java . This class represents the response object that Google sends back after performing a validation of the reCaptcha token.

import com.fasterxml.jackson.annotation.JsonProperty;

public class RecaptchaResponse {

private boolean success;
private String challenge_ts;
private String hostName;

@JsonProperty("success")
public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

@JsonProperty("challenge_ts")
public String getChallenge_ts() {
return challenge_ts;
}

public void setChallenge_ts(String challenge_ts) {
this.challenge_ts = challenge_ts;
}

@JsonProperty("hostname")
public String getHostName() {
return hostName;
}

public void setHostName(String hostName) {
this.hostName = hostName;
}

@Override
public String toString() {
return "RecaptchaResponse [success=" + success + ", challenge_ts=" + challenge_ts + ", hostName=" + hostName + "]";
}

}

The ResponseObject.java class is the the one that we return once the reCaptcha token is validated from the RecaptchaManagementController.java controller

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
* The Class ResponseObject.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class ResponseObject implements Serializable {

/**
* The Constant serialVersionUID.
*/
private static final long serialVersionUID = 1L;

private String token;

public String getToken() {
return token;
}

public void setToken(String token) {
this.token = token;
}

@Override
public String toString() {
return "ResponseObject [token=" + token + "]";
}

}

The SignupModel.java is the class that will be holding the request data from the client.

import com.fasterxml.jackson.annotation.JsonProperty;

public class SignupModel {

private String captchaToken;

public SignupModel() {
super();
// TODO Auto-generated constructor stub
}

public String getCaptchaToken() {
return captchaToken;
}

public void setCaptchaToken(String captchaToken) {
this.captchaToken = captchaToken;
}

@Override
public String toString() {
return "SignupModel [captchaToken=" + captchaToken + "]";
}

}

Now create a REST endpoint that will accept the reCaptcha token sent by the client and will validate using our Component class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/api")
public class UserControllerImpl{

@Autowired
RecaptchaManagementController recaptchaController;

@PostMapping(value = "/signup")
public @ResponseBody ResponseObject register(@RequestBody SignupModel signupModel, HttpServletRequest request){
return recaptchaController.validateCaptcha(signupModel.getCaptchaToken(), request);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Doubts? WhatsApp me !