Protect an MCP server in ASP.NET Core with OAuth: a step-by-step example with Keycloak

An MCP server over HTTP is a web API that an AI client calls for a user. The moment it does anything that isn't public, you need to know who is calling and what they allowed that client to do. The MCP specification answers this with OAuth, and its authorization pages are long. Most of them aren't about your server, though.

The one idea to keep through this article: an MCP server is an OAuth resource server, nothing more. It validates access tokens, and it tells clients where to get one. Signing users in, asking for consent, issuing and renewing tokens and registering clients are the authorization server's job, and you don't have to write one.

In this tutorial we will build a small MCP server in ASP.NET Core that only signed-in users can use, with Keycloak as the authorization server. Everything runs locally, without any cloud. At the end a console client, Claude Code and VS Code find the server, sign the user in through the browser and call its tools, and each tool does only what the token allows.

The title "MCP + OAuth in ASP.NET Core" above a terminal that shows a 401 response with a WWW-Authenticate header and a console client signing in, next to a consent card asking "Grant access to the MCP client?" with Yes and No buttons

The whole example is on GitHub: gergodrazsdik/example-aspnet-mcpauth. Each step below is one commit and one tag, step-01 to step-10, so you can check out any step or compare two of them. I only show the code that matters here; the rest is in the repository.

What you need

  • The .NET 11 SDK. The code uses nothing that is new in .NET 11: with net10.0 and the 10.0 packages it builds and passes its tests on .NET 10 too. The comments in Directory.Build.props and Directory.Packages.props say what to change.
  • Podman or Docker, with Compose.
  • Ports 8180 (Keycloak) and 5100 (the MCP server) free.

The versions I used: the official MCP C# SDK (ModelContextProtocol.AspNetCore) 2.3.1, Microsoft.AspNetCore.Authentication.JwtBearer 11.0.0 and Keycloak 26.8.1. The MCP specification revision is 2026-07-28. This area moves fast, so check anything that looks different on your machine against the versions you have.

Try it first

If you'd rather see it work before reading how, clone the repository and start the two parts:

bash
podman compose up -d                         # or: docker compose up -d
dotnet run --project src/McpAuth.Server      # the MCP server on http://localhost:5100/mcp

Keycloak takes about half a minute to start. Then, in a second terminal:

bash
dotnet run --project src/McpAuth.Client -- --add "Hello from the console"

A browser opens Keycloak's login page. Sign in as alice (password alice) and allow access. The client prints who you are, what the token allows, and the notes, yours included. Then run it again and sign in as bob (password bob): he may read notes but not add them, and you'll see where that is decided. The same browser works. The client asks for an offline token, Keycloak keeps no browser session for such a sign-in, and so every run starts at the login page. If Keycloak does send you straight back as alice, run the client with --no-browser and open the address it prints in a private window.

These passwords are public demo values. Nothing in this setup is meant to leave your machine, and the last sections list what production would change.

How the pieces fit

A client that knows nothing but the endpoint's URL can work out everything else. That is the part of the MCP authorization specification a server has to get right:

Sequence diagram of discovery and sign-in between the MCP client, the MCP server and Keycloak, in thirteen numbered steps: an unauthenticated request and its 401, the two metadata documents, client registration, the sign-in in the browser, the token request, and the call with the token
From the endpoint's URL to a call with a token

