cloudflare turnstile机器人验证

cf登录后左边菜单栏 选择Turnstile,创建网站,输入域名和资料获得
Site Key 用于前端
Secret Key 用于后端

前端引入Jscript:

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>

插入下面的部件来显示验证,需要填入Site Key,部件必须在表单内才生效

<div class="cf-turnstile" data-sitekey="<Site Key>"></div>

<!--有其他属性可选,例如亮光-->
<div class="cf-turnstile" data-sitekey="<Site Key>" data-theme="light"></div>

后端处理:

#这是验证函数,需要填入Secret Key
def cfyanzhen(cfresponse:str,cfip:str) -> bool:
    """输入参数:cf-turnstile-response,CF-Connecting-IP
    返回布尔值"""
    url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
    # 构建POST请求的数据
    data = {
        'secret': '<Secret Key>',
        'response': cfresponse,
        'remoteip': cfip,
    }

    try:
        response = requests.post(url, data=data)
        jieguo = response.json()
        if jieguo.get('success', False):
            print(f'验证成功,cfresponse:{cfresponse},ip:{cfip}')
            return True
        else:
            print(f'验证失败,cfresponse:{cfresponse},ip:{cfip}')
            return False
    except:
        print('cf连接失败,返回成功')
        return True

#这是验证视图
def login_view(request,diqu):
    if request.method == 'POST':
        # 获取Cloudflare Turnstile的响应和IP地址
        token = request.POST.get('cf-turnstile-response')
        ip = request.headers.get('CF-Connecting-IP')
                        #判断cf验证函数是否验证通过
        if not cfyanzhen(token,ip):
            messages.info(request, _("安全验证失败"),extra_tags="is-warning")
            return redirect('/')

        #这里是处理其他登录验证信息

    else:  #如果是get返回登录页
        form = LoginForm(request)
    return render(request, 'login.html', {'form': form})