Our Take · December 4, 2026

Build a secure MCP server in C#: OAuth, per-user tools and a production checklist

Build a secure MCP server in C#: OAuth, per-user tools and a production checklist

An MCP (Model Context Protocol) server lets AI tools such as Claude, ChatGPT and Microsoft Copilot call your product’s data and actions. If you sell software, an MCP server is how your product becomes something an agent can use. This guide builds one in C# and .NET, protects it with bearer-token authentication, and makes a tool that knows who is calling.

We ran every piece of code below on December 1, 2026, with .NET 10, the ModelContextProtocol.AspNetCore package version 2.4.0 and Microsoft.AspNetCore.Authentication.JwtBearer 10.x. Where we didn’t test something, we say so.

What you’ll build

  • An ASP.NET Core app that exposes an MCP endpoint over HTTP at /mcp.
  • Bearer-token (JWT) authentication on that endpoint, so anonymous calls get a 401.
  • The “protected resource metadata” document that tells an MCP client where to sign in.
  • One tool, get_order_status, that reads the signed-in user’s identity.

1. Create the project

dotnet new web -n McpDemo
cd McpDemo
dotnet add package ModelContextProtocol.AspNetCore --version 2.4.0
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version "10.*"

One practical note: the JwtBearer package must match your target framework. The newest major version needs a newer framework than .NET 10, and dotnet add package without a version fails with a compatibility error (NU1202) on a .NET 10 project. Pinning 10.* fixes it.

2. The server

using System.ComponentModel;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Server;

var builder = WebApplication.CreateBuilder(args);

var serverUrl = builder.Configuration["Mcp:ServerUrl"] ?? "http://localhost:5080/";
var tenantId = builder.Configuration["Entra:TenantId"]!;
var authority = $"https://login.microsoftonline.com/{tenantId}/v2.0";
var audience = builder.Configuration["Entra:Audience"] ?? serverUrl;

builder.Services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = authority;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidAudience = audience,
        NameClaimType = "name",
    };
})
.AddMcp(options =>
{
    options.ResourceMetadata = new()
    {
        AuthorizationServers = { authority },
        ScopesSupported = ["mcp:tools"],
    };
});

builder.Services.AddAuthorization();
builder.Services.AddMcpServer()
    .WithHttpTransport()
    .WithTools<OrderTools>();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapMcp("/mcp").RequireAuthorization();
app.Run(serverUrl.TrimEnd('/'));

[McpServerToolType]
public class OrderTools
{
    [McpServerTool(Name = "get_order_status"),
     Description("Returns the status of an order for the signed-in user.")]
    public static string GetOrderStatus(
        ClaimsPrincipal user,
        [Description("The order number")] string orderNumber)
        => $"Order {orderNumber} for {user.Identity?.Name ?? "unknown"}: shipped";
}

A few things worth knowing about this code:

  • AddMcp is what makes a standard client able to sign in. It publishes the metadata document and adds the challenge header described next.
  • RequireAuthorization() on MapMcp is what actually protects the endpoint.
  • The tool takes a ClaimsPrincipal. The SDK supplies the signed-in user to your tool, so each call can be scoped to that person. That is where per-customer authorization belongs, not in a prompt.
  • Return real data from your own services, not strings. The tool above is a stub.

3. What we tested

We started the server and checked four things.

An anonymous call is rejected, with directions. A tools/list request with no token returns 401 Unauthorized and a WWW-Authenticate header pointing to the metadata: Bearer resource_metadata="http://localhost:5391/.well-known/oauth-protected-resource/mcp". A client uses that to find out where to authenticate.

The metadata document is served. Requesting that URL returns JSON naming the resource, the authorization server (your Entra authority), the header bearer method and the scope mcp:tools.

A bad token is rejected. Authorization: Bearer abc returns 401.

A valid token reaches the tool, and the tool sees the user. Calling get_order_status with {"orderNumber":"A-1001"} returned Order A-1001 for Test User: shipped. To test locally without a tenant, we signed a short-lived token ourselves and told the server to trust a test key, in a development-only branch that isn’t part of the code above.

What we did not test: a real sign-in against Microsoft Entra. For that you register the API in Entra, decide the audience your tokens carry, and have your MCP client complete the OAuth flow. Microsoft’s documentation covers the registration; the one part to be careful about is that ValidAudience must match the audience your tokens actually carry.

4. Before this goes to production

  1. Validate issuer, audience and lifetime, as above. A token meant for another API must not work on yours.
  2. Authorize inside every tool. Authentication says who is calling; each tool still has to check what that person may see. Test with a user who should see nothing.
  3. Keep tools narrow and well described. The description is what the model reads to decide when to call a tool. Prefer a few clear tools to one that does everything.
  4. Think about origins. The official SDK sample enables CORS only because it serves a browser client from a different origin; if your server isn’t meant for cross-origin browser access, leave CORS off.
  5. Choose stateless unless you need sessions. The SDK’s sample notes that stateless mode is its recommended default for servers that don’t need server-to-client requests, and it scales without session affinity.
  6. Log who called what, and decide what you will not log.
  7. Evaluate before you release. Write down the questions a real customer’s agent will ask and check the answers.

5. Where this goes next

Once your server works, you can connect it to an agent: Claude and other tools can use it directly, and in Microsoft 365 you can attach it to a declarative agent so your customers use your product from Copilot. We cover that choice in how to put your software product inside Microsoft 365 Copilot.

If you’d like a team that has shipped production AI features on .NET and Azure to build and own this with you, that’s an Embedded Product Team. If you want your own engineers to get good at it first, that’s AI Enablement.

Get your AI game plan

Sources, December 1, 2026: the official ModelContextProtocol C# SDK sample “ProtectedMcpServer” (code patterns and comments), Microsoft Learn “Build a plugin for a declarative agent from an MCP server.” Test run on our own machine; no production system was involved.

A
Aviron Labs

Aviron Labs is a highly productive US team that ships production AI features inside software companies' products, led by Spencer Schneidenbach.

Learn more about our team

Get your AI game plan.

A free hour with our problem solvers.

Get your AI game plan