如何使用 Python 验证 ReCaptcha 响应服务器端?

IT技术 python reactjs recaptcha
2021-05-16 19:30:33

我想检查react-google-recaptcha在我的注册表单中使用生成的客户端的响应不幸的是,我不知道如何使用 Python 验证它的服务器端。

我试过recaptcha-clienthttps://pypi.python.org/pypi/recaptcha-client,但它似乎期待来自生成的 iframe 直接使用相同的库的响应。

2个回答

它实际上非常简单,并且不需要库来执行此验证,遵循 Google 的文档:https : //developers.google.com/recaptcha/docs/verify

我只需要在地址中编码我的参数并向谷歌服务器发送请求,这是我的代码,请注意我使用的是 Flask,但任何 Python 后端的原理都是相同的:

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'

在服务器端使用 python 和flask

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)

在您的客户端,使用 React

安装官方谷歌 reCaptcha module:

npm install react-google-recaptcha

然后,在您持有表单的组件中:

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>
       )
    }
}