Three standards do most of the work:

  • Protected resource metadata (RFC 9728). The server answers a request without a token with 401 and a WWW-Authenticate header that points to a small JSON document. The document names the resource (the endpoint's URL), the authorization server and the scopes. The MCP specification requires servers to implement this, and clients to use it.
  • Authorization server metadata (RFC 8414). Keycloak publishes its endpoints and what it supports. The client reads them from there.
  • Authorization code with PKCE. The user signs in at Keycloak in the browser, the client gets a code on a loopback address and exchanges it for an access token. The client also sends a resource parameter (RFC 8707) that says which server the token is for.

Your server implements the first and validates the result of the third. The MCP C# SDK and ASP.NET Core's JwtBearer do both, with about forty lines of configuration.

The example's domain is as small as it can be while keeping the authorization visible: a notes store with three tools. whoami shows the signed-in user and what the token allows, list_notes needs the notes:read scope, and add_note needs notes:write.

Step 1: An MCP server with one tool

Start without authentication, so there's something to protect. The server is a minimal API with the SDK's Streamable HTTP transport (step-01):

src/McpAuth.Server/Program.cs csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<NoteStore>();

builder.Services.AddMcpServer()
    .WithHttpTransport(options => options.Stateless = true)
    .WithTools<NoteTools>();

var app = builder.Build();

app.MapMcp("/mcp");

app.Run();

Stateless means the server keeps no session between requests, so any instance can answer any request and you can scale out without sticky sessions. In the SDK's 2.x versions it is the default; I set it anyway so the code says so.

A tool is a method on a class:

src/McpAuth.Server/NoteTools.cs csharp
[McpServerToolType]
public sealed class NoteTools(NoteStore notes)
{
    [McpServerTool(Name = "list_notes", Title = "List notes", ReadOnly = true)]
    [Description("Lists every note, oldest first, with its author and when it was written.")]
    public IReadOnlyList<Note> ListNotes() => notes.All();
}

Name is what clients call, the description is what the model reads, and the return value is serialized to JSON. ReadOnly = true becomes a hint for the client. Remember that it's only a hint; step 6 comes back to it.

A stateless server answers tools/list without any handshake, so curl is enough to check it:

bash
curl -i http://localhost:5100/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

The Accept header has to list both content types. The answer is a 200 with the list_notes tool in it. Anyone who can reach the port gets that answer, and the rest of the article changes that.

Step 2: Keycloak with a seeded realm

Keycloak runs in a container in dev mode and imports a realm file at every start (step-02). The parts of compose.yaml that matter:

compose.yaml yaml
services:
  keycloak:
    image: quay.io/keycloak/keycloak:26.8.1@sha256:3f3c5f8e03c614774b4bd9173b88391fefa4153bfc010d8012d59ad825377332
    command: ["start-dev", "--import-realm"]
    environment:
      KC_BOOTSTRAP_ADMIN_USERNAME: admin
      KC_BOOTSTRAP_ADMIN_PASSWORD: admin
      # The address in the tokens' issuer. The browser and the MCP server
      # on the host both reach Keycloak here, so both see the same issuer.
      KC_HOSTNAME: http://localhost:8180
    ports:
      - "127.0.0.1:8180:8080"
    volumes:
      - ./keycloak:/opt/keycloak/data/import:ro

KC_HOSTNAME guards against the most confusing error of this kind of setup. A token's issuer is the address Keycloak believes it has, and the server accepts only tokens whose issuer matches what it read from Keycloak itself. Without a fixed hostname, Keycloak takes that address from each request. A server that reaches Keycloak under another name than the browser does, a container name for instance, then gets tokens it can't validate.

There is no volume for Keycloak's data, on purpose: podman compose down followed by up -d gives you the realm file's state again.

The realm

keycloak/realm-demo.json is about 250 lines and holds everything the example needs:

  • Two realm roles, notes-reader and notes-writer, and two users: alice has both, bob only the reader role.
  • Two client scopes, notes:read and notes:write, each with the text the consent page shows.
  • A public client for the console app, mcpauth-console: no secret, authorization code flow only, consent required, PKCE required, and the redirect URI http://127.0.0.1/callback.

Two details of the scopes carry the design. Here is notes:write, with the mapping that follows the scope list (its third line, for offline_access, arrives in step 5):

keycloak/realm-demo.json json
{
  "name": "notes:write",
  "description": "Add notes on the MCP server.",
  "protocol": "openid-connect",
  "attributes": {
    "include.in.token.scope": "true",
    "display.on.consent.screen": "true",
    "consent.screen.text": "Add notes for you"
  },
  "protocolMappers": [
    {
      "name": "mcp audience",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-audience-mapper",
      "config": {
        "included.custom.audience": "http://localhost:5100/mcp",
        "access.token.claim": "true",
        "id.token.claim": "false",
        "introspection.token.claim": "true"
      }
    }
  ]
}
keycloak/realm-demo.json json
"scopeMappings": [
  { "clientScope": "notes:read", "roles": ["notes-reader"] },
  { "clientScope": "notes:write", "roles": ["notes-writer"] },
  { "clientScope": "offline_access", "roles": ["offline_access"] }
]

The audience mapper puts the MCP endpoint's URL into the aud claim of every token that carries a notes scope. The MCP specification requires a server to accept only tokens issued for it, and aud is how the server will know. A token from the same realm without a notes scope has no such audience, and the server refuses it.

The specification's own mechanism for this is the resource parameter that clients send. Keycloak 26.8 has an experimental resource-indicators feature for it, off by default, and its guide for MCP describes the audience mapper on optional client scopes as the way to bind the audience without it. With the feature off, Keycloak ignores resource, which does no harm here because the server checks aud itself. I tried the feature in a second container: it refused token requests whose resource didn't match the audience exactly, and a trailing slash was enough for invalid_target. Whichever way you go, keep one spelling of the endpoint's URL everywhere.

The scope-to-role mapping makes Keycloak grant a scope only to users who hold its role:

Keycloak's admin console, the Scope tab of the notes:write client scope: a note says that when role scope mappings are defined, the user must be a member of at least one of the roles, and the table below lists the notes-writer role
notes:write is granted only to users with the notes-writer role

So when a client asks for notes:read notes:write for bob, Keycloak leaves notes:write out and issues the token anyway. The claims of three tokens, all requested through the same client (trimmed):

text
alice, asked for notes:read notes:write
  iss:   http://localhost:8180/realms/demo
  aud:   http://localhost:5100/mcp
  scope: openid profile notes:read notes:write
  roles: ["notes-writer","notes-reader"]

bob, asked for notes:read notes:write
  scope: openid profile notes:read          <- notes:write dropped by Keycloak
  roles: ["notes-reader"]

alice, asked for notes:read only
  scope: openid profile notes:read
  roles: ["notes-reader"]                    <- only the roles of the granted scopes

The scope claim is already the intersection of what the client asked for, what the user consented to and what the user's roles allow. The server can authorize on that one claim.

Pitfalls of the realm import

  • An import that lists clientScopes drops Keycloak's built-in scopes. My first realm file defined only the notes scopes, and the realm came up without profile, roles, basic and the others. Without basic there is no sub claim in the access token. The realm file therefore defines the few scopes it needs itself, which also keeps it readable next to a 2,000-line export.
  • No roles claim, although the user has the roles. When an imported client has consentRequired: true and doesn't say otherwise, Keycloak sets fullScopeAllowed to false for it, and then only roles that some scope maps to get into the token. The fix is the scopeMappings above, and its side effect is the downscoping that the example relies on.
  • Consent is remembered. When the same user signs in again, there is no consent page after the login page. To see it again, recreate the container or remove the consent under Users → alice → Consents in the admin console (http://localhost:8180/admin, admin/admin).
  • A recreated Keycloak has new signing keys. A server that is still running holds the old ones, and the first request fails with IDX10503: Signature validation failed. Restart the server after you reset Keycloak.

Step 3: Require a token

Now the endpoint accepts only requests with a valid access token from the realm (step-03). This is the heart of the example:

src/McpAuth.Server/Program.cs csharp
var authority = builder.Configuration["Auth:Authority"]   // http://localhost:8180/realms/demo
    ?? throw new InvalidOperationException("Set Auth:Authority to the Keycloak realm's URL.");
var resource = builder.Configuration["Auth:Resource"]     // http://localhost:5100/mcp
    ?? throw new InvalidOperationException("Set Auth:Resource to the MCP endpoint's URL.");

builder.Services.AddAuthentication(options =>
    {
        // JwtBearer validates the token. The MCP SDK's scheme sends the challenge: a 401 whose
        // WWW-Authenticate header points the client at the protected resource metadata.
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        // Keycloak's signing keys and issuer come from the realm's OIDC discovery document.
        options.Authority = authority;

        // The token must be for this endpoint: Keycloak's audience mapper puts its URL in "aud".
        options.Audience = resource;

        // Keycloak runs on plain HTTP in development only.
        options.RequireHttpsMetadata = !builder.Environment.IsDevelopment();

        // Keep the claims as Keycloak names them (sub, scope, roles, preferred_username).
        options.MapInboundClaims = false;
        options.TokenValidationParameters.NameClaimType = "preferred_username";
        options.TokenValidationParameters.RoleClaimType = "roles";
    })
    .AddMcp(options =>
    {
        // Served at /.well-known/oauth-protected-resource/mcp (and without /mcp): it names the
        // resource and the authorization server that issues tokens for it (RFC 9728).
        options.ResourceMetadata = new()
        {
            Resource = resource,
            AuthorizationServers = { authority },
        };
    });

builder.Services.AddAuthorization();

And at the end of the file:

src/McpAuth.Server/Program.cs csharp
app.UseAuthentication();
app.UseAuthorization();

// Only signed-in users: without a valid token, the endpoint answers 401.
app.MapMcp("/mcp").RequireAuthorization();

There are two authentication schemes, with one job each:

  • JwtBearer authenticates. It reads Keycloak's discovery document and signing keys from Authority and checks every token's signature, issuer, lifetime and audience.
  • The SDK's scheme challenges. AddMcp registers a handler that validates nothing. It serves the protected resource metadata, and when a request isn't authenticated it sends the 401 with the pointer to that metadata.

Because JwtBearer isn't the challenge scheme, its own challenge never runs, and every 401 carries exactly one WWW-Authenticate header. This is also the pairing the SDK's own protected-server sample uses.

Check it with the same curl as before:

text
HTTP/1.1 401 Unauthorized
Content-Length: 0
WWW-Authenticate: Bearer resource_metadata="http://localhost:5100/.well-known/oauth-protected-resource/mcp"

A made-up token gets the same answer, and so does a real token from the realm that wasn't issued for this endpoint. Only a token with the endpoint's URL in aud gets the 200. (Step 8 adds two parameters to this header.)

A few of those lines deserve a word:

  • Set Resource explicitly. Left unset, the handler derives it from the request's path. The metadata is also served at the root path, without /mcp, and there it would name http://localhost:5100 as the resource, which isn't the tokens' audience.
  • RequireHttpsMetadata is off in Development only. In Production against an HTTP Keycloak, JwtBearer refuses with "The MetadataAddress or Authority must use HTTPS unless disabled for development", so the switch can't follow you there unnoticed.
  • MapInboundClaims = false keeps the claim names as they are in the token. Otherwise sub and friends turn into long XML-era URIs and the code in step 6 gets harder to read.

Step 4: Tell clients which scopes to ask for

The metadata document from step 3 names the resource and the authorization server. Two more lines make it name the scopes and itself (step-04):

src/McpAuth.Server/Program.cs csharp
options.ResourceMetadata = new()
{
    Resource = resource,
    AuthorizationServers = { authority },
    ScopesSupported = [NoteScopes.Read, NoteScopes.Write],
    ResourceName = "MCP Auth example: notes",
};
bash
curl -s http://localhost:5100/.well-known/oauth-protected-resource/mcp
json
{
  "resource": "http://localhost:5100/mcp",
  "authorization_servers": ["http://localhost:8180/realms/demo"],
  "bearer_methods_supported": ["header"],
  "scopes_supported": ["notes:read", "notes:write"],
  "resource_name": "MCP Auth example: notes"
}

According to the specification, a client asks for the scopes named in the challenge's scope parameter if there is one, and otherwise for everything in scopes_supported. The SDK's challenge has no scope parameter, so for now this list is what clients will request. Keep it to what a client needs for normal use. The specification says a server should name the scopes in the challenge too, and step 8 adds that.

From authorization_servers the client goes on to Keycloak's own metadata, at http://localhost:8180/.well-known/oauth-authorization-server/realms/demo. It lists the authorization, token and registration endpoints and S256 among the PKCE methods, which an MCP client insists on. Nothing to build here: this step is the server saying where to go, and Keycloak answering for itself.

Step 5: Sign in from a console client

The client side shows how little a client has to know (step-05). The SDK's HTTP transport has OAuth support built in:

src/McpAuth.Client/Program.cs csharp
// Keycloak accepts any port on the loopback address for the registered
// http://127.0.0.1/callback (RFC 8252), so take a free one.
var redirectUri = new Uri($"http://127.0.0.1:{FreePort()}/callback");

var transport = new HttpClientTransport(new HttpClientTransportOptions
{
    Endpoint = endpoint,
    TransportMode = HttpTransportMode.StreamableHttp,
    OAuth = new ClientOAuthOptions
    {
        // Registered in Keycloak's realm (keycloak/realm-demo.json): a public client, no secret.
        ClientId = "mcpauth-console",
        RedirectUri = redirectUri,
        AuthorizationCallbackHandler = (context, cancellationToken) =>
            SignInInBrowserAsync(context.AuthorizationUri, context.RedirectUri, noBrowser, cancellationToken),
    },
});

await using var client = await McpClient.CreateAsync(transport, new McpClientOptions
{
    ClientInfo = new Implementation { Name = "mcpauth-console", Version = "1.0.0" },

    // Connecting includes signing in, so give the user as long as the sign-in waits (the
    // default is 60 seconds).
    InitializationTimeout = TimeSpan.FromMinutes(5),
});

The client supplies a client ID, a redirect URI and a callback. Everything in the diagram above is the SDK's work: it reads the 401, fetches both metadata documents, makes the PKCE verifier and challenge, builds the authorization URL, and after the callback exchanges the code and retries the request with the token.

The callback, SignInInBrowserAsync, is about forty lines in the repository: it listens on the redirect address with an HttpListener, opens the browser, waits for /callback, shows a "Signed in" page and hands the code back to the SDK.

This is the authorization request the SDK built for one run:

text
/realms/demo/protocol/openid-connect/auth
  client_id             = mcpauth-console
  redirect_uri          = http://127.0.0.1:41479/callback
  response_type         = code
  code_challenge        = Dp4hpXLga5yGhWRug-_9GFY-5GLuchXWsqLKOskSCV4
  code_challenge_method = S256
  state                 = 811UPMkPT5riwpYMsRHPwPmotwMIM6zRz0T4wU6NlMU
  resource              = http://localhost:5100/mcp
  scope                 = notes:read notes:write offline_access

After the login page, Keycloak asks the user what the client may do, in the words the realm file gave each scope:

Keycloak's consent page in the MCP Auth demo realm, "Grant Access to MCP Auth console client": it lists Add notes for you, Your username and name, Read your notes and Stay signed in (offline access), above Yes and No buttons
The consent page, with the texts from the realm file

The offline_access trap

Look at the last line of that request. Nobody asked for offline_access: the SDK adds it whenever the authorization server lists it among its scopes, and Keycloak always does. The specification allows clients to do this, and Claude Code and VS Code do the same. It cost three errors in a row.

  1. The first sign-in came back with error=invalid_scope and the description Invalid scopes: notes:read notes:write offline_access. The client wasn't allowed offline_access. Keycloak's message lists every requested scope, not only the one it objects to.
  2. Adding the scope to the client's optional scopes did nothing, and Keycloak's log said Referenced client scope 'offline_access' doesn't exist. Keycloak creates its built-in offline_access scope only after it has imported the clients. The realm file has to define the scope itself.
  3. Then the sign-in worked, the client printed "Signed in", asked to sign in a second time and finally threw System.TimeoutException: Initialization timed out. Keycloak's log had the cause: CODE_TO_TOKEN_ERROR ... reason="Offline tokens not allowed for the user or client". Offline tokens need the user to hold the offline_access role, and with full scope off the scope has to map to that role. That's the third line of the scopeMappings shown in step 2, which the realm file gains in this step.

The third one is worth remembering beyond Keycloak: the SDK doesn't surface a failed code exchange. It starts the authorization over, which looks like a loop. When a client asks to sign in twice, read the authorization server's log.

Step 6: Authorize each tool

Authentication says who is calling. What they may do is in the token's scope claim, and each tool checks it (step-06). The tools read the user from the current request through IHttpContextAccessor:

src/McpAuth.Server/NoteTools.cs csharp
[McpServerTool(Name = "add_note", Title = "Add a note", ReadOnly = false, Destructive = false, Idempotent = false)]
[Description("Adds a note in the signed-in user's name and returns it. Needs the notes:write scope.")]
public Note AddNote([Description("The note's text: 1 to 500 characters.")] string text)
{
    Require(NoteScopes.Write, "add notes");
    text = text?.Trim() ?? "";
    if (text.Length is 0 or > 500)
    {
        throw new McpException($"text must be 1 to 500 characters; this one has {text.Length}.");
    }

    return notes.Add(User.Identity?.Name ?? "(unknown)", text, time);
}

// A refusal the model can act on: what's missing, why, and what to do instead.
private void Require(string scope, string action)
{
    var user = User;
    var scopes = NoteScopes.Of(user);
    if (!scopes.Contains(scope))
    {
        throw new McpException(
            $"{user.Identity?.Name} may not {action} with this token: it needs the {scope} scope and has "
            + $"{(scopes.Count == 0 ? "none" : string.Join(", ", scopes))}. Keycloak grants {scope} only to users "
            + $"with the matching role who allow it when signing in. Don't retry; tell the user.");
    }
}

NoteScopes.Of splits the scope claim, which is one space-separated string. An McpException reaches the client as a tool result with isError set and its message intact; any other exception becomes a generic error. The reader of that message is a language model, so it says what is missing, why, and what to do next.

Run the client as alice, as bob, and as alice with --read-only, which asks Keycloak for notes:read only. This is bob (output trimmed and wrapped):

bash
dotnet run --project src/McpAuth.Client -- --add "Bob was here."
text
whoami:
{"user":"bob",…,"scopes":["notes:read","profile","offline_access"],"roles":["notes-reader","offline_access"],…}

add_note:
  refused: An error occurred invoking 'add_note': bob may not add notes with this token: it needs the
  notes:write scope and has notes:read, profile, offline_access. Keycloak grants notes:write only to users
  with the matching role who allow it when signing in. Don't retry; tell the user.

Read-only alice gets the same refusal for a different reason:

alice bob alice, --read-only
The client asks for notes:read notes:write notes:read notes:write notes:read
The user's roles reader, writer reader reader, writer
Notes scopes in the token notes:read notes:write notes:read notes:read
add_note works refused refused

Both refusals were decided before the token was issued. The tool only reads the result.

A few design decisions in this step:

  • Scopes, not roles. Because each scope maps to a role in Keycloak, the scope claim already combines what the user may do with what they allowed this client. With an identity provider that doesn't downscope like this, check both: the role says what the user may do, the scope what they delegated.
  • Tool annotations aren't a guard. ReadOnly and Destructive are hints that a client may show or ignore. On another server of mine, Claude Code ran a tool annotated as destructive without asking. What a token may do has to be enforced on the server.
  • Refuse, hide or challenge? The SDK can also hide tools from users who may not call them, with AddAuthorizationFilters() and [Authorize] on the tool. The example keeps add_note visible and refuses with a message, so the model can tell the user why it can't add a note. The specification suggests a third way for a missing scope: a 403 with error="insufficient_scope", so that the client can ask the user for more. The SDK has nothing on the server side for that yet (issue #1482 asks for it), and here it couldn't help. Every client already asks for both scopes, so a missing one means that the user lacks the role, like bob, or that the client chose not to ask, like read-only alice. A 403 would only send bob through the sign-in again for nothing.
  • A refusal looks like a crash in the server's log. The SDK logs every exception a tool throws at error level, as an "unhandled exception" with a stack trace, and that includes a deliberate McpException. The client still gets the message. If the noise bothers you, return a CallToolResult with IsError = true instead of throwing.
  • Tell the client who it works for. The server's instructions are built per request and name the user and what the token allows: "You work for bob (Bob Reader) ... This token lets you read notes (list_notes) but not add them: add_note will be refused, so tell the user instead of trying." A model that knows this up front doesn't have to learn it from refusals.

Step 7: Real clients: Claude Code and VS Code

The console client had a client ID waiting for it in the realm. Real MCP clients arrive with nothing (step-07). The server needs no change for them: it never learns how a client got its token.

Claude Code

bash
claude mcp add --transport http mcpauth-notes http://localhost:5100/mcp

In Claude Code, run /mcp, choose mcpauth-notes, then Authenticate. Claude Code (2.1.326 here) registers itself at Keycloak with dynamic client registration, and with Keycloak's defaults that fails:

text
Policy 'Trusted Hosts' rejected request to client-registration service. Details: Host not trusted.

Keycloak's default policy for anonymous registration checks the host that sends the request against a list of trusted hosts, and the list is empty. From the container's side, the sender isn't even your machine, it's the container network's gateway. The realm file changes the policy to look at where the client wants to be redirected instead:

keycloak/realm-demo.json json
{
  "name": "Trusted Hosts",
  "providerId": "trusted-hosts",
  "subType": "anonymous",
  "config": {
    "host-sending-registration-request-must-match": ["false"],
    "client-uris-must-match": ["true"],
    "trusted-hosts": ["localhost", "127.0.0.1"]
  }
}

Anyone may register a client, but only one whose redirect URIs point at the local machine. That is the narrow fix. Switching the policy off would let anyone register a client that redirects anywhere.

Importing one registration policy drops the other nine. Keycloak has ten default client registration policies, and a realm import that lists any of them replaces them all. The realm file lists all ten for that reason. If you leave out "Consent Required" and "Full Scope Disabled", a self-registered client skips the consent page and gets every role mapping, and nothing warns you.

With the policy in place, Claude Code registered a public client named "Claude Code (mcpauth-notes)" with one redirect URI on http://localhost, and the other default policies gave it consent, full scope off and the realm's default scopes. It ended up with exactly what the console client has: the same consent page, the same audience, the same downscoping for bob. Its whoami showed alice, the client's generated ID and both scopes, and a note it added arrived in alice's name.

One caveat about this route. The current MCP specification deprecates dynamic client registration in favour of Client ID Metadata Documents, where the client ID is an HTTPS URL that the authorization server fetches. Registration remains in the specification for authorization servers that don't support the newer way. In Keycloak 26.8 that support is an experimental feature, so the example uses what works with a stock Keycloak today.

VS Code

VS Code (1.146 here) reads the server from .mcp.json at the repository's root. Older versions use .vscode/mcp.json, with "servers" in place of "mcpServers":

.mcp.json json
{
  "mcpServers": {
    "mcpauth-notes": { "type": "http", "url": "http://localhost:5100/mcp" }
  }
}

Its registration can't pass a localhost-only policy. It always registers a redirect URI on vscode.dev next to the loopback one, and names https://code.visualstudio.com as the client's home page. Keycloak checks both against the trusted hosts and says no, and VS Code reports that as missing support:

A Visual Studio Code dialog titled "Dynamic Client Registration not supported": it offers to continue with a client ID entered by hand and lists the redirect URIs http://127.0.0.1:33418 and https://vscode.dev/redirect, with Copy URIs & Proceed and Cancel buttons
VS Code after Keycloak refused its registration

There are two ways to let it in. You can add vscode.dev and code.visualstudio.com to the trusted hosts, and then the rule no longer means "this machine only". Or you give VS Code a client of its own, which is what the realm file does: mcpauth-vscode, a public client with the same settings as the console client's. Choose Copy URIs & Proceed, enter mcpauth-vscode and leave the secret empty.

The redirect URIs took a second try. VS Code doesn't use the address its dialog lists: it sends a trailing slash and, when it signs in, a random port. Keycloak compares redirect URIs exactly, apart from the loopback port, so the client has http://127.0.0.1/ and https://vscode.dev/redirect. If you mistype the client ID, VS Code keeps it and retries with it; Authentication: Remove Dynamic Authentication Providers in the Command Palette makes it forget.

Step 8: Harden it

The example works now. This step adds what a server that others might copy should have (step-08). The order of the middleware matters as much as its content:

csharp
app.UseRateLimiter();            // 1. turn floods away before any token is parsed
app.Use(/* Origin check */);     // 2. refuse web pages that aren't on the list
app.UseCors();                   // 3. let the allowed pages read what they need
app.Use(/* the challenge */);    // 4. name the scopes, and tell "no token" from "bad token"
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization();

Origin and Host

The specification's Streamable HTTP page says that servers must validate the Origin header of incoming connections, and answer 403 to one that is present and not allowed. It protects against DNS rebinding, where a web page reaches a server on your machine through your own browser. The SDK doesn't make this check, and that is a decision, not an oversight: its maintainers leave it to ASP.NET Core's host filtering and CORS. The example uses both, and adds the specification's check on top with a small middleware:

src/McpAuth.Server/Program.cs csharp
app.Use(async (context, next) =>
{
    var origin = context.Request.Headers.Origin.ToString();
    if (origin.Length > 0 && !allowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase))
    {
        app.Logger.LogWarning("Refused a request from origin {Origin}; allowed: Mcp:AllowedOrigins.", origin);
        context.Response.StatusCode = StatusCodes.Status403Forbidden;
        return;
    }

    await next(context);
});

Requests without an Origin header pass. Desktop and command-line clients send none, and neither Claude Code nor VS Code was ever refused. Host filtering is what actually stops a rebinding page, which reaches the server under its own host name: "AllowedHosts": "localhost;127.0.0.1;[::1]" in appsettings.json refuses a request that arrives under any other name. It matters for a second reason. The SDK builds the metadata address in the challenge from the request's Host header, so without the filter a caller could choose what that address says.

CORS, with two lines that are easy to get wrong

Browser-based clients need CORS, for the endpoint and for the metadata:

src/McpAuth.Server/Program.cs csharp
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
    .WithOrigins(allowedOrigins)
    .WithMethods("POST", "GET")
    .WithHeaders("Authorization", "Content-Type", "Accept", "Mcp-Protocol-Version", "Mcp-Method", "Mcp-Name")
    .WithExposedHeaders("WWW-Authenticate")));

