Integrate Google Recaptcha Enterprise using Vue.js and Golang

Completely Automated Public Turing test to tell Computers and Humans Apart(CAPTCHA)
Sep 20 2022 · 4 min read

Introduction 

Hello everyone!!!

We all want to protect our websites or application from spam or abuse. One possible way provided by Google is reCaptcha.

Google Recaptcha uses advanced risk analysis engines and automated public turing tests to protect our application from spam or abusive activities by bots. It can be able to identify bots and humans and let valid users use our application.

What will you learn?

Complete guide on how to implement google reCaptcha in your website.

Before beginning with reCaptcha, I must recommend reading google’s getting started guide on reCaptcha Enterprise.
As our application is non-Google cloud, we will use a non-Google cloud environment setup.

Flow is simple!!

  • Generate a token from the frontend after verifying reCaptcha
  • Verify the token from the backend before processing form data.

Here is a step-by-step guide on implementing it in Vue and Go. Technologies never matter. You can apply it to any language.

  • Configure reCaptcha on the Google cloud console
  • Add a javascript API reference on the website(VueJs)
  • Initialize reCaptcha and generate the token
  • Verify reCaptcha token at backend(Golang)

1. Configure reCaptcha on the Google cloud console

Assuming that you have created a project on the google cloud console. If not yet, you can start over here.

We need to enable Enterprise API in the Google cloud console.

Here are references…

You will have the site key and JSON file containing project information. For security purposes, it’s better to store this information as environment variables.

For storing the reCaptcha JSON file as an environment variable, convert it to base64 and store it. you can use it easily without exposing content.

2. Add a javascript API reference on the website

To use reCaptcha, we need to use google’s reCaptcha enterprise API on our website in a script tag.

<script src=”https://www.google.com/recaptcha/enterprise.js?render=YOUR_RECAPTCHA_SITE_KEY” async defer />

In Vue with vite, we have appended it using javascript like below.

let recaptchaScript = document.createElement("script");
recaptchaScript.setAttribute(
   "src",
   "https://www.google.com/recaptcha/enterprise.js?render=" + import.meta.env.VITE_RECAPTCHA_SITE_KEY
);
recaptchaScript.setAttribute("async", "true");
recaptchaScript.setAttribute("defer", "true");
document.head.appendChild(recaptchaScript);

If you want hidden reCaptcha, you can add CSS to its’s class like below,

.grecaptcha-badge {
  visibility: hidden;
}

3. Initialize reCaptcha and generate the token

By adding the link as mentioned in step 2, we can access reCaptcha using grecaptcha.enterprise .

grecaptcha.enterprise.ready(() => {
        grecaptcha.enterprise
          .execute(import.meta.env.VITE_RECAPTCHA_SITE_KEY, {
            action: "verify",
        })
        .then(function (token) {
            /** append token with formData and send it to backend API */
        })
        .catch(() => {
            /** invalid reCaptcha score */
        });
});
  • ready() : execute code once reCaptcha API will load fully.
  • execute() : It invokes reCaptcha enterprise verification for score-based site keys. It will generate a reCaptcha token that will be used for verification.
    We will explore more about the reCaptcha token in step 4.
  • action: the name of the event on which you want to run reCaptcha. It can be anything. some examples are here. You can also use other names apart from them.

4. Verify the reCaptcha token at the backend

Let’s create code that will verify the reCaptcha token from the request body before processing the form data and tell us whether the user is valid or not.

I have divided this process into a few steps, so it’s easy to understand.

i. install the library

We are using the google-cloud library of go. Install it using the following command

go get cloud.google.com/go/recaptchaenterprise/v2/apiv1

Import it to the file,

recaptcha "cloud.google.com/go/recaptchaenterprise/v2/apiv1"

ii. Create a reCaptcha client


ctx := context.Background()

/** convert base64 formetted JSON to bytearray */
credBytes, err := b64.StdEncoding.DecodeString(os.Getenv("JSON_BASE64"))
if err != nil {
	return false, err
}

/** create reCaptcha client with JSON bytearray */
client, err := recaptcha.NewClient(ctx, option.WithCredentialsJSON(credBytes))
if err != nil {
	return false, err
}

/** close client when it's done */
defer client.Close()
  • ctx: Creating go context necessary for using reCaptcha API in Golang.
  • credBytes: converted base64 JSON to a byte array, so we can use it when creating a client.
  • recaptcha.NewClient(): will create a new client using ctx and credBytes

iii. Create an assessment

Assessment is a type of process in which, you have to submit a reCaptcha token to the reCaptcha enterprise endpoint . it will process the token and report the token’s validity and score.

In Golang, you need to install the library

go get google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1

Import it like,

recaptchapb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1"

Create assessment using recaptchapb,

/** create the assessment request */
request := &recaptchapb.CreateAssessmentRequest{
	Assessment: &recaptchapb.Assessment{
		Event: &recaptchapb.Event{
			Token:   token,
			SiteKey: os.Getenv("RECAPTCHA_SITE_KEY"),
		},
	},
	Parent: fmt.Sprintf("projects/%s", os.Getenv("RECAPTCHA_PROJECT_ID")),
}
 
/** create assessment */
response, err := client.CreateAssessment(ctx, request)
  • request: Build assessment request using reCaptcha token and site key . Parent refers to a project in which we want to create an assessment. For that it uses projectID .
  • CreateAssessment(): will send a request to the enterprise endpoint and get a result from it.

iv. Interpret assessment

In this step, we will interpret the response from the assessment and make a decision based on it.

We have to check action which we have used in frontend and score ≥ 0.9 of reCaptcha to validate the user.

if response.TokenProperties.Action == "verify" && response.TokenProperties.Valid && response.RiskAnalysis.Score >= 0.9 {
    return true
}

you can explore more about assessment response from GitHub.

Based on the assessment result, we can decide whether to process further or just throw an error to the user.

The full source code of it as below,

func VerifyRecaptcha(token string) (bool, error) {

    ctx := context.Background()

    /** convert base64 formetted JSON to bytearray */
    credBytes, err := b64.StdEncoding.DecodeString(os.Getenv("JSON_BASE64"))
    if err != nil {
      return false, err
    }

    /** create reCaptcha client with JSON bytearray */
    client, err := recaptcha.NewClient(ctx, option.WithCredentialsJSON(credBytes))
    if err != nil {
      return false, err
    }

    /** close client when it's done */
    defer client.Close()

    /** create the assessment request */
    request := &recaptchapb.CreateAssessmentRequest{
      Assessment: &recaptchapb.Assessment{
        Event: &recaptchapb.Event{
          Token:   token,
          SiteKey: os.Getenv("RECAPTCHA_SITE_KEY"),
        },
      },
      Parent: fmt.Sprintf("projects/%s", os.Getenv("RECAPTCHA_PROJECT_ID")),
    }

    /** create assessment */
    response, err := client.CreateAssessment(ctx, request)

    if err != nil {
      return false, err
    }

    /** Interpret and verify assessment response */
    if response.TokenProperties.Action == "verify" && response.TokenProperties.Valid && response.RiskAnalysis.Score >= 0.9 {
      return true, nil
    }

    return false, nil
}

sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.


sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.

canopas-logo
We build products that customers can't help but love!
Get in touch

Let's Work Together

Not sure where to start? We also offer code and architecture reviews, strategic planning, and more.

cta-image
Get Free Consultation
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.