How to Secure Remote MCP Servers in ASP.NET Core 10 Using C#, OAuth 2.1 and JWT Authentication – Complete Guide (2026)
How to Secure Remote MCP Servers in ASP.NET Core 10 Using C#, OAuth 2.1 and JWT Authentication – Complete Guide (2026)
A remote MCP server can expose useful tools to multiple applications. It can also turn a leaked token or a broad service identity into access to actions the caller never intended to authorize. The server needs to establish who sent the request, whether the token was issued for this MCP endpoint, and whether that identity may use the requested tool.
How do you secure a remote MCP server in ASP.NET Core 10? Put the Streamable HTTP endpoint behind HTTPS and JWT bearer authentication. Publish OAuth Protected Resource Metadata and advertise its URL in authentication challenges. Accept only tokens issued by a trusted authorization server for your exact resource. Enforce a scope for the MCP endpoint and stricter policies for privileged tools.
This guide implements a small catalog server and a C# client. Keycloak 26.8.1 issues access tokens. ASP.NET Core validates them using issuer discovery and signing keys. The official MCP C# SDK 2.3.1 handles MCP. The lab has a read-only status tool and a privileged publish preview that changes no data.
The three participants in MCP authorization
| Participant | Responsibility |
|---|---|
| MCP client | Discover the resource and its authorization server, select the grant and request the intended resource and scopes. Send an access token on each protected request. |
| Keycloak authorization server | Authenticate the user or client, apply grants and consent policies, and issue a signed access token with the permitted audience and scopes. |
| ASP.NET Core MCP protected resource | Publish metadata, validate the bearer token, enforce endpoint and tool policies, and return the appropriate challenge on failure. |
Authentication establishes a principal from the validated token. Authorization answers whether that principal may perform the operation. A valid read token can call the catalog status tool. A publish preview still requires the publish scope.
Stdio usually runs a trusted executable under a local operating-system identity, with credentials supplied through an appropriate local mechanism. An HTTP deployment crosses a network boundary and must defend the endpoint, redirects, metadata, tokens and tool actions. Local HTTP is still a browser-reachable network service. Limit the listener, validate Host and Origin, and use authentication. Review the MCP authorization specification.
OAuth 2.1 status and the MCP authorization flow
As of 5 November 2026, the IETF Datatracker lists OAuth 2.1 as active Internet-Draft draft-ietf-oauth-v2-1-17. The July 2026 MCP specification references revision -13 in its standards list. Read the requirements in the applicable MCP revision. OAuth 2.0 and its published extensions already define the mechanisms used here. See the OAuth 2.1 draft, OAuth 2.0 framework and OAuth security best current practice.
For an interactive client, use authorization code with PKCE S256. The client generates a verifier and sends its SHA-256 challenge to the authorization server. It associates the browser redirect with the original transaction using state and checks the authorization response issuer against the issuer selected at discovery. The client then exchanges the one-time code and the verifier at the token endpoint. Use exact registered redirects, with the applicable native loopback exception where supported. Keep implicit and password grants out of this design. See RFC 7636 and RFC 9207.
For service-to-service calls, a confidential client may authenticate with the client credentials grant if the authorization server and deployment support it. The resulting identity is the application or its service account. It cannot represent an end user’s consent or tenancy on its own. The executable lab uses this grant so readers can repeat the HTTP tests without automating a login page. The realm also includes a separate public client for an interactive code-and-PKCE test.
The MCP client sends the resource identifier in the authorization and token requests where applicable. In this lab it is exactly https://localhost:7443/mcp. The authorization server translates the request into an audience restriction. The API then checks that audience. An OAuth scope describes permission within the target resource. It does not replace audience validation. See RFC 8707.
Protected Resource Metadata and issuer discovery
The server exposes an anonymous JSON document at /.well-known/oauth-protected-resource/mcp. Its resource is the canonical endpoint, and authorization_servers contains the exact Keycloak realm issuer URL. Clients can read the resource_metadata parameter on the Bearer challenge first and use the prescribed path and root fallback locations when the parameter is absent. The metadata URL is built from trusted configuration.
After finding an issuer, the client tries the MCP specification’s OAuth Authorization Server Metadata and OpenID Connect Discovery locations. Path-based issuers have specific path insertion and appending rules. Keycloak exposes the realm’s OIDC discovery document at /realms/mcp-lab/.well-known/openid-configuration. Validate the returned issuer string against the selected issuer before trusting endpoints or exchanging credentials. Treat remote metadata as an outbound request boundary. See MCP discovery, RFC 9728 and RFC 8414.
Client registration is separate. This controlled lab uses pre-registered clients. For dynamically introduced clients, review the current MCP Client ID Metadata Document guidance and restrict metadata fetch destinations. Legacy dynamic registration has compatibility considerations. A complete MCP client needs discovery, registration strategy, OAuth transaction security, and token lifecycle handling. The short C# lab runner receives a token that was already obtained from Keycloak.
What JWT bearer validation checks
A signed JWT normally has a header, payload and signature. Base64url decoding reveals the payload and cannot establish authenticity. The middleware uses Keycloak’s public signing keys and a configured RS256 algorithm allowlist. It verifies the token signature, issuer, audience, expiration and validity window. Signing-key rollover is handled through issuer metadata and key refresh. A caller cannot choose its own trusted key by supplying a URL in a token.
The sample uses exact audience matching, requires expiration, and allows 15 seconds of clock skew. It also checks Keycloak’s access-token payload marker typ=Bearer. That marker is issuer-specific. For a different issuer, use its documented token-class checks and algorithms. An OpenID Connect ID token is issued to the client application as a login assertion and should never be used as the MCP API access token. Opaque tokens require a different validation design, typically issuer introspection. See Microsoft’s JWT bearer guide and RFC 8725.
Set up the two .NET 10 projects
Install a supported .NET 10 SDK, Keycloak 26.8.1 with JDK 21, Python 3 for the realm configuration helper and curl or Postman. Use two sibling projects and keep the local issuer and MCP server on different HTTPS ports. The Web SDK supplies ASP.NET Core hosting. JwtBearer supplies token validation. The MCP ASP.NET Core package adds server hosting and authorization filters, and the Core package supplies the client API.
See MCP SDK release 2.3.1, MCP ASP.NET Core on NuGet, MCP Core on NuGet, and JwtBearer on NuGet. If you need the basic MCP server pattern or more JWT middleware context, start with Build an MCP Server in C# or JWT Authentication in ASP.NET Core 10.
Configure Keycloak as the external authorization server
Use a fresh local Keycloak distribution so a realm import is applied. The script below creates the realm and four registrations. The resource client maps the MCP URL using resource_url. The three OAuth clients have an audience mapper targeting that resource client. Keycloak 26.8.1 marks resource-indicators experimental. Enable the documented feature for this lab and assess support before deploying it. A production issuer must provide the audience binding and client interoperability your system depends on. See the Keycloak MCP integration guide.
| Registration | Access |
|---|---|
catalog-mcp |
Resource registration with the canonical MCP URL. |
mcp-reader |
Confidential service account with catalog:read. |
mcp-publisher |
Separate confidential service account with catalog:read and catalog:publish. |
mcp-desktop |
Public authorization code client, PKCE S256, read scope, and an exact loopback callback. |
Save this as make-realm.py beside the projects. It uses separate secrets from local environment variables. The generated realm file contains those secrets. Keep the file in a private directory and out of source control.
The following commands assume a Bash terminal, OpenSSL and an extracted Keycloak directory. Run them from the parent directory containing the projects. Set KC_DIR to the absolute Keycloak directory. Generate a local TLS certificate for localhost with a DNS SAN. Trust it in your development client and the issuer-metadata backchannel. On Linux, the example creates a local CA bundle. On Windows, use your OS certificate trust store or a trusted development CA. Keep development private keys on the development machine.
Run Keycloak in another terminal using the same project directory. Configure a local bootstrap admin via Keycloak’s supported method if you want to create a test user for the interactive flow. Use HTTPS for all requests in the exercise. Keycloak development mode may also start a loopback HTTP listener, so keep the entire instance private.
Verify the realm discovery document and its issuer before continuing. Existing realms may be skipped during startup import. Use the Admin Console to review clients and permissions if rerunning the lab. The scope assignments here belong to separate pre-registered lab identities. In a production system, grant privileged scopes only to explicitly entitled users or clients. See Keycloak server administration and the Keycloak OpenJDK setup guide.
Implement JWT authentication and the MCP endpoint
Set SecureMcp/appsettings.json to the exact configured issuer and resource URL. Do not add client credentials to this file. The server validates tokens using public keys, so it needs no OAuth client secret for this role.
Replace SecureMcp/Program.cs with the complete server configuration. Middleware checks HTTPS and Origin, then runs routing, authentication and authorization before dispatch. The API requires catalog:read on the MCP endpoint. A bounded, single-object JSON preflight on the protected POST path checks the actual named tool operation before it reaches the SDK. This lets the server issue a real HTTP 403 Bearer scope challenge for the privileged tool. Routing headers alone never grant access.
Add CatalogTools.cs. The SDK’s authorization filters apply policy at the tool handler as well. If the handler is reached by a path the preflight did not anticipate, the SDK policy remains the defense at execution. Keep this layer even when discovery hides restricted tools. Tool lists change by identity and should never be cached across callers without the appropriate cache key and policy.
The preflight parses the body twice overall, once here and again in the SDK. The 64 KiB server limit bounds this demo. Duplicate properties and non-object JSON are rejected. If you add methods that invoke privileged tools indirectly, review the HTTP challenge mapping and enforce the underlying operation’s policy on each path. A real publishing tool would also verify ownership and tenancy for the specific catalog, check approval where required, and use idempotency or reconciliation for uncertain writes.
Understand 401, 403 and Bearer challenges
| Case | HTTP response |
|---|---|
| Missing bearer token | 401 with Bearer, resource metadata and the entry scope. |
| Expired, malformed or wrong-audience token | 401 with error="invalid_token" and resource metadata. |
| Valid token without the entry scope | 403 with error="insufficient_scope" and catalog:read. |
Read token calling publish_preview |
403 with both required scopes and metadata. |
| Untrusted browser Origin | 403 from the transport boundary. |
| Authorized catalog operation | The SDK returns the MCP result. |
When a user-facing client receives an insufficient-scope challenge, it can request an updated token with the required scope set subject to the issuer’s policy and the user’s approval. The new request normally preserves scopes the client previously requested. A service client can stop and ask an operator to grant the correct identity access. Adding an arbitrary requested scope cannot create a permission the issuer has not granted. See MCP authorization errors and RFC 6750.
Run the protected MCP server and client
Start the server in the terminal with the trust bundle configured. Read the password used to create the development PFX into a process environment variable. Kestrel uses the certificate for HTTPS and JWT bearer middleware trusts the issuer through the development trust bundle.
Use curl or Postman to confirm discovery and inspect the unauthenticated challenge. POST is the protocol entry point. The missing-token test is denied before JSON-RPC parsing. Keep certificate verification enabled.
After inserting the console client Program.cs below, run dotnet build SecureMcp.Client. Next request a Keycloak access token using client credentials. Use an environment that keeps secrets out of command logs and tracing. In each client terminal on Linux, export SSL_CERT_FILE to the absolute path of the development trust bundle before running the C# client. The example passes the form to curl on stdin and extracts only the access token into a shell variable. The example assumes the generated hex secrets and a fixed resource. If adapting it to arbitrary values, form-encode them. In another terminal, load the same test credentials into its private environment. Use the reader identity first.
Replace SecureMcp.Client/Program.cs with this code before running the client. It sends the access token to a fixed endpoint and refuses redirects. It is an authenticated SDK request runner for the lab. Use an OAuth-capable client in a user-facing app and manage refresh and storage through its supported flow. The token expires after about a minute in this realm. Build first and use --no-build if you want more time to run checks.
The reader should print Catalog is online.. Run with -- --publish using the reader token to exercise the 403 path. Mint a new token with client_id=mcp-publisher and the publisher secret and repeat the publish call. A successful preview prints Publish preview authorized. No catalog data changed.. Stop reusing the secret-bearing environment when you finish.
Inspect a scope denial over HTTP
Use Postman with the reader token in its local secret environment. Send POST to https://localhost:7443/mcp with Content-Type: application/json and Accept: application/json, text/event-stream. For a modern July 2026 request, include MCP-Protocol-Version: 2026-07-28, Mcp-Method: tools/call, and Mcp-Name: publish_preview. Use this request body.
The reader request produces HTTP 403 with error="insufficient_scope", scope="catalog:read catalog:publish", and the protected resource metadata URL in the Bearer challenge. Repeat with a missing token and then the literal not-a-jwt as a bearer value. Both should return 401, with the malformed value labeled invalid_token. For the expiry check, retain the original reader token until its expiration plus the 15-second configured skew has passed. For an audience mismatch, this Keycloak lab can issue a service token without the resource indicator that has a different audience. Inspect aud locally before relying on it as a negative test. Never paste a token into a public decoder.
Try an interactive authorization code flow
Create a Keycloak test user and use a client configured with the pre-registered mcp-desktop ID. Configure its loopback listener at http://127.0.0.1:8765/callback or update both the registration and client to the same exact callback. Use the realm discovery document for the authorization and token endpoints. Generate a fresh verifier, S256 challenge and state per attempt. Include the resource URL and request catalog:read. On callback, compare state and issuer to the stored transaction, then exchange the code, verifier, matching redirect URI, client ID and resource at the discovered token endpoint. The public client has no secret. Test with a client that supports the required issuer binding and resource parameters. Generic OAuth tools may require explicit additional parameters or lack the checks needed for a production MCP client. Interactive consent and browser redirects are separate from the automated service-account tests below.
Verification record. The server and client built without warnings using .NET SDK 10.0.100. I ran the server and Keycloak 26.8.1 on loopback HTTPS with a trusted local certificate. The checks covered protected resource metadata, missing token, malformed token, wrong audience, insufficient scope, an unexpected Origin, and successful read and publish-preview tool calls. An additional expiry check used the original issuer-signed reader token after its expiration and clock skew. The interactive authorization-code flow and production reverse-proxy setup were not exercised.
Threat model and production checklist
| Threat | Control |
|---|---|
| Token minted for another API | Validate issuer, exact MCP audience, expiration, signature and token class. |
| Confused deputy | Check the caller’s entitlement per operation and acquire separately scoped downstream credentials. |
| Token passthrough | Do not forward an inbound MCP token to another API. Obtain an appropriate downstream token with a distinct audience, using a trusted delegation mechanism where applicable. |
| Replay of stolen bearer token | Enforce TLS, minimize token life, avoid logs, and consider sender-constrained tokens where your full stack supports them. |
| DNS rebinding or hostile browser request | Restrict Host, reject untrusted Origin, bind local services narrowly and require auth. Configure CORS only when a browser client needs cross-origin access. |
| SSRF through discovery, redirects or tool input | Validate endpoint and issuer selection, restrict egress, check resolved addresses and redirects, and reject private or link-local destinations unless explicitly approved. |
| Overprivileged tool or cross-tenant access | Separate read/write identities and scope checks, then enforce object-level authorization against server-owned records. |
Use a trusted reverse proxy configuration. If TLS terminates at the proxy, apply forwarded headers before HTTPS enforcement and accept them only from known proxies or networks. Set stable public resource and metadata URLs from configuration. Audit resource IDs and allowed host names before rollout. Keep authentication events structured and log the failure category and a correlation ID. Exclude bearer tokens, client secrets, PKCE verifiers, authorization codes and unnecessary tool arguments. Protect private keys and credentials with a managed secret store, rotate them, and test key rollover and clock synchronization. See ASP.NET Core proxy guidance and Keycloak production configuration.
Put request body, concurrency and time limits at the service and proxy boundary. Rate limit after authentication where possible by client or principal, with an outer limit for unauthenticated traffic. Alert on repeated invalid-token and insufficient-scope failures, issuer discovery failures, and signing-key rotation issues. Use short access tokens and plan incident response and revocation for the grant and service identity. JWT validation by itself does not guarantee immediate revocation of an already issued access token.
Troubleshooting and FAQs
| Symptom | What to check |
|---|---|
Keycloak returns invalid_target |
Confirm the resource indicator exactly matches the resource client’s URL and that the requesting client may target it. |
Token endpoint returns invalid_client |
Check the client authentication method, active credentials and service account settings. |
| .NET returns 401 even though token issuance succeeded | Check local CA trust, metadata issuer, exact audience, signing algorithm, expiration and token class. |
| An operation returns 403 | Check the server’s challenge and compare the required scopes with the token’s actual claims. |
| Postman works but a browser fails | Validate Origin and configure narrowly scoped CORS if intentional cross-origin calls are required. |
| Client expects a session or sends legacy SSE requests | Verify SDK and protocol versions and select Streamable HTTP for this endpoint. |
Is adding JwtBearer enough to secure MCP?
JwtBearer validates an incoming access token. MCP interoperability also depends on discoverable protected resource metadata, suitable HTTP challenges, a compatible issuer and client OAuth behavior. Each tool still needs an authorization decision.
Can I use the same access token for several MCP servers?
Use a token bound to the specific resource you intend to call. Each server should validate that it is an intended audience and enforce its own authorization policy. Separate identities or grants further limit the effect of token theft.
Do tools need their own scopes?
Use separate scopes when tools carry different privileges. A write-capable tool often also needs resource ownership, tenant checks and user approval. A tool annotation or model prompt cannot enforce these permissions.
Do I need OAuth for local stdio?
MCP’s HTTP authorization mechanism applies to HTTP transports. A stdio integration is primarily governed by local process trust, OS permissions and the credentials passed to the process.
Conclusion and further reading
Start with a read-only tool and prove that missing, malformed, expired and wrong-audience tokens are rejected. Then test a privileged tool with a read identity and a separate authorized identity. Future topics in this series could cover MCP OAuth token exchange for downstream APIs, JWT key rotation drills, and browser-based MCP discovery with hardened outbound requests.
- MCP authorization and MCP authorization server discovery
- OAuth 2.1 Internet-Draft, RFC 6749 and RFC 9700
- Bearer tokens, PKCE and issuer identification
- Resource Indicators, Protected Resource Metadata and Authorization Server Metadata
- JWT security best practices and ASP.NET Core JWT validation
- MCP C# SDK release and SDK authorization filter documentation
- Keycloak MCP integration, server administration and production deployment
- Build an MCP server in C#, JWT authentication in ASP.NET Core 10 and Global exception handling in ASP.NET Core 10
Comments
Post a Comment