The request headers. Since the 2026-07-28 revision, every request carries its method in an Mcp-Method header, and a tool call carries the tool's name in Mcp-Name. The SDK's server refuses a current-revision request without Mcp-Method. My first policy didn't list the two. The preflight still answered 204, only without those names in it, so a browser would not have sent the request, and curl showed nothing wrong. The CORS sample in the SDK's documentation doesn't list them either, so don't copy it as it is. CORS has no pattern for header names: if a tool mirrors parameters into Mcp-Param- headers, each of them has to be listed. No tool here does.

The exposed header. Without WWW-Authenticate among the exposed headers, the preflight passes and the request returns its 401, but the browser hides the challenge from the page. A browser client then never finds the metadata, and nothing in the server's log tells you why.

The server is stateless, so the policy needs nothing for sessions. GET is there for clients on older revisions, which may try to open an event stream and expect the 405 they get.

Your server's CORS is only half of a browser client's way in. Keycloak refused client registration from a web page with {"error":"Invalid origin"} and no CORS headers, so the page saw only a failed fetch. With a pre-registered public client that lists the page's address under Web origins, the whole path worked, from sign-in to a tool call. And a page on a public site that calls a server on localhost first has to get past Chrome's Local Network Access permission, before CORS even applies.

Rate limiting comes before authentication

