3

the following is the HTML of my login page:

<!DOCTYPE HTML>
<html>

<head>
    <script type="text/javascript" src="/resources/libraries/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js?render=<recaptchaSiteKey>"></script>
</head>

<body>
    <form id="loginForm">
        <table>
            <tr>
                <td>User:</td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td><button type="submit">Submit</button></td>
            </tr>
        </table>
    </form>
    <input id="recaptchaSiteKey" type="hidden" value="<recaptchaSiteKey>" />

    <script type="text/javascript">
        $(document).ready(() => {
            $('#loginForm').submit((event) => {
                event.preventDefault();
                const siteKey = $('#recaptchaSiteKey').val();

                grecaptcha.ready(() => {
                    grecaptcha
                        .execute(siteKey, {
                            action: 'login'
                        })
                        .then((token) => {
                            $('#loginForm').prepend(`<input type="hidden" name="g-recaptcha-response" value="${token}" />`);
                            const submittableForm = $(`<form action="/login" method="POST" />`);

                            $('#loginForm *').filter(':input')
                                .each((index, element) => {
                                    const jqElement = $(element);
                                    const name = jqElement.attr('name');
                                    const value = jqElement.val();

                                    if (name && value) {
                                        submittableForm.append(`<input type="hidden" name="${name}" value="${value}" />`)
                                    }
                                });

                            $(document.body).append(submittableForm);
                            $(submittableForm).submit();
                        });
                });
            });
        });
    </script>
</body>

</html>

In the documentation of reCaptcha V3 - Frontend integration, it is mentioned:

<script src="https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"></script>
<script>
grecaptcha.ready(function() {
    grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) {
       ...
    });
});
</script>
  1. Load the JavaScript api with your sitekey
  2. Call grecaptcha.execute on an action or when the page loads
  3. Send the token to your backend with the request to verify

I am wondering if I am using the grecaptcha.execute properly or not.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

0 Answers0