[Django]-Recaptcha v3 is backend implementation necessery?

2👍

Yes, you need to implement verification on the backend.

I tend to do this via a mixin so that it can be added to any view secured by reCAPTCHA;

class VerifyCaptchaMixin:
    """ Verify post requests which use google recaptcha """

    def post(self, request, *args, **kwargs):
        """
        Send a verification request to google if we can.
        """
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        ''' Begin reCAPTCHA validation '''
        recaptcha_response = request.POST.get('g-recaptcha-response')
        if recaptcha_response:
            # captcha verification
            data = {
                'response': recaptcha_response,
                'secret': settings.NORECAPTCHA_SECRET_KEY
            }
            resp = requests.post(
                'https://www.google.com/recaptcha/api/siteverify',
                data=data
            )
            result_json = resp.json()
            ''' End reCAPTCHA validation '''
            if not result_json.get('success'):
                err_msg = "An error has occurred with Google reCAPTCHA"
                form.add_error(None, err_msg)
                # error in recaptcha, re-render the signup form
                return render(
                    request, self.template_name, {
                        'form': form,
                        'is_robot': True
                    }
                )
        return super().post(request, *args, **kwargs)

Docs on this are here; https://developers.google.com/recaptcha/docs/verify

Leave a comment