The limiter is partitioned by client address and registered first, so a flood is refused with 429 before the server spends anything on parsing or validating tokens. Two details:

  • Limit by address, not by token. A limit per token gives every made-up token a fresh allowance.
  • It has to be a global limiter. The metadata is answered by the SDK's authentication handler, not by an endpoint, so a policy attached to MapMcp wouldn't cover it.

Behind a reverse proxy, add the forwarded headers middleware first, or every request shares the proxy's address.

Clock skew, and what it uncovered

Keycloak's access tokens live five minutes. JwtBearer's default clock skew is also five minutes, so the tokens were accepted for ten:

src/McpAuth.Server/Program.cs csharp
options.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(30);

Tightening it exposed a difference between the clients. Claude Code renews its token ahead of expiry. VS Code renews after a 401, and with the SDK's bare challenge it failed the tool call first and only the next call worked. A bare challenge means "sign in". For a token that was sent and rejected, RFC 6750 has error="invalid_token", which means "renew it".

The SDK's challenge carries the metadata address and nothing else, and its handler has no event to hook. That is the same in 2.3.1 and 2.4.0. So a middleware completes the challenge, with the error code and with the scope parameter that step 4 promised:

src/McpAuth.Server/Program.cs csharp
var challengeScope = $", scope=\"{NoteScopes.Read} {NoteScopes.Write}\"";
app.Use(async (context, next) =>
{
    context.Response.OnStarting(() =>
    {
        var challenge = context.Response.Headers.WWWAuthenticate.ToString();
        if (context.Response.StatusCode == StatusCodes.Status401Unauthorized
            && challenge.StartsWith("Bearer ", StringComparison.Ordinal)
            && !challenge.Contains("scope=", StringComparison.Ordinal))
        {
            context.Response.Headers.WWWAuthenticate = challenge + challengeScope
                + (context.Request.Headers.Authorization.Count > 0 ? ", error=\"invalid_token\"" : "");
        }

        return Task.CompletedTask;
    });

    await next(context);
});

