Clavem

How to validate a license key in a C# or .NET app

POST the key and the saved instance id to /v1/licenses/validate with one shared HttpClient that has a timeout, read the status and the Retry-After header from the response, and map the answer to a record. On Windows, protect the stored key with DPAPI for the current user.

This page covers the online validate call in C#. The token check for the offline path is in offline verification in C#, and the first-run call is in device activation in C#. The C# code in this guide was not compiled or run, because no .NET SDK was available. It uses documented APIs, and the server behavior it relies on was checked against the live API.

The client

HttpClient returns a response for every HTTP status, so a 404 or 429 is not an exception. Only a network failure or a timeout throws. One static client with a connection lifetime is Microsoft’s recommended pattern:

using System.Net.Http.Json;
using System.Text.Json;

public enum LicenseKind { Valid, NotValid, Unknown, NoAnswer }

public sealed record Outcome(LicenseKind Kind, string? Token = null, string? Reason = null, TimeSpan? RetryAfter = null);

public sealed class LicenseClient
{
    private static readonly HttpClient Http = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) })
    {
        BaseAddress = new Uri("https://clavem.io"),
        Timeout = TimeSpan.FromSeconds(8),
    };

    static LicenseClient() => Http.DefaultRequestHeaders.UserAgent.ParseAdd("Inkwell/3.2");

    private sealed record Reply(bool? Valid, string? Error, string? Token);

    public async Task<Outcome> ValidateAsync(string key, string? instanceId, CancellationToken ct = default)
    {
        var body = new Dictionary<string, string> { ["license_key"] = key };
        if (instanceId is not null) body["instance_id"] = instanceId;

        try
        {
            using var response = await Http.PostAsJsonAsync("v1/licenses/validate", body, ct);
            var reply = await ReadAsync(response, ct);
            switch ((int)response.StatusCode)
            {
                case 200 when reply?.Valid is bool valid:
                    return valid ? new(LicenseKind.Valid, reply.Token) : new(LicenseKind.NotValid, reply.Token, reply.Error);
                case 404:
                    return new(LicenseKind.Unknown, Reason: reply?.Error);
                case 429 or 503:
                    return new(LicenseKind.NoAnswer, RetryAfter: response.Headers.RetryAfter?.Delta);
                default:
                    return new(LicenseKind.NoAnswer);   // 400 is a bug in the app; other 5xx is on the server
            }
        }
        catch (Exception e) when (e is HttpRequestException or TaskCanceledException or JsonException)
        {
            return new(LicenseKind.NoAnswer);            // offline, DNS failure, timeout
        }
    }

    private static async Task<Reply?> ReadAsync(HttpResponseMessage response, CancellationToken ct)
    {
        try { return await response.Content.ReadFromJsonAsync<Reply>(JsonSerializerOptions.Web, ct); }
        catch (JsonException) { return null; }           // not JSON: for example an HTML page from a proxy
    }
}

JsonSerializerOptions.Web (new in .NET 9; on .NET 8 use new JsonSerializerOptions(JsonSerializerDefaults.Web)) makes property names case-insensitive, so valid binds to Valid. A null for error binds to a null string, which is why the record fields are nullable. response.Headers.RetryAfter is parsed for you: Delta is a TimeSpan when the header holds seconds, which is the form Clavem sends.

What each answer means

Reply Kind What the app does
200, valid: true Valid Store the new token. This restarts the 14-day window.
200, valid: false NotValid Expired or disabled. Store the token, show Reason, keep the key.
404 Unknown Unknown key, or instance_id not found. Clear the license, ask for the key.
429 (Retry-After: 60), 503 (Retry-After: 5) NoAnswer No verdict. Use the stored token and retry later.
Exception NoAnswer Offline or timeout. Same.

Retry a 503 once for its 5 seconds. Never hold a launch for the 60 seconds a 429 asks for. The live API answers an empty body with a 400 and {"valid":false,"error":"license_key: Invalid input: expected string, received undefined"}. That is a bug in your call, not a customer problem.

Where to keep the key

On Windows, DPAPI encrypts a value so that only the same Windows user can decrypt it. ProtectedData lives in the System.Security.Cryptography.ProtectedData package on modern .NET, and it works only on Windows:

using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text.Json;

public sealed record Saved(string Key, string InstanceId, string Token);

[SupportedOSPlatform("windows")]
public static class LicenseStore
{
    private static readonly byte[] Entropy = "com.example.inkwell"u8.ToArray();
    private static string FilePath => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Inkwell", "license.bin");

    public static void Save(Saved saved)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
        var plain = JsonSerializer.SerializeToUtf8Bytes(saved);
        File.WriteAllBytes(FilePath, ProtectedData.Protect(plain, Entropy, DataProtectionScope.CurrentUser));
    }

    public static Saved? Load()
    {
        try
        {
            var plain = ProtectedData.Unprotect(File.ReadAllBytes(FilePath), Entropy, DataProtectionScope.CurrentUser);
            return JsonSerializer.Deserialize<Saved>(plain);
        }
        catch (Exception e) when (e is IOException or CryptographicException or JsonException) { return null; }
    }

    public static void Clear() { if (File.Exists(FilePath)) File.Delete(FilePath); }
}

Guard calls with OperatingSystem.IsWindows(). On macOS and Linux, ProtectedData throws PlatformNotSupportedException. A .NET MAUI app can use SecureStorage, which wraps each platform’s store. A cross-platform desktop app without MAUI needs a library for the Keychain and the Secret Service, or an accepted fallback to a file with restricted permissions.

Pitfalls specific to .NET

  • Do not block on .Result or .Wait() in a UI app. The continuation needs the UI thread, and the app deadlocks. Use await from an async handler.
  • Timeouts are cancellations. Catch TaskCanceledException, or a slow network crashes the launch.
  • PooledConnectionLifetime matters. A static client without it keeps connections forever and ignores DNS changes.
  • DPAPI ties data to a Windows user. A roaming profile or a reset password can make old blobs unreadable. Load returns null then, and the app asks for the key again.
  • One request per launch. The License API allows 60 requests a minute per key, so do not validate in a loop or from several windows at once.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the assembly. Plan limits never block validation. See the API reference for every field.

Questions

Should I create a new HttpClient for each license check?

No. Microsoft's guidance is to use a static or singleton HttpClient with PooledConnectionLifetime set, or IHttpClientFactory. Creating and disposing a client per call wastes connections and can exhaust ports.

What exception does HttpClient throw on a timeout?

A TaskCanceledException, with a TimeoutException as its inner exception in current .NET versions. It is not an HttpRequestException, so catch both when you want to treat offline and timeout alike.

Where do I store a license key in a .NET desktop app?

On Windows, encrypt it with ProtectedData and DataProtectionScope.CurrentUser, which is DPAPI. In a .NET MAUI app, SecureStorage uses each platform's secure store. DPAPI throws on macOS and Linux, so check the operating system first.

Sources

  1. Microsoft Learn, HttpClient guidelines (checked November 2026)
  2. Microsoft Learn, ProtectedData class (checked November 2026)