FocalCXM is recognized as a Major Contender in the Veeva Services PEAK Matrix® Assessment 2025 by Everest Group.

703.868.6393 contact@focalcxm.com

Streamlining Security with Google reCAPTCHA v3 in Salesforce Experience Cloud

SaiRohith Ramini

15 October 2024, Tuesday

As online threats become more sophisticated, securing web applications is a top priority. Integrating Google reCAPTCHA v3 into your Salesforce Experience Cloud ensures that your platform can distinguish between real users and bots, enhancing overall security.

In this post, we’ll walk you through how to implement reCAPTCHA v3 using Lightning Web Components (LWC) and Apex, making your Salesforce environment more secure.

Integrating Google reCAPTCHA v3

1. Register Your Site with Google reCAPTCHA

Start by visiting the Google reCAPTCHA admin console and signing in. Click ‘Register a new site,’ select reCAPTCHA v3, and fill in the details for your Salesforce Experience Cloud site. Once completed, you’ll receive two keys: the Site Key and Secret Key.

2. Apex Class for Token Verification

After registration, you’ll need an Apex class that verifies the reCAPTCHA token. This class handles communication with Google’s reCAPTCHA API to validate the token. Here’s a breakdown of the process:

  • Retrieve the reCAPTCHA Secret Key from custom metadata.
  • Send an HTTP POST request to Google’s API.
  • Parse the response to check if the verification was successful.
  • Return the result to the client (LWC component).

Here’s an example of an Apex method that does just that:

verifyRecaptcha(String response) {

    RecaptchaVerificationResult result = new RecaptchaVerificationResult();

    try {

        String recaptchaSecretKey = ‘YOUR_SECRET_KEY’;

        HttpRequest request = new HttpRequest();

        request.setEndpoint(‘https://www.google.com/recaptcha/api/siteverify’);

        request.setMethod(‘POST’);

        request.setBody(‘secret=’ + recaptchaSecretKey + ‘&response=’ + response);

        HttpResponse res = new Http().send(request);

        Map<String, Object> jsonResponse = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());

        result.isSuccess = (Boolean) jsonResponse.get(‘success’);

        result.score = jsonResponse.containsKey(‘score’) ? (Decimal) jsonResponse.get(‘score’) : 0;

        return (result.isSuccess && result.score >= 0.7) ? result : new RecaptchaVerificationResult(false, ‘reCAPTCHA verification failed.’);

    } catch (Exception ex) {

        return new RecaptchaVerificationResult(false, ‘Error during verification: ‘ + ex.getMessage());

    }

}

3. LWC Component for Front-End Interaction

Now, let’s create a Lightning Web Component to manage reCAPTCHA interaction. The LWC will handle token submission and process the reCAPTCHA response:

  • Listen for the reCAPTCHA token.
  • On Case submission, verify the token via the Apex class.
  • Handle success or failure responses based on the token score.

Here’s a basic example:

token = ”;

recaptchaResponseCount = 0;

isSubmitting = false;

connectedCallback() {

    document.addEventListener(‘grecaptchaVerified’, this.handleRecaptchaResponse.bind(this));

}

handleRecaptchaResponse(event) {

    if (this.isSubmitting) {

        this.token = event.detail.response;

        if (this.token) {

            verifyRecaptcha({ response: this.token })

                .then(result => {

                    if (result.isSuccess && result.score >= 0.7) {

                        this.submitCase();

                    } else {

                        this.errorMessage = ‘Failed to verify reCAPTCHA. Please try again.’;

                        this.isSubmitting = false;

                    }

                })

                .catch(() => this.showError());

        }

    }

}

handleSubmit() {

    this.isSubmitting = true;

    document.dispatchEvent(new CustomEvent(‘grecaptchaExecute’, { detail: { action: ‘submit’ } }));

}

showError() {

    this.errorMessage = ‘Error during reCAPTCHA validation. Please try again.’;

    this.isSubmitting = false;

}

4. Experience Cloud Script Integration

To make it all work, load the Google reCAPTCHA script on our Experience Cloud site. Add this code to your site’s header or footer:

<script>

    document.addEventListener(‘grecaptchaExecute’, function(e) {

        grecaptcha.execute(‘YOUR_SITE_KEY’, {action: e.detail.action}).then(function(token) {

            document.dispatchEvent(new CustomEvent(‘grecaptchaVerified’, { detail: { response: token, action: e.detail.action }}));

        });

    });

</script>

<script src=“https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY”></script>

Key Takeaways

  • Enhanced Security: Integrating reCAPTCHA v3 in Salesforce Experience Cloud helps distinguish between bots and real users, reducing the risk of attacks.
  • Seamless Integration: By combining Apex and LWC, we created a secure yet smooth user experience.
  • Flexible Use: reCAPTCHA can be implemented across various site actions, making it a versatile tool for security.

By following this guide, you’ll be able to secure your Salesforce Experience Cloud sites effectively, preventing malicious bot activity while maintaining a smooth user experience.

Need help implementing reCAPTCHA in your Salesforce org? Reach out, and let’s continue building secure, efficient solutions together!