A request without a token now gets the first of these headers, and a request with a rejected token the second:

text
WWW-Authenticate: Bearer resource_metadata="…", scope="notes:read notes:write"
WWW-Authenticate: Bearer resource_metadata="…", scope="notes:read notes:write", error="invalid_token"

With the error code, VS Code recovers by itself. This is one such moment from the server's log and Keycloak's events, six minutes after the token had expired:

Time What happened
00:35:28.129 VS Code sends the expired token. The server answers 401 with error="invalid_token".
00:35:28.191 Keycloak logs a successful refresh for mcpauth-vscode.
00:35:28.244 VS Code repeats the request with the new token, and list_notes succeeds.

That is 115 milliseconds, and the user sees nothing. I saw this recovery in two runs and the failed call without the error code in one, all on VS Code 1.146, so take it as an observation about that version. The general point holds: a generous clock skew hides what your clients do with expired tokens.

In the realm: rotation and PKCE for everyone

Two settings in the realm file complete the step.

Refresh tokens work once (revokeRefreshToken: true, refreshTokenMaxReuse: 0). Every client here is a public client, and OAuth 2.1 wants their refresh tokens rotated or bound to the sender. A used refresh token that shows up again is treated as stolen, and Keycloak ends that session. Claude Code and VS Code both renew their tokens under rotation without trouble.

