Celestine Babayaro
Celestine Babayaro

Reputation: 363

How to validate Google Recaptcha from server(Java) side?

I have login page with working Google Recaptcha

Login

The problem is, even if I'm not pressing I'm not a robot, I can login. How to make check that the checkboxed is checked?

My java code

@RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> login(@RequestParam String email,
                                                     HttpServletRequest request){

        String ip = request.getRemoteAddr();
        String captchaVerifyMessage = request.getParameter("g-recaptcha-response");
        captchaService.verifyRecaptcha(ip, captchaVerifyMessage);
        if (StringUtils.isNotEmpty(captchaVerifyMessage)) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", captchaVerifyMessage);
            return ResponseEntity.badRequest()
                    .body(response);
        }
        String token;
        User user = userRepository.findOneByEmail(email);
        Map<String, Object> tokenMap = new HashMap<>();
        if (user != null) {
            token = Jwts.builder().setSubject(email).claim("roles", user.getRoles()).setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
            tokenMap.put("token", token);
            tokenMap.put("user", user);
            return new ResponseEntity<>(tokenMap, HttpStatus.OK);
        } else {
            tokenMap.put("token", null);
            return new ResponseEntity<>(tokenMap, HttpStatus.UNAUTHORIZED);
        }
    }

My aim is to make some alert message, smth like "You need to prove that you're not a robot"

Upvotes: 4

Views: 2991

Answers (1)

Roshana Pitigala
Roshana Pitigala

Reputation: 8776

Your best option is to verify it using javascript before submitting your form.

function checkCaptcha() {
  if (!grecaptcha.getResponse()) {
    alert("You need to prove that you're not a robot");
  } else {
    document.getElementById('yourFormId').submit();
  }
}

And in your <form> change the <button> type to button and call checkCaptcha() on click.

<button type='button' onclick='checkCaptcha()'>Login</button>

Because by default type is submit, which will cause the form to submit on press.


If you want to validate reCaptcha from server side take a look at the following post of mine.

Upvotes: 1

Related Questions