NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

More languages

How to solve AWS WAF CAPTCHA in C#

In .NET the cleanest place for AWS WAF handling is the HTTP pipeline itself. This guide builds a DelegatingHandler that notices the puzzle, fetches an aws-waf-token cookie at $1.40 per 1,000, puts it in the CookieContainer and resends, invisible to the calling code.

Why a message handler

HttpClient sends every request through a chain of handlers. A custom DelegatingHandler sees each request and response, so it can recognize the AWS WAF puzzle, solve it and send the request again before the caller ever sees the puzzle. Your scraping or integration code keeps calling GetStringAsync as usual. Combined with a shared CookieContainer, the cookie is then sent on every later request automatically.

The code targets .NET 8 and uses only the base class library. The AWS WAF CAPTCHA entry explains what the check is and why it sets a cookie.

Anatomy of the puzzle response

A challenged request returns a short HTML document, often with status 405 (Method Not Allowed), that defines a gokuProps object with key, iv and context. These three values are optional inputs for the task; the page URL alone also works. A regular expression with a JSON parse is enough to read them.

using System.Text.Json;
using System.Text.RegularExpressions;

internal static partial class WafPage
{
    [GeneratedRegex(@"gokuProps\s*=\s*(\{[\s\S]*?\})\s*;")]
    private static partial Regex Goku();

    public static bool TryRead(int status, string html, out Dictionary<string, string> props)
    {
        props = new();
        var m = Goku().Match(html);
        if (!m.Success) return false;
        try
        {
            using var doc = JsonDocument.Parse(m.Groups[1].Value);
            foreach (var p in doc.RootElement.EnumerateObject())
                if (p.Value.ValueKind == JsonValueKind.String) props[p.Name] = p.Value.GetString()!;
        }
        catch (JsonException) { /* the URL alone still works */ }
        return status == 405 || props.ContainsKey("key");
    }
}

The source generated regex ([GeneratedRegex]) is compiled at build time in .NET 7 and newer. On older versions, a static new Regex(..., RegexOptions.Compiled) does the same.

The solver call

The handler needs one method that turns a URL plus the optional values into a cookie value. It uses its own HttpClient for the API, separate from the one being protected, so API calls never pass through the WAF handler.

using System.Net.Http.Json;   // PostAsJsonAsync for the task body
using System.Text.Json.Nodes;  // JsonObject and JsonNode

public sealed class WafCookieSource(HttpClient api, string apiKey)
{
    private async Task<JsonNode> Call(string route, JsonObject body, CancellationToken ct)
    {
        body["clientKey"] = apiKey;
        using var res = await api.PostAsJsonAsync($"https://gatesolver.com/{route}", body, ct);
        var text = await res.Content.ReadAsStringAsync(ct);
        var node = JsonNode.Parse(text)!;
        if ((int?)node["errorId"] is int e && e != 0)
            throw new InvalidOperationException($"{route}: {node["errorCode"]}");
        return node;
    }

    public async Task<string> GetAsync(Uri page, IReadOnlyDictionary<string, string> goku, CancellationToken ct)
    {
        var task = new JsonObject { ["type"] = "AntiAwsWafTaskProxyLess", ["websiteURL"] = page.ToString() };
        if (goku.TryGetValue("key", out var k)) task["awsKey"] = k;
        if (goku.TryGetValue("iv", out var iv)) task["awsIv"] = iv;
        if (goku.TryGetValue("context", out var cx)) task["awsContext"] = cx;
        var created = await Call("createTask", new JsonObject { ["task"] = task }, ct);
        var id = created["taskId"]!.ToString();
        for (var n = 0; n < 40; n++)
        {
            await Task.Delay(TimeSpan.FromSeconds(3), ct);
            var progress = await Call("getTaskResult", new() { ["taskId"] = id }, ct);
            var status = (string?)progress["status"];
            if (status == "ready") return (string)progress["solution"]!["cookie"]!;
            if (status == "failed") throw new InvalidOperationException("WAF task failed, nothing charged");
        }
        throw new TimeoutException("aws-waf-token not ready after two minutes");
    }
}

JsonObject from System.Text.Json.Nodes builds the task without defining classes, which suits a payload with optional fields.

The DelegatingHandler with CookieContainer

using System.Net;

public sealed class AwsWafHandler(WafCookieSource source, CookieContainer jar) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        var response = await base.SendAsync(request, ct);
        if (request.Method != HttpMethod.Get) return response;
        var html = await response.Content.ReadAsStringAsync(ct);
        if (!WafPage.TryRead((int)response.StatusCode, html, out var goku)) return response;

        var value = await source.GetAsync(request.RequestUri!, goku, ct);
        jar.Add(request.RequestUri!, new Cookie("aws-waf-token", value, "/"));
        response.Dispose();

        using var again = new HttpRequestMessage(HttpMethod.Get, request.RequestUri);
        foreach (var h in request.Headers) again.Headers.TryAddWithoutValidation(h.Key, h.Value);
        return await base.SendAsync(again, ct);
    }
}