PKCE is required for every public client, through a client policy rather than a per-client setting, because clients that register themselves don't set it:

keycloak/realm-demo.json json
"clientProfiles": {
  "profiles": [
    {
      "name": "require-pkce",
      "description": "Authorization code requests must carry a PKCE S256 code challenge.",
      "executors": [{ "executor": "pkce-enforcer", "configuration": { "auto-configure": "true" } }]
    }
  ]
},
"clientPolicies": {
  "policies": [
    {
      "name": "public-clients-use-pkce",
      "description": "Every public client, including ones that registered themselves, must use PKCE S256.",
      "enabled": true,
      "conditions": [{ "condition": "client-access-type", "configuration": { "type": ["public"] } }],
      "profiles": ["require-pkce"]
    }
  ]
}

Finally, the server refuses to start outside Development when Auth:Authority or Auth:Resource isn't an https URL. Tokens travel in a header, and plain HTTP is for localhost only.

Step 9: Test the sign-in end to end

A flow with a browser, three processes and two users breaks quietly, so the example has an end-to-end test project with TUnit and Playwright (step-09). It runs against the running stack, starts the console client with --no-browser, and signs in on Keycloak's real login and consent pages:

bash
dotnet build
pwsh artifacts/bin/McpAuth.Screens/debug/playwright.ps1 install chromium   # once
dotnet test --project tests/McpAuth.Screens

The tests cover alice adding a note, bob being refused, bob signing in after alice in the same browser, read-only alice, both forms of the challenge, the metadata, the Origin check, and CORS from a real page in the browser. They also took the Keycloak screenshots in this article.

One snippet is worth copying. After the login button, either the consent page appears or, when consent is remembered, the client's "Signed in" page. The test waits for whichever comes, without a sleep:

tests/McpAuth.Screens/Stack.cs csharp
// Keycloak asks for consent once per user and client; after that it goes straight back.
var allow = page.GetByRole(AriaRole.Button, new() { Name = "Yes" });
var done = page.GetByText("Signed in.");
await Assertions.Expect(allow.Or(done)).ToBeVisibleAsync();
if (await allow.IsVisibleAsync())
{
    await allow.ClickAsync();
}

Three things to know when you write tests like these:

  • Keycloak doesn't keep the scopes in a fixed order between tokens, so compare sets, not strings.
  • A test that needs the consent page has to revoke the consent first, which the project does through the admin API.
  • Don't serve the test page for CORS through Playwright's routing. With request interception on, the browser accepted every preflight, and my CORS tests passed against the broken policy too. The page now comes from a real local server.

What's dev-only

Everything above runs on plain HTTP on one machine, with passwords in a public repository. This is what a real deployment changes:

Here In production
Keycloak start-dev: HTTP, an in-memory database, the realm imported at every start start with TLS, a real database, a managed realm, the hostname set
Users and the admin with passwords in the repository real accounts or an identity provider; admin credentials from a secret store
The server on plain HTTP, RequireHttpsMetadata off in Development HTTPS, and forwarded headers behind a proxy
AllowedHosts localhost; allowed origins: the MCP Inspector your host name; only the web clients you serve
Anyone may register a client whose redirect URIs are on localhost Client ID Metadata Documents, registration access tokens or pre-registered clients only, and a cleanup of unused clients
Notes in memory a database
Keycloak's events on the console events stored and watched: a reused refresh token is a theft signal

Going further

  • Client ID Metadata Documents instead of registration, once your authorization server supports them in a stable release. That is where the specification is heading.
  • Step-up authorization: name only notes:read in the first challenge, and answer a tool that needs more with 403 and error="insufficient_scope". That is where the 403 pays off. The SDK's client handles such a challenge; the server's side is yours to write for now.
  • Token exchange (RFC 8693) when a tool calls another API. The specification forbids passing the client's token on: get one for the downstream API instead.

The short version

  • The MCP server is a resource server. JwtBearer validates the tokens, the SDK's AddMcp sends the challenge and serves the metadata, and RequireAuthorization() closes the endpoint.
  • The token must be for this server. With Keycloak, an audience mapper on the scopes puts the endpoint's URL into aud.
  • Let the authorization server decide who gets which scope, and let each tool check the scope it needs.
  • Expect offline_access from every client, and read the authorization server's log when a sign-in loops.
  • Complete the challenge: the scopes on every 401, and error="invalid_token" when a token was rejected.
  • Check Origin and filter hosts. For browsers, allow Mcp-Method and Mcp-Name and expose WWW-Authenticate.
  • Limit by address before authentication, and keep the clock skew small.

The code is at github.com/gergodrazsdik/example-aspnet-mcpauth, under the MIT No Attribution licence: copy what you need. It's a companion to this article, not a maintained project, so it isn't open for issues, but you're welcome to fork it.

Tags

About Gergő Drazsdik

Software architect and developer based in Budapest, Hungary. I've spent more than 18 years building .NET systems and the infrastructure they run on. These days a growing part of my work is about how AI fits into all of that, both as something we build and as a tool we build with.

Comments

No comments yet.

Back to the top