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.
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!!
Here is a step-by-step guide on implementing it in Vue and Go. Technologies never matter. You can apply it to any language.
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.
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;
}
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 */
});
});
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.
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"
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
and credBytes
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)
reCaptcha token
and site key
. Parent refers to a project in which we want to create an assessment. For that it uses projectID
.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
}
Let's Work Together
Not sure where to start? We also offer code and architecture reviews, strategic planning, and more.