How to Integrate reCAPTCHA into a Form

  


reCAPTCHA is a system developed by Google to protect websites from automated bot attacks. Its main function is to distinguish between real users and malicious software, preventing the latter from sending spam or fraudulently accessing a service.

Implementing reCAPTCHA in a form is essential to improve security and prevent attacks such as credential stuffing or comment spam. In this article, we will see how reCAPTCHA works, how to generate API keys and how to effectively integrate it into your website using grecaptcha.enterprise.

🔗 Do you like Techelopment? Check out the site for all the details!

How reCAPTCHA Works

Google reCAPTCHA uses different techniques to identify and block bots. It can work in visible mode, where the user is asked to select images or solve puzzles, or in invisible mode, which automatically analyzes the user's behavior to determine whether they are human or not.

It works based on two keys:

  • Public key: used on the client side to request verification of the reCAPTCHA
  • Private key: used on the server side to invoke Google APIs and verify whether the reCAPTCHA is valid

However, it must be considered that talking about reCAPTCHA validation is improper. This technology is actually based on the generation of a token. The token will be validated to understand whether it is valid or not.

Creating API Keys

To use reCAPTCHA, you need to get API keys from Google. Follow these steps:

  1. Go to the Google reCAPTCHA Enterprise console
  2. Create a new project or select an existing one.
  3. Register your site and choose the type of reCAPTCHA you want.
  4. You will get two keys:
    • Public key (site key): This is used on the client-side to generate the token.
    • Private key (secret key): This is used on the server-side to verify the validity of the token.

keys generation

Difference between reCAPTCHA v2, v3 and Enterprise:

  • reCAPTCHA v2: requires direct user interaction (e.g. selecting images).
  • reCAPTCHA v3: works invisibly, assigning a score to the user to assess whether they are a bot.
  • reCAPTCHA Enterprise:
    • This is the most advanced version, designed for large companies.
    • It offers more sophisticated and customizable risk analysis capabilities.
    • It provides detailed reports and integration with other Google Cloud security services.

Integrating reCAPTCHA into your website

To integrate reCAPTCHA into your website without displaying it directly in the form, you need to add the Google JavaScript script to your page:

<head>
    <script src="https://www.google.com/recaptcha/enterprise.js?render=YOUR_API_KEY"></script>
</head>

Where YOUR_API_KEY should be replaced with your public key.

Next, when the user tries to submit the form, we need to generate a token and attach it to the request:

<form id="my-form">
    <input type="text" id="username" name="username" placeholder="Username" required>
    <input type="password" id="password" name="password" placeholder="Password" required>
    <button type="submit">Submit</button>
</form>

We need to define a callback function to initialize the reCAPTCHA object and <div>:

var onloadCallback = function() {
    grecaptcha.enterprise.render('recaptcha_div', {
      'sitekey' : 'YOUR_API_KEY',
    });
};

Let's now define the function that will handle the form submission and invoke the Google API to generate the reCAPTCHA token:

document.addEventListener('DOMContentLoaded', (e) => {
    document.getElementById("my-form").addEventListener("submit", function(event) {
        event.preventDefault();
       
        grecaptcha.enterprise.ready(async () => {
            const token = await grecaptcha.enterprise.execute('YOUR_API_KEY', {action: 'SUBMIT_FORM'});
         
            let form = document.getElementById("my-form")

            let username = form.querySelector("#username").value;
            let password = form.querySelector("#password").value;
           
            var formData = new FormData();
            formData.append("username", username)
            formData.append("password", password)
            formData.append("recaptcha-response", token);

            fetch("/validateLogin", {
                method: "POST",
                body: formData
            }).then(response => {
               
                if(response.status=="200"){
                    //go to Home Page
                }else{
                    //login error
                }
            })
            .catch(error => {
                console.error("Login error!", error)
            });
        });
    });
});

Here's how it works:
  • We use grecaptcha.enterprise.ready() to make sure the system is loaded.
  • execute() generates a token based on the user's action.
  • We create a FormData object to more easily manage the parameters to be sent to the server to which we add the generated token.

Server Side Token Verification

Once we receive the server side token, we need to verify its validity by making a request to the Google API. Here's an example in JavaScript (Node.js with Express):

const express = require("express");
const fetch = require("node-fetch");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post("/validateLogin", async (req, res) => {
  const token = req.body["recaptcha-response"];
  const secretKey = "YOUR_SECRET_API_KEY";

  const response = await fetch("https://www.google.com/recaptcha/api/siteverify", {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    payload: {
        secret: secretKey,
        response: data["recaptcha-response"]
      }
  });

  const data = await response.json();

  const login = await login(req.body["username"], req.body["password"]) //out of scope of this article

  if (data.success && login) {
    res.json({ success: true, status: "200", message: "Login successfully!" });
  } else {
    res.json({ success: false, status: "500", message: "Login failed!" });
  }
});

app.listen(3000, () => console.log("Server listening on port 3000"));

Explanation:
  • We retrieve the token from the request body.
  • We send it to the Google endpoint along with the secret key.
  • Google responds with a JSON object containing success: true if the token is valid.
  • Based on the response, we can accept or reject the form submission.

Things to keep in mind

Integrating reCAPTCHA into your form is an essential step to ensure the security of user interactions and protect against automated attacks. By using reCAPTCHA, we can improve the user experience without requiring annoying interactions, while ensuring high security.

By following these steps, you will be able to implement an effective and secure verification system for your website. 🚀


Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment