Using Google reCAPTCHA to Secure API Endpoints – News Couple
ANALYTICS

Using Google reCAPTCHA to Secure API Endpoints


In this demo, we are going to do reCAPTCHA v3 by using the spring boot application. For that, we are using a simple Button. This button is protected with reCAPTCHA v3, while clicking on the button, it will call google reCAPTCHA.

Here I created the simple button by using thymeleaf. If you need you can use a different HTML body for the different views. The view design can be anything you follow.

reCAPTCHA v3 returns a score for each request without user friction. The
score depends on the interactions with our application and we can take appropriate action according to our business case. We can execute reCAPTCHA on as many actions on the same page.

Register a New Site for Google reCAPTCHA v3

Visit Google reCAPTCHA admin by using this link – https://www.google.com/recaptcha/admin/create

Then simply register. While registering you can give any label, choose reCAPTCHA v3, if you are using localhost you can give localhost as the domain and check the terms and conditions. Finally submit the form.

After clicking on submit you will have the site key and secret key.

Google reCAPTCHA

Handle the Token from the Spring Boot Application

To engage with the demo, First I am doing the token handling part, Token is given by the Google reCAPTCHA site while clicking the button in the front-end, that part we will be look later. So here we are using the token for validating the score by getting from the google client by giving google token and secret to the following URL.

URL: https://www.google.com/recaptcha/api/siteverify

1. Create API for getting token

WebController

package com.amitech.recaptchaservice.controller;
import com.amitech.recaptchaservice.resource.TokenResource;
import com.amitech.recaptchaservice.service.RecaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping
public class WebController 
    @Autowired
    RecaptchaService recaptchaService;
    
    @GetMapping("/index")
    public String index() 
        return "index";
    

    @PostMapping("/api/v1/saveScore")
    public String saveScore(@RequestBody TokenResource tokenResource) throws Exception 
        return recaptchaService.checkValidity(tokenResource.getToken());
    


2. Validate the token by calling the google client

TokenResource

package com.amitech.recaptchaservice.resource;
public class TokenResource 
    private String token;
    public TokenResource() 
    public TokenResource(String token) 
         this.token = token;
    

    public String getToken() 
      return token;
    
    public void setToken(String token) 
        this.token = token;
   

   @Override
    public String toString() 
       return "tokenResource" +
            "token='" + token + ''' +
                '';
    

RecaptchaService

package com.amitech.recaptchaservice.service;
import com.amitech.recaptchaservice.client.GoogleRecaptchaClient;
import com.amitech.recaptchaservice.response.RecaptchaResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RecaptchaService {
 @Autowired
private GoogleRecaptchaClient googleRecaptchaClient;

 public String checkValidity(String token) throws Exception 
if ("FIRST_TIME".equals(token)) 
return "FIRST_TIME";

else 
RecaptchaResponse recaptchaResponse = googleRecaptchaClient.checkScore(token);
if (!recaptchaResponse.getSuccess()) 
if("timeout-or-duplicate".equals(recaptchaResponse.getErrorCodes().get(0)))
return "timeout-or-duplicate";
else
return "Error: " + recaptchaResponse.getErrorCodes().get(0);


else if (recaptchaResponse.getSuccess() && recaptchaResponse.getScore() <= 0.5) 
return "Score: " + recaptchaResponse.getScore();

else if (recaptchaResponse.getSuccess() && recaptchaResponse.getScore() > 0.5) 
return "Score: " + recaptchaResponse.getScore();


return token;


}

GoogleRecaptchClient

package com.amitech.recaptchaservice.client;
import com.amitech.recaptchaservice.response.RecaptchaResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Service
public class GoogleRecaptchaClient 
    private String mSpaceHost = "https://www.google.com/recaptcha/api/siteverify";
    private final RestTemplate restTemplate;
    private static final Logger logger = LoggerFactory.getLogger(GoogleRecaptchaClient.class);
    @Autowired
    public GoogleRecaptchaClient(RestTemplate restTemplate) 
        this.restTemplate  = restTemplate;
    
public RecaptchaResponse checkScore(String token) throws Exception  HttpServerErrorException e) 
logger.error("Error response : State code: , response:  ", e.getStatusCode(), e.getResponseBodyAsString());
throw e;
 catch (Exception err) 
logger.error("Error:  ", err.getMessage());
throw new Exception("This service is not available at the moment!");


 


Thymeleaf App Configuration

Protect button with reCAPTCHA v3

Inside our HTML document,

1. Load the JavaScript API with our sitekey.

2. Add the following tag in the button

<button class="g-recaptcha"
        data-sitekey="6LfqNpQgAAAAABgZ4O_tTN185xDW8gC6nu9bBQ5f"
        data-callback='onSubmit'
        data-action='submit'>Submit

3. Add Submit Script

Call grecaptcha.execute on each action you wish to protect.

function onSubmit() 
        grecaptcha.execute('6LfqNpQgAAAAABgZ4O_tTN185xDW8gC6nu9bBQ5f', action:'validate_captcha')
            .then(function(token) 
                document.getElementById('g-recaptcha-response').value = token;
                console.log(token);
            );
reCAPTCHA

From this image, you can see the protected application, and while clicking the protected button it returns the token from the google site.

Then post the token to the relevant API (The API should be already created by the spring-boot application), and get the response and display.



Source link

Related Articles

Deixe uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

Back to top button