You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloudflare Turnstile reCaptcha后端验证:应使用哪个IP地址?

在ASP.NET Core Web API中集成Cloudflare Turnstile时的IP地址选择问题

你需要传递的是发起请求的用户真实IP地址,具体获取方式分两种场景:

  • 如果你的API部署在Cloudflare代理之后:直接从请求头CF-Connecting-IP中获取,这个字段是Cloudflare专门用来转发用户真实IP的,避免拿到Cloudflare节点的代理IP。
  • 如果没有用Cloudflare代理:直接取HttpContext.Connection.RemoteIpAddress,注意要处理IPv6转IPv4的场景(如果业务需要)。

给你修改后的完整代码示例:

首先添加一个获取客户端真实IP的辅助方法:

private string GetClientIp(HttpContext httpContext)
{
    // 优先从Cloudflare转发头取真实IP
    if (httpContext.Request.Headers.TryGetValue("CF-Connecting-IP", out var cfIp))
    {
        return cfIp.ToString();
    }
    
    // 处理非代理场景的IP获取,兼容IPv6转IPv4
    var remoteIp = httpContext.Connection.RemoteIpAddress;
    if (remoteIp != null)
    {
        if (remoteIp.IsIPv4MappedToIPv6)
        {
            remoteIp = remoteIp.MapToIPv4();
        }
        return remoteIp.ToString();
    }
    
    return string.Empty;
}

然后把remoteip字段加入到验证请求中:

// 获取用户真实IP
var clientIp = GetClientIp(HttpContext);

var dictionary = new Dictionary<string, string>
{
    { "secret", reCaptchaKey },
    { "response", customerInquiry.Token },
    { "remoteip", clientIp }
};

var postContent = new FormUrlEncodedContent(dictionary);

HttpResponseMessage recaptchaResponse = null;
string stringContent = "";

// 调用Turnstile验证接口
using (var http = new HttpClient())
{
    recaptchaResponse = await http.PostAsync("https://challenges.cloudflare.com/turnstile/v0/siteverify", postContent);
    stringContent = await recaptchaResponse.Content.ReadAsStringAsync();
}

补充说明:remoteip不是Cloudflare Turnstile验证的必填字段,但传递用户真实IP能帮助Cloudflare更准确地识别异常请求,提升验证的有效性。

内容的提问来源于stack exchange,提问作者Qiuzman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:00:38