# Securing an MCP Server

## Introduction

The Model Context Protocol (MCP) lets an AI assistant work with a service's data on behalf of a user: read the tasks in a tracker, open a ticket or find a document. The service runs an MCP server that describes what it can do, and the assistant calls those tools when the user asks. Any assistant that speaks MCP works with any MCP server, with no integration built for the pair.

An MCP server that serves a user's data has to know who is asking and what that user allows. The assistant is usually made by another company, and the organization running the MCP server never signed anything with that vendor. The [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) answers this with OAuth 2.1, the IETF draft that brings together OAuth 2.0, on which OpenID Connect is built, and its security best practice: the MCP server is a protected resource, the organization's own [authorization server](https://www.abblix.com/en/docs/glossary-overview#authorization-server) issues [access tokens](https://www.abblix.com/en/docs/glossary-overview#access-token) for it, and the assistant gets a token through the [authorization code flow](https://www.abblix.com/en/docs/glossary-overview#authorization-code-flow) with [PKCE](https://www.abblix.com/en/docs/glossary-overview#pkce), with the user signing in and consenting at the authorization server.

The assistant acts for the user without holding the user's credentials: it gets a token of its own. The token names the user, so the MCP server serves that user's data, and it carries only the scopes the user consented to, names this one MCP server as its audience, and has a lifetime of its own, so withdrawing it touches nothing else the user has signed in to. The MCP server does not pass this token on to another API; it exchanges it for a token issued to that API ([below](#call-upstream-apis-with-token-exchange)). An assistant that works with no user behind it uses the [client credentials grant](https://www.abblix.com/en/docs/machine-to-machine-client-credentials) instead; this guide covers the case with a user.

This guide sets that up with Abblix OIDC Server 3.1 as the authorization server. The code comes from the [MCP server sample](https://github.com/Abblix/Oidc.Server.GettingStarted/tree/master/McpServerSample) in the Getting Started repository: `ProviderApp` is the authorization server, `McpServerApp` the MCP server, a task tracker built on ASP.NET Core and the official C# MCP SDK, and `McpClientApp` the assistant. The sample's README walks through every request and shows how to run it. This guide is the checklist behind it: what each side has to do, and the requirement each step answers. The first three sections configure the authorization server, the rest the MCP server.

## Declare the MCP server as a resource

The authorization server knows each MCP server as a resource of its tenant (one issuer with its clients and resources), with the scopes its tools use. A client names the MCP server in the `resource` parameter of its authorization and token requests, as [RFC 8707, section 2](https://datatracker.ietf.org/doc/html/rfc8707#section-2) defines, and the access token it gets carries that URI as its audience.

Declare every MCP server under its canonical resource URI: the URI the MCP specification has clients send in `resource`, and the one the MCP server compares the audience against. The two sides compare it as a string, so the authorization server and the MCP server are configured with exactly the same value, trailing slash included. In `ProviderApp` the tenant's `Resources` holds one `ResourceDefinition` for the task tracker: its URI, `https://localhost:5008/mcp`, and a `ScopeDefinition` for each of its two scopes, `tasks.read` and `tasks.write`.

Where one tenant serves several MCP servers, set `NewClientOptions.SingleResourceAccessTokens`, so each access token names one of them: a token with several audiences would let a tool on one MCP server use the token it received at another.

## Admit MCP clients: dynamic registration or metadata documents

An MCP client that has never met the authorization server becomes known to it in one of two ways: by dynamic client registration, or by a Client ID Metadata Document.

With dynamic client registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)), the client posts its metadata and gets a `client_id` the server generates. Anybody can register any name, so the name says nothing about who made the client.

In Abblix OIDC Server, the registration endpoint exists once the host calls `AddDynamicClientRegistration()`, and it is closed by default: `OidcOptions.RequireInitialAccessToken` is true, so a client registers only with an initial access token the host issues. To serve MCP clients that register themselves, the host sets it to false. An open registration endpoint needs a rate limit, and the built-in ASP.NET Core `AddRateLimiter` provides one, applied to the registration endpoint alone. Behind a reverse proxy, the limit counts real clients only once the host forwards their addresses, as the [production hardening checklist](https://www.abblix.com/en/docs/production-hardening-checklist) describes.

The MCP specification (revision 2026-07-28) marks dynamic registration as deprecated, kept for clients written to earlier revisions, and recommends Client ID Metadata Documents in its place. With a metadata document, the client's `client_id` is the `https` URL of a JSON document its vendor publishes, and the authorization server fetches it. The host turns this on with `AddClientIdMetadataDocuments()`. The feature implements [draft-ietf-oauth-client-id-metadata-document-03](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-03) and is experimental in Abblix OIDC Server.

Only whoever controls the vendor's web address can publish a document under it. List the addresses of the vendors you trust in `ClientIdMetadataDocuments.AllowedClientIdPrefixes`, and a document under any other address is refused without a request leaving the server. Left unset, the list admits any document the draft allows, and the consent page is the user's only check. Write each prefix with its trailing slash (`https://assistant.example.com/`), and never name a host where others can publish files: a prefix trusts everything under it. The fetch follows no redirects, reads a bounded size, by default reaches no private network, and accepts a document only when its `client_id` equals the URL it came from.

The list says whose document it is, not which program is asking. A `client_id` is public, and with a loopback redirect URI any program on the user's computer can start a flow under a trusted vendor's identifier. Against that, the warning on the consent page and the user's own judgment are the defense, which is why trusting a vendor never skips the consent page ([below](#ask-the-user-on-a-consent-page)).

In `ProviderApp` the list comes from its settings:

```csharp
// A client may name itself by the https URL of a metadata document it publishes instead of registering
// (draft-ietf-oauth-client-id-metadata-document-03). With prefixes set, the provider fetches only documents under
// them, so a URL of an untrusted vendor is refused without a request leaving the provider; the user still
// approves every client on the consent page.
options.ClientIdMetadataDocuments = new ClientIdMetadataDocumentOptions
{
    AllowedClientIdPrefixes = allowedClientIdPrefixes,

    // McpClientApp serves its document on this machine, and the draft forbids fetching one from a special-use
    // address (section 10.7) except on a development machine whose authorization server is itself on loopback.
    // The library applies this only while the tenant's issuer is on loopback, and a Production host does not
    // start with it.
    DocumentAddresses = builder.Environment.IsDevelopment()
        ? ClientIdMetadataDocumentAddresses.AllowLoopback
        : ClientIdMetadataDocumentAddresses.PublicOnly,
};
```

Whichever way a client becomes known, it gets only the `authorization_code` and `refresh_token` grants and no resource until the host names one in `NewClientOptions`. The sample spells that policy out, with `mcpResource` holding the task tracker's resource URI, `https://localhost:5008/mcp`:

```csharp
options.NewClientOptions = new NewClientOptions
{
    // These are the library's defaults, written out so the sample shows the policy: an MCP client acts for a user
    // through the authorization code flow, renewed by refresh tokens, so a registration asking for anything else,
    // client_credentials included (a token for the MCP server with no user behind it), is refused.
    AllowedGrantTypes = [GrantTypes.AuthorizationCode, GrantTypes.RefreshToken],

    // Allowed gives MCP clients a refresh token without prompt=consent: they ask for offline_access without it,
    // and by default (ConsentRequired) such a request gets none (OpenID Connect Core 1.0, section 11). The user's
    // answer on the consent page stands in for prompt=consent, so the assistant keeps working after its access token expires.
    OfflineAccess = OfflineAccess.Allowed,

    // A client that registers itself may get a token for the task tracker and nothing else this provider
    // protects, whatever it names: which resources a client reaches is the provider's policy, not the client's
    AllowedResources = [mcpResource],
};
```

A client known by its metadata document is also held to `ClientIdMetadataDocuments.AllowedGrantTypes`, so a host widening the grants names them in both. A client that registers itself is held to the scopes it registered, so it registers with every scope it will use, writing included, and asks for them in its first authorization request. The refresh token of such a public client is replaced on every use.

## Ask the user on a consent page

Any application can become a client, so the user approves every authorization. [RFC 10017, section 6.3.3.2](https://datatracker.ietf.org/doc/html/rfc10017#section-6.3.3.2) says an authorization server should not process authorization requests automatically without user consent, unless it can assure the identity of the client.

Abblix OIDC Server has no consent page of its own. The host serves one at the tenant's `ConsentUri`, and its `IUserConsentsProvider` returns each request's consent as pending, so the library sends the user there; in the sample that is `ConsentPageDecisions`. The page shows:

- The client's name and where that name comes from: a metadata document's claim, with the host it is published on, or the client's own claim at registration. The name is asserted by the client itself ([draft section 10.10](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-03#section-10.10)), so the host beside it is what the user can check.
- The `client_id`, and the host the authorization code goes to. For a redirect URI on a loopback address, a warning that any program on the user's computer could receive the code: the MCP specification recommends that authorization servers display additional warnings for `localhost`-only redirect URIs.
- The scopes and the resources asked for, each scope with its own checkbox, so the user can allow reading without allowing changes. For a client that registered itself and asks for writing up front, this checkbox is where the user keeps writing out of its token.

Like any consent page, it carries an antiforgery token and forbids being framed. An approval is not remembered for a client nobody vetted: RFC 10017 lets an earlier approval count for a client whose redirect URIs are a fixed set of exact `https` URIs, and an MCP client usually redirects to a loopback `http` address. Because nothing is remembered, an approval cannot carry over from one client or MCP server to another, which [draft section 10.12](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-03#section-10.12) warns about for servers that do remember approvals.

## Publish protected resource metadata

A client finds the authorization server through the MCP server. The MCP server publishes protected resource metadata ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)) naming its resource URI and its authorization server, and answers a request without a valid token with 401 and `WWW-Authenticate: Bearer resource_metadata="..."`, the address of that metadata.

In `McpServerApp` the MCP SDK's authentication scheme serves the metadata. Its challenge carries only `resource_metadata`, so the sample's `ScopeChallengeHandler` adds the `scope` a client needs to start, which the MCP specification recommends, and `error="invalid_token"` when a token came and was refused.

## Validate the token at the MCP server

The MCP server is a resource server, and it checks every token itself before a tool runs:

- The issuer and the signature, against the authorization server's metadata and keys.
- The audience, equal to the MCP server's own resource URI. The MCP specification requires servers to validate that access tokens "were issued specifically for them as the intended audience". A token issued for another resource, or for none, is refused.
- The token type, `at+jwt`, as [RFC 9068, section 4](https://datatracker.ietf.org/doc/html/rfc9068#section-4) requires a resource server to check. A JWT of another type, such as an ID token or a refresh token, is not an access token, and the MCP specification forbids an MCP server to accept any token other than one issued for it. Set the expected type explicitly: by default `JwtBearer` accepts a token of any type.
- A user behind the token, where the tool acts for one. A token from the [client credentials grant](https://www.abblix.com/en/docs/machine-to-machine-client-credentials) carries `idp` `client_credentials`, and the MCP server refuses it like a token without a subject.

In `McpServerApp` all four are `JwtBearer` settings, and `MapInboundClaims = false` keeps the claims under their JWT names, `sub` and `scope`:

```csharp
authentication.AddJwtBearer(options =>
{
    // The signing keys and the issuer come from the provider's metadata
    options.Authority = authorizationServer;

    // The MCP specification: servers "MUST validate that access tokens were issued specifically for them as
    // the intended audience". The provider writes the resource the client named (RFC 8707) into aud, so a
    // token issued for any other resource, or for none, is refused here.
    options.Audience = resource.OriginalString;

    // A refresh token of this provider is addressed to the issuer, so the audience check already refuses one; the
    // type check keeps that true whatever audience a token carries, and the MCP specification says servers
    // "MUST NOT accept or transit any other tokens".
    options.TokenValidationParameters.ValidTypes = ["at+jwt"];

    // Keep the claims under their JWT names (sub, scope) rather than the mapped .NET claim types
    options.MapInboundClaims = false;

    // The tools act for a user, so a token issued to a client on its own behalf is refused like any other token
    // not meant for this server. The provider marks such a token with idp=client_credentials; its subject is no
    // guide, since a client with pairwise subjects gets a pseudonym there rather than its client_id.
    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = context =>
        {
            var subject = context.Principal?.FindFirst("sub")?.Value;
            var identityProvider = context.Principal?.FindFirst("idp")?.Value;
            if (string.IsNullOrEmpty(subject) || identityProvider == "client_credentials")
                context.Fail("The access token carries no user");

            return Task.CompletedTask;
        },
    };
});
```

## Start with the smallest scope

Give each tool one authorization policy, satisfied by one [scope](https://www.abblix.com/en/docs/glossary-overview#scope): in the sample, `tasks.read` for listing the tasks and `tasks.write` for changing them. The MCP server's protected resource metadata lists only the scope a client needs to start, and its 401 challenge names that scope too. The MCP specification has `scopes_supported` represent "the minimal set of scopes necessary for basic functionality". Do not list every scope of the catalog in every challenge: a client asks for what the challenge names, and a token for everything is a token that can do everything. In `McpServerApp` each policy is built from its scope:

```csharp
// Reading the tracker and changing it are granted separately, so an employee can let an assistant see the tasks
// without letting it change them. Each tool names the policy it needs.
// The scope behind each policy: the policies are built from it, and a refused call is told which one it lacks.
var policyScopes = new Dictionary<string, string>
{
    [TaskPolicies.Read] = readScope,
    [TaskPolicies.Write] = writeScope,
};
var authorizationBuilder = builder.Services.AddAuthorizationBuilder();
foreach (var (policyName, policyScope) in policyScopes)
{
    authorizationBuilder.AddPolicy(policyName, policy => policy
        .RequireAuthenticatedUser()
        .RequireAssertion(context => context.User.FindFirst("scope")?.Value
            .Split(' ', StringSplitOptions.RemoveEmptyEntries)
            .Contains(policyScope, StringComparer.Ordinal) is true));
}
```

A call to a tool whose scope the token lacks is answered 403 with `error="insufficient_scope"` and the scope the tool needs, as [RFC 6750, section 3.1](https://datatracker.ietf.org/doc/html/rfc6750#section-3.1) defines. The client then sends the user back to the authorization server asking for that scope as well, the step-up flow of the MCP specification, and repeats the call with the new token. A client known by its metadata document asks for writing only at this point, so a token that only ever reads never carries it.

The sample lists every tool to every token, so an assistant sees a tool it cannot use yet, calls it, and steps up from the refusal. Each tool names the scope it needs with the sample's `[ToolPolicy]` attribute, and `ToolScopeGate` answers a call without that scope with 403 before the MCP SDK dispatches it. The SDK's own authorization filters can answer only with a JSON-RPC error inside a 200 response, which a client cannot step up from. The gate sits in front of the endpoint `MapMcp` maps, so every request routed to it, `/mcp/` included, passes it:

```csharp
// After the endpoint's own check that a valid token came with the request: a call to a tool the token's scope does
// not cover is answered 403 with the scope it needs
var gate = ActivatorUtilities.CreateInstance<ToolScopeGate>(app.Services, policyScopes);
app.Use(gate.InvokeAsync);

// The gate acts on the endpoint carrying it, so every path spelling routing sends here (/mcp/ included) passes it
app.MapMcp(resource.AbsolutePath).RequireAuthorization().WithMetadata(gate);
```

## Call upstream APIs with token exchange

A tool that calls another API on the user's behalf does not forward the token it received: the MCP specification forbids token passthrough, because the upstream API would then accept a token that was never issued for it, and the MCP server's audience check would mean nothing. The MCP server exchanges its token at the authorization server for one issued to the upstream API, with [token exchange](https://www.abblix.com/en/docs/glossary-overview#token-exchange) ([RFC 8693](https://datatracker.ietf.org/doc/html/rfc8693)), and sends that one.

For this the MCP server is a confidential client of the authorization server, allowed the `urn:ietf:params:oauth:grant-type:token-exchange` grant, and the upstream API is declared as a resource of its own. The token the MCP server holds was issued to the assistant, another client, and Abblix OIDC Server refuses to exchange another client's token by default. Set the MCP server's `CrossClientSubjectTokenExchange` to `AddressedToClient` with its own resource URI in `ResourceLocations`: it then exchanges only access tokens addressed to it. The MCP server sends the token it received as `subject_token` and names the upstream API in `resource`. The sample's tools call no upstream API, so it does not show this step.

## Know what sign-out reaches

When the user signs out at the authorization server, Abblix OIDC Server revokes the assistant's refresh token from that session (`RevokeSessionTokensOnLogout`, on by default). The access token it already holds keeps working at the MCP server until it expires, because the MCP server checks it itself, so keep access tokens short-lived, or have the MCP server introspect them ([RFC 7662](https://datatracker.ietf.org/doc/html/rfc7662)) where access has to stop at once.

## Never authenticate by session

Whatever the transport keeps, the MCP server checks the access token on every request and never takes an `Mcp-Session-Id` as proof of who is calling. The sample runs the SDK's HTTP transport stateless. State that belongs to a user, the tasks in the sample, is keyed by the token's `sub`, so an assistant acting for one user never sees another's.

## Next steps

To connect your own service through MCP to agents such as Claude or Codex, with the agents known by their metadata documents, the authorization server and your MCP server need public hosting over HTTPS: the agents connect from their vendors' side and cannot reach `localhost` on your machine. Give each a host name of its own on the standard port 443, for example `https://login.example.com` and `https://tasks.example.com/mcp`, with certificates the agents trust, and use those addresses as the issuer and as the resource URI on both sides. An agent that becomes known by its metadata document is admitted once its vendor's prefix is in `AllowedClientIdPrefixes`.

- The [MCP server sample README](https://github.com/Abblix/Oidc.Server.GettingStarted/tree/master/McpServerSample) runs the three applications and walks through every request.
- [Upgrading to 3.1](https://www.abblix.com/en/docs/upgrading-to-3.1) lists what changed in the authorization server this guide relies on.
