Using Google reCAPTCHA v2 in Lightning Web Component

We have many applications that do require some authentication to prevent the attack vectors. To stop flooding the application with unnecessary attacks(eg. Robots running the scripts), we have to adopt some sort of authentication mechanism to regularize the application access. Google reCAPTCHA can help in identifying if the requests are coming from human or not. This blog will help integrate Google reCAPTCHA v2 successfully in our salesforce specifically using lighting web components.
reCAPTCHA V2

To implement Google reCAPTCHA in our lightning web components, we need to following steps:

Salesforce Documentation for reCAPTCHA: click here
  1. Setup Google Admin console for using reCAPTCHA: First step is to set up the site key and secret key in order to use Google reCAPTCHA. Follow the steps as given here. Copy the site key and we will use this in our next step.
  2. Create a static resource named recaptchaV2
  3. Create lightning web component recaptchaV2
Note: This blog assumes you have successfully registered with your Google Account for reCAPTCHA as outlined in step 1 above. While registering, ensure you give your domain url without https://

1. Create Static Resource: Create a static resource recaptchaV2 as given below:
recaptchaV2.html : Create html file and update the ENTER_YOUR_SITE_KEY in this file with the site key that you did create as part of Google Admin console set up. Also see the usage of window.postMessage in details to understand how it works and how this can be leveraged.
<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" onsubmit="return validateForm()" method="POST">
      <div class="g-recaptcha" data-sitekey="ENTER_YOUR_SITE_KEY"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>

    <script type="text/javascript">
        function validateForm(){

            if(grecaptcha.getResponse().length == 0){
                alert('Please click the reCAPTCHA checkbox');
                parent.postMessage("captcha failed", location.origin);
                return false;
            }
            parent.postMessage("captcha success", location.origin);
            return true;
        }
    </script>
  </body>
</html>
Upload this in static resource. The static resource should look like below
2. Create LWC recaptchaV2: Create a lightning web component recaptchaV2 as below:
recaptchaV2.html:
<template>
    <iframe src={navigateTo} name="captchaFrame" onload={captchaLoaded} style="width: -webkit-fill-available;"></iframe>
</template>
recaptchaV2.js: 
import { LightningElement, track } from 'lwc';
import pageUrl from '@salesforce/resourceUrl/recaptchaV2';

export default class RecaptchaV2 extends LightningElement {
    @track navigateTo;

    constructor(){
        super();
        this.navigateTo = pageUrl;
        window.addEventListener("message", this.listenForMessage);//add event listener for message that we post in our recaptchaV2 static resource html file.
    }

    captchaLoaded(event){
        if(event.target.getAttribute('src') == pageUrl){
            console.log('Google reCAPTCHA is loaded.');
        } 
    }

    listenForMessage(message){
        console.log('message data : ' + message.data);//message.data - The object passed from the other window.
        console.log('message origin : ' + message.origin);//message.origin - The origin of the window that sent the message at the time postMessage was called.
} }
recaptchaV2.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
</targets> </LightningComponentBundle>
Demo: Upload the recaptchaV2 in you SFDC environment and add on the Home page. You will see different behaviors in your console.

If you like this blog content and find inciteful, please comment and let me know. 

Comments

  1. to send an event from Message listener to the parent component. Its getting dispatched but it is not receiving in the parent, Any idea?

    ReplyDelete
  2. This website and I conceive this internet site is really informative ! Keep on putting up! Anti captcha key

    ReplyDelete
  3. the community stopped working after the code is deployed and the changes were made

    ReplyDelete
  4. "very informative topic, keep sharing such wonderful posts with us, and I will subscribe for more useful updates from you.
    latest tech news"

    ReplyDelete
  5. Platform Developer I Certification Maintenance (Winter '24): https://salesforcehints.blogspot.com/2023/12/platform-developer-i-certification.html

    ReplyDelete
  6. 401 (Unauthorized) POST error receiving while clicking on submit. What could be the reason ?

    ReplyDelete

Post a Comment