Throw These 8 Tokens at Your .NET MCP Server Before Someone Else Does
Here's the cheapest security test I now run against every MCP server I build: I hand it eight access tokens it should refuse, and I count how many it accepts. The first time I did it, my support-desk MCP server was prot
Here's the cheapest security test I now run against every MCP server I build: I hand it eight access tokens it should refuse, and I count how many it accepts.
The first time I did it, my support-desk MCP server was protected the way most samples protect it: validate the JWT signature and move on. A plain signature check accepted 5 of the 8. All five were signed by our real identity provider, because one identity provider signs tokens for every app in the company.
This post is the drill itself: the eight tokens, what each one looks like, which validation setting stops it, and the shape of the xUnit test that keeps it stopped. It's not the full server build.
Tech Skill Builder is $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10. Join Tech Skill Builder. The complete, tested OAuth-protected MCP server behind this post is in there.
Does your agent also read ticket text or tool results? My LLM Data Firewall for .NET 10 is
IChatClientmiddleware that redacts PII and wraps untrusted tool results before the prompt leaves your server.
The "it works on my machine" baseline
This is roughly what a lot of quick-start code boils down to. It proves the token was signed by a key you trust, and nothing else:
// The baseline I tested against: signature only
var signatureOnly = new TokenValidationParameters
{
IssuerSigningKey = signingKey,
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = false,
};
A signature answers "did our identity provider sign this?". An MCP server needs a different answer: "was this token issued for me, by the issuer I expect, right now, as an access token?" The MCP spec is explicit that servers must only accept tokens issued for themselves.
The eight tokens
I ran each token through the signature-only check and through the real server (an in-process test host with a dev token issuer, on my machine):
| # | Token | Signature-only | Hardened server |
|---|---|---|---|
| 1 | Issued for a sibling MCP server (same IdP) | accepted | 401 |
| 2 | Audience is just the origin, not the MCP URL | accepted | 401 |
| 3 | Issuer of another tenant, same signing key | accepted | 401 |
| 4 | Expired 1 h 50 min ago | accepted | 401 |
| 5 | ID token (typ: id+jwt) replayed as an access token |
accepted | 401 |
| 6 |
alg: none, signature stripped |
rejected | 401 |
| 7 | Payload edited to upgrade the scope | rejected | 401 |
| 8 | Signed by an unknown key | rejected | 401 |
Tokens 6 to 8 are the ones everyone thinks about, and the signature check already catches them. The dangerous ones are 1 to 5: they're real tokens, correctly signed, just not meant for this server.
Tokens 1 and 2: the audience must be the exact MCP URL
A token for your CRM MCP server and a token for your desk MCP server look identical to a signature check. The audience claim is the only difference, so validate it against the exact resource URL, not the host name:
ValidAudience = resource.ResourceUrl, // e.g. https://desk-mcp.example.com/mcp, from config
This works because MCP clients request tokens with resource=<your MCP URL> (RFC 8707), so a legitimate client always gets that exact value. An "audience = host" token (number 2) fails, and so does the sibling server's token.
Token 3: pin the issuer
Multi-tenant identity providers can sign tokens for several tenants with the same key. If you don't check the issuer, any tenant's token is good enough:
ValidIssuer = resource.Issuer.TrimEnd('/'),
Token 4: lifetime is not optional
Turning off lifetime validation usually happens during debugging and never gets turned back on. Require an expiry and keep the skew small:
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.FromSeconds(30),
Token 5: an ID token is not an access token
An ID token tells a client who signed in. It was never meant to be sent to an API. It can carry the same issuer, audience and signature as an access token. The typ header is what tells them apart:
ValidTypes = ["at+jwt", "JWT"],
Tokens 6 to 8: still lock the algorithms
The signature check handles these, but I still list the algorithms I expect so nothing I didn't plan for gets negotiated:
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.EcdsaSha256, SecurityAlgorithms.RsaSsaPssSha256],
Put together, the JwtBearer registration has this shape:
.AddJwtBearer(o =>
{
o.MapInboundClaims = false; // keep "sub", "scope", "tid" as-is
o.Authority = resource.Issuer;
o.TokenValidationParameters = new TokenValidationParameters
{
// ValidIssuer, ValidAudience, lifetime, ValidTypes, ValidAlgorithms
// exactly as in the sections above
};
})
.AddMcp(o => { /* Protected Resource Metadata (RFC 9728) for clients */ });
// full registration, options validation and metadata setup in the complete project
Make the drill a test, not a one-off
A one-time check proves nothing about next month's refactor. In the project, every bad token is a row in one xUnit theory that runs against the real app in a test host:
public static TheoryData<string> BadTokens() =>
["wrong-audience", "audience-is-the-origin", "wrong-issuer", "expired",
"alg-none", "tampered", "other-key", "garbage", "id-token-typ"];
[Theory]
[MemberData(nameof(BadTokens))]
public async Task Tokens_that_are_not_for_this_server_are_rejected(string kind)
{
using var response = await factory.RpcAsync(Make(kind), ToolsListJson);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.Contains("resource_metadata", response.Headers.WwwAuthenticate.ToString());
}
// Make(kind) mints each bad token with a dev token issuer
// (wrong audience, past IssuedAt, typ id+jwt, edited payload, foreign key ...)
// -- full helper and test host factory in the complete project
(It has nine rows: the eight tokens from the table plus a string that isn't a JWT at all.) Two details I'd keep. The test hits the real HTTP pipeline, not JsonWebTokenHandler directly, so a middleware ordering mistake also fails it. And it asserts the resource_metadata hint in the 401, because that's how an MCP client discovers where to sign in.
Passing all 8 is the floor
A token that is valid for your server can still do too much. Once the drill passes, these are the next three things I check:
-
What does a read-only token see in
tools/list? With scope-based authorization filters, atickets:readtoken sees 2 of 4 tools in my server. The refund tool isn't in the model's context at all. -
What does "not enough scope" look like? An HTTP 403 with
error="insufficient_scope"and every scope the call needs lets the client step up once. A JSON-RPC "Access forbidden" doesn't. - What token goes to downstream APIs? Never the one you received. In my server, 0 of 50 billing calls carried the user's token; RFC 8693 token exchange with a cache needed 5 exchanges for 50 refunds.
Checklist
- [ ] Audience = the exact MCP resource URL, from configuration
- [ ] Issuer pinned
- [ ] Lifetime validated, expiry required, small clock skew
- [ ]
ValidTypesrejects ID tokens - [ ] Algorithms listed explicitly, signed tokens required
- [ ] One theory with every bad token, run against the real HTTP pipeline
- [ ] 401s carry
resource_metadata - [ ] Next: scope-filtered
tools/list, 403 step-up, token exchange downstream
All results are local measurements: the real app in an in-process test host, a dev token issuer and offline fakes, on my machine.
Get the complete project
The snippets above are the skeleton. The full, tested .NET 10 project is in Tech Skill Builder: an OAuth-protected MCP server built on the official MCP C# SDK with Clean Architecture layers, audience-bound JwtBearer validation, scope-filtered tools, 403 step-up challenges, RFC 8693 token exchange with caching, audit rows, the bench tool and 179 passing tests, plus a long PDF walkthrough with architecture and request-flow diagrams. It's $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10.
Worried about what your agent sends to the model, not just who calls it? The LLM Data Firewall for .NET 10 redacts PII, wraps untrusted tool results and keeps count-only audit logs.
How many of the eight would your MCP server accept today?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.