Three details matter. The handler only resends GET requests, because replaying a POST body is not always safe. It copies the original headers so the User-Agent stays the same, since the cookie is tied to the identity that earned it. And it solves at most once per request; if the resend still returns the puzzle, the caller receives it and can log the problem rather than loop.

Reading the body to look for gokuProps buffers the response. For normal pages that is fine; if you download large files through the same client, check the content type first and skip the scan for non HTML responses.

Wiring it together

The CookieContainer must be the same object the inner HttpClientHandler uses, so that cookies added by the WAF handler go out with later requests.

var jar = new CookieContainer();
var inner = new HttpClientHandler { CookieContainer = jar, UseCookies = true,
                                    AutomaticDecompression = DecompressionMethods.All };
var source = new WafCookieSource(new HttpClient { Timeout = TimeSpan.FromSeconds(30) },
                                 Environment.GetEnvironmentVariable("GATESOLVER_KEY") ?? "YOUR_API_KEY");
var client = new HttpClient(new AwsWafHandler(source, jar) { InnerHandler = inner });
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36");

foreach (var path in new[] { "/fares/LIS-OPO", "/fares/LIS-FAO", "/fares/OPO-FAO" })
{
    var text = await client.GetStringAsync("https://fares.example.com" + path);
    Console.WriteLine($"{path}: {text.Length} chars");
}

Usually only the first request triggers a solve. The rest reuse the cookie from the jar, which makes the cost per page a small share of the per solve price. With IHttpClientFactory, register the handler with AddHttpMessageHandler and configure the primary handler with the shared container through ConfigurePrimaryHttpMessageHandler.

Proxies

If the inner handler sends traffic through a proxy (Proxy = new WebProxy(...)) and the site refuses cookies earned from another IP, change the task type to AntiAwsWafTask and add a proxy field in the form http://user:pass@host:port with the same proxy. Use one client, jar and proxy per identity.

Troubleshooting

SymptomLikely cause
Puzzle returned again after the resendUser-Agent changed, cookie added for a different host, or IP mismatch
Cookie never sent on later requestsThe handler and the inner handler use different CookieContainer objects
InvalidOperationException with ERROR_ZERO_BALANCEThe account needs a top-up
Images to choose instead of a plain checkThe grid variant; use AWS WAF Image Classification

The guide on finding AWS WAF parameters lists other markers of the puzzle page, and AWS WAF has all task fields.

Fits integration jobs, catalogue syncs and monitoring of public pages you are allowed to automate.

Avoiding a burst of solves

If many requests start at the same moment, each one can see the puzzle before the first cookie arrives, and each would start its own solve. Add a SemaphoreSlim(1, 1) to the handler: after detecting the puzzle, wait on the semaphore, then check whether the container already holds an aws-waf-token for that host (from a solve that finished while you waited). If it does, skip straight to the resend. Only the first request pays for a solve; the rest reuse its cookie.

Release the semaphore in a finally block so an exception during the solve does not block every later request.

Logging inside the pipeline

Inject an ILogger<AwsWafHandler> and log when a puzzle is detected, the task id, the time the solve took and whether the resend succeeded. Because the handler hides the puzzle from callers, these lines are the only place where you will see how often the site challenges you. A sudden increase is an early sign that the identity or request rate needs attention.

Handling POST endpoints

If the protected call is a POST, warm the session first with a GET to a page on the same site. The handler solves on that GET, the cookie lands in the container, and the POST then goes through with it.

Testing the handler

Give the handler a fake inner handler that returns a saved puzzle page with status 405 on the first call and real content on the second, and a fake WafCookieSource that returns a fixed value. Then assert that the caller receives the content, that the container holds aws-waf-token for the host, and that exactly one solve happened. This runs offline in milliseconds.

Common questions

Why put the logic in a DelegatingHandler?

It keeps WAF handling out of business code. Callers use HttpClient normally and the handler solves and resends when needed.

Why does the handler only resend GET requests?

Replaying a POST body is not always safe or possible. For POST endpoints, load a GET page first to obtain the cookie.

Do I need the gokuProps values?

No. They are optional. The handler sends them when the page includes them.

Does each request cost a solve?

No. The cookie in the container is reused until it expires; only puzzle responses trigger a new solve.

Can I use this with IHttpClientFactory?

Yes. Register the handler with AddHttpMessageHandler and give the primary handler the shared CookieContainer.

Keep reading