Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a ReCaptcha response server side with Python?

I'd like to check a response from client generated using react-google-recaptcha in my Signup form. Unfortunately, I don't see how to validate it server side with Python.

I tried recaptcha-client : https://pypi.python.org/pypi/recaptcha-client, but it seems that it's expecting a response from a generated iframe directly with the same library.

like image 311
dbrrt Avatar asked Sep 24 '17 17:09

dbrrt


People also ask

How do I verify a reCAPTCHA response?

For web users, you can get the user's response token in one of three ways: g-recaptcha-response POST parameter when the user submits the form on your site. grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge.

How do you validate Google reCAPTCHA v3 on server side?

html and contact. php, the first call the second, in thé first i put the following : before </head> : <script src='google.com/recaptcha/api.js'></script> before the submit button <div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div> but in contact.

Does reCAPTCHA need backend?

Yes. It's not clear of your exact setup based on the question, but the backend indeed does need to do some sort of verification to determine if the captcha was passed.

What does validation reCAPTCHA v3 mean?

reCAPTCHA v3. reCAPTCHA v3 verifies requests with a score and gives you the ability to take action in the context of your site. reCAPTCHA v2. reCAPTCHA v2 verifies if an interaction is legitimate with the “I am not a robot” checkbox and invisible reCAPTCHA badge challenges.


2 Answers

It was actually quite straightforward, and no library is required to perform this verification, following Google's documentation : https://developers.google.com/recaptcha/docs/verify

I just had to encode my parameters in the address and send a request to Google servers, here's my code, note that I'm using Flask, but the principle remains the same for any Python back-end :

from urllib.parse import urlencode
from urllib.request import urlopen
import json


        URIReCaptcha = 'https://www.google.com/recaptcha/api/siteverify'
        recaptchaResponse = body.get('recaptchaResponse', None)
        private_recaptcha = '6LdXXXXXXXXXXXXXXXXXXXXXXXX'
        remote_ip = request.remote_addr
        params = urlencode({
            'secret': private_recaptcha,
            'response': recaptchaResponse,
            'remote_ip': remote_ip,
        })

        # print params
        data = urlopen(URIReCaptcha, params.encode('utf-8')).read()
        result = json.loads(data)
        success = result.get('success', None)

        if success == True:
            print 'reCaptcha passed'
        else:
            print 'recaptcha failed'
like image 180
dbrrt Avatar answered Oct 17 '22 18:10

dbrrt


Using python with flask on your server-side

from flask import request

     def verify_recaptcha(self, token):
        recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
        recaptcha_secret_key = 'SECRET-KEY'
        payload = {
           'secret': secret_key,
           'response': token,
           'remoteip': request.remote_addr,
        }
        response = requests.post(, data = payload)
        result = response.json()
        return result.get('success', False)

And on your client side, using React

Install official Google reCaptcha module:

npm install react-google-recaptcha

Then, in your component holding the form:

import React, {Component} from "react";
import ReCAPTCHA from "react-google-recaptcha";

class formContainer extends Component {

    constructor(props) {
        super(props);
        this.recaptchaRef = React.createRef();
    }

    async apply() {
        const token = await this.recaptchaRef.current.executeAsync();
        let formData = new FormData();
        formData.append("token", token);
        //submit your form
    }

    render() {

       return (
          <div>
             <form>
                <input name="email"/>
                <button onClick={()=> { apply(); }}>
             </form>
             <ReCAPTCHA ref={this.recaptchaRef} size="invisible" sitekey={SITE_KEY}/>
          </div>
       )
    }
}
like image 40
David D. Avatar answered Oct 17 '22 17:10

David D.