ASP.NET · Security

Recaptcha Fraud Detection Setup

Implement reCAPTCHA Enterprise fraud protection on ASP.NET WebForms. Includes script integration, token submission via hidden field, and backend API validation.

Google Recaptcha Fraud Protection

(10,000 requests per month are free)

Put in your html <head> on your html page, aspx page, or master page.

HTML
<script src="https://www.google.com/recaptcha/enterprise.js?render=sitekey"></script>

Here is a DIV to drop right on your html or aspx page. This contains the HTML DIV and a javascript call.

HTML & JavaScript
<div class="row">
    <div class="offset-md-2 col-md-10">
        <!-- Hidden input to store the token for C# backend -->
        <asp:HiddenField ID="hfRecaptchaToken" runat="server" />

        <asp:Button runat="server" ID="btnRegister" OnClick="CreateUser_Click" 
                    OnClientClick="return onSubmit(event);" Text="Register" 
                    CssClass="btn btn-outline-dark" />
        <p>NOTE: If you forget your password, email us at skylinecloud.ai.</p>
    </div>
</div>

<script>
    function onSubmit(e) {
        // Prevent the default form submission temporarily
        e.preventDefault();

        grecaptcha.enterprise.ready(async () => {
            // 1. Generate the token on click
            const token = await grecaptcha.enterprise.execute('sitekey', { action: 'submit' });

            // 2. Put token into ASP.NET hidden field
            document.getElementById('<%= hfRecaptchaToken.ClientID %>').value = token;
      
            // 3. Trigger ASP.NET postback manually
            __doPostBack('<%= btnRegister.UniqueID %>', '');
        });
    }
</script>

Step 2 you need to call the google fraud api to complete the request, else this process fails.

On register.cs:

C#
protected void CreateUser_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        string token = hfRecaptchaToken.Value;

        if (string.IsNullOrEmpty(token) || !VerifyRecaptcha(token))
        {
            ErrorMessage.Text = "reCAPTCHA verification failed or score was too low. Please try again.";
            return;
        }
        
        // else continue code
    }
}

CreateUser_Click was a simulated button click. However you use Recaptcha, you need to next see the response from the verification.

C#
public class RecaptchaResponse
{
    public bool success { get; set; }
    public double score { get; set; }
    public string action { get; set; }
    public string[] error_codes { get; set; }
}

private bool VerifyRecaptcha(string token)
{
    // Replace with your reCAPTCHA Enterprise Secret Key from Google Cloud Console
    string secretKey = "secretkey";

    string url = string.Format(
        "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
        secretKey,
        token
    );

    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            string jsonResponse = stream.ReadToEnd();
            JavaScriptSerializer js = new JavaScriptSerializer();
            RecaptchaResponse result = js.Deserialize<RecaptchaResponse>(jsonResponse);

            // Verify success, score threshold (e.g., >= 0.5), and action name
            return result.success && result.score >= 0.5;
        }
    }
    catch (Exception)
    {
        return false;
    }
}

Key Architectural Principles

  • Free Tier Limit: Includes up to 10,000 free assessment requests per month.
  • Step 1 (Client Head Script): Include the official Google Enterprise JS library in your <head> section.
  • Step 2 (Form & Handshake): Capture the token on button click via JavaScript and pass it to an ASP.NET HiddenField during postback.
  • Step 3 (Backend Trigger): Retrieve the hidden field token in your CreateUser_Click event before executing user creation logic.
  • Step 4 (Google API Verification): Send the token to Google's siteverify API endpoint using HttpWebRequest and validate that score >= 0.5.

Need something built?

We design websites for free, animate logos, and build custom software.

Explore our services