Recursive AI

Validate HTTP bearer tokens against JWKS in C#

OneModelContext is a free, open-source .NET SDK for the Model Context Protocol® from Recursive AI. MIT or Apache-2.0, no native dependencies.

A JSON Web Key Set (JWKS) publishes the public keys a server uses to verify signed access tokens. You can use ResourceServer with JwtTokenValidator in a plain HTTP API that accepts signed JWT bearer tokens; the validation doesn’t require a Model Context Protocol® server.

Terminal
dotnet add package RecursiveAI.OneModelContext

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneModelContext.Auth;
using RecursiveAI.OneModelContext.Jose;
// args: issuer, JWKS URL, resource URL
using var keys = new HttpJwksProvider(
    new Uri(args[1]));
var jwt = new JwtTokenValidator(
    args[0], keys);
var auth = new ResourceServer(
    new(new Uri(args[2]), jwt));
var header =
    Environment.GetEnvironmentVariable(
        "AUTHORIZATION") ?? "";
var result =
    await auth.AuthenticateAsync([header]);
Console.WriteLine(result.Succeeded);

Unzip the example, then dotnet run.

The downloaded example generates its own signing key, serves its public key as a local JWKS, and signs two test tokens. dotnet run prints:

Text
Matching audience: accepted
Wrong audience: 401 invalid_token

To run the snippet separately, supply a JWT access token from your issuer. The snippet reads the full Authorization header value (Bearer followed by the access token) from AUTHORIZATION in a console test. Pass the trusted issuer, its JWKS URL, and your resource URL as the three program arguments. Inside a server, pass the request’s actual header values to AuthenticateAsync instead.

The full program

The download generates a temporary RSA signing key and serves its public key at /jwks on loopback. It signs two short-lived tokens with that same key, one for https://tools.example/tools and one for https://other.example/tools. No identity provider, files, or credentials are needed.

C#
using System.Security.Cryptography;
using System.Text.Json;
using RecursiveAI.OneModelContext.Auth;
using RecursiveAI.OneModelContext.Http;
using RecursiveAI.OneModelContext.Jose;
 
// A throwaway issuer and signing key for this local example only.
const string issuer = "https://issuer.example";
var resource = new Uri("https://tools.example/tools");
using var rsa = RSA.Create(2048);
var key = JsonWebSigningKey.FromRsa(rsa, "demo-key");
using var body = new MemoryStream();
using (var json = new Utf8JsonWriter(body))
{
    json.WriteStartObject();
    json.WriteStartArray("keys");
    key.WritePublicJwk(json);
    json.WriteEndArray();
    json.WriteEndObject();
}
var jwks = body.ToArray();
await using var host = new HttpServer(async exchange =>
{
    if (exchange.Request.Path != "/jwks")
    {
        exchange.Response.StatusCode = 404;
        return;
    }
    exchange.Response.StatusCode = 200;
    exchange.Response.SetHeader("Content-Type", "application/json");
    await exchange.Response.Body.WriteAsync(jwks, exchange.Aborted);
});
host.Start();
 
using var keys = new HttpJwksProvider(new Uri(host.BaseAddress!, "/jwks"));
var validator = new JwtTokenValidator(issuer, keys);
var auth = new ResourceServer(new ResourceServerOptions(resource, validator));
 
await CheckAsync("Matching audience", resource.AbsoluteUri);
await CheckAsync("Wrong audience", "https://other.example/tools");
 
async Task CheckAsync(string label, string audience)
{
    var payload = JsonSerializer.SerializeToUtf8Bytes(new
    {
        iss = issuer,
        aud = audience,
        sub = "demo-user",
        exp = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds(),
    });
    var token = key.SignJwt("at+jwt", payload);
    var result = await auth.AuthenticateAsync([$"Bearer {token}"]);
    var outcome = result.Succeeded ? "accepted" : $"{result.StatusCode} {result.Error}";
    Console.WriteLine($"{label}: {outcome}");
}
Text
Matching audience: accepted
Wrong audience: 401 invalid_token

An invalid token yields a failed result; when no verification keys can be obtained because the issuer is unreachable, the resource server can return 503. The resource-server guide says, “A token is never passed on to anything”: use the resulting principal rather than forwarding the bearer token to a tool.

Variations

For a quick test of a request with no credentials, add this after constructing auth in the full program:

C#
var missing = await auth.AuthenticateAsync([]);
Console.WriteLine(missing.StatusCode);
Text
401

The short answer

In C#, give JwtTokenValidator the expected issuer and an HttpJwksProvider pointing at that issuer’s public key set. Put the validator on a ResourceServer configured with your resource URL. Pass the Authorization header values to AuthenticateAsync. Accept the request only if the result succeeds, then check access to the specific operation. Reading a JWT’s claims is not the same as verifying its signature or checking that the claims authorize this request.

How do I validate a JWT bearer token with JWKS?

Start with three trusted settings: the exact issuer (iss), the URL from which to fetch its public keys, and the resource URI the token must name in aud. They serve different purposes, even if their hostnames match. Don’t choose the key server or expected audience from claims supplied in the request. The resource-server guide says the resource is configured, not derived from the Host header. The audience comparison normalizes scheme and host case and drops a default port; otherwise it is exact.

The key set is a JSON document with a keys array. The validator uses those public keys to check the signature. It also checks the issuer, audience and token lifetime; exp is required. The documented algorithms are RS, PS and ES with 256, 384 and 512 variants. An opaque access token isn’t a signed JWT; the validator guide lists an introspection option for that case.

Why does a signed bearer token return 401?

The signature only establishes that a matching key signed the token. Both tokens in the download have that signature property, but the second names another resource. Accepting it would let a token issued for one service be used at another. If you get a 401, compare the issuer and audience with server configuration, check the expiration and check that the key set includes the signer. A missing credential also returns 401, but without error="invalid_token". A valid token that lacks a configured required scope returns 403 instead. On failure the authentication result supplies both the HTTP status and the challenge value, when applicable.

What happens when the issuer rotates its signing keys?

Keep the HttpJwksProvider around instead of creating it per request. It caches the key set for ten minutes. An unknown kid can trigger an early refresh, but fetch attempts are limited to one per 30 seconds. A failed refresh keeps the cached keys if there are any. The default provider uses HTTPS for a remote issuer, permits plain HTTP only on loopback, and does not follow redirects. In the download, only the test key endpoint uses loopback HTTP; the iss and aud strings are identifiers and aren’t fetched.

All onemodelcontext recipes