Expose an MCP server with per-user OAuth
This guide connects an AI assistant, or any other MCP client, to a remote MCP server that your app hosts. Each person signs in as themselves. The assistant's token acts with that person's roles, and only within the scopes they approved. Your existing authorization policies keep working.
It uses the AuthEndpoints.OpenIddict package (preview). The same steps work for a plain HTTP API that OAuth clients call. For every option, see the package README.
How the connection works
- The person pastes your MCP URL, for example
https://app.example.com/mcp, into the assistant. - The assistant calls
/mcpwithout a token. It gets401withWWW-Authenticate: Bearer resource_metadata="https://app.example.com/.well-known/oauth-protected-resource/mcp", reads that protected resource metadata (RFC 9728), and finds your authorization server. - The assistant identifies itself. It either uses an
httpsURL as itsclient_id(a client ID metadata document, which the MCP spec prefers), or registers at/connect/register(dynamic client registration, the fallback). - The browser goes to
/connect/authorize. A signed-out person is sent to your sign-in page first. An existing session skips that step. - Your consent page shows the assistant's name, the domain that published it, and the requested scopes in words. The person approves or denies.
- The assistant exchanges the code with PKCE and a
resourceindicator (RFC 8707) for an access token whose audience is/mcp, plus a refresh token that rotates on every use. - Each MCP call runs as that person: your role and policy checks apply, narrowed by the granted scopes.
- To disconnect the assistant, you revoke its authorization. To disconnect everything, you change the person's security stamp.
| Step | Feature |
|---|---|
| 2 | ProtectedResource, UseOAuthResourceChallenge() |
| 3 | ClientMetadataDocuments, DynamicRegistration, DynamicRegistration.AllowedScopes |
| 4–5 | LoginUrl, ConsentUrl, the consent API, ScopeDefinitions |
| 6 | AdditionalResources, AcceptedAudiences, rotating refresh tokens |
| 7 | RequireOAuthAudience, RequireOAuthScope, RequireOAuthScopeWhenDelegated, HasOAuthScope, AccessTokenClaims |
| 8 | Connected apps (GET/DELETE /oauth/authorizations), IOAuthConnectedAppService, UserManager.UpdateSecurityStampAsync |
Before you start
- Your app signs people in with AuthEndpoints and an Identity cookie (
AddPasswordAuth, or another setup that ends with the Identity application cookie). The authorize step reads that cookie. - Your app serves HTTPS on a public host. MCP clients reach
/mcp,/.well-known/…, and/connect/…on it. - To reuse role checks, Identity has roles (
AddRoles<IdentityRole>()).
dotnet add package AuthEndpoints.OpenIddict --prerelease
In this guide, one app serves both the cookie-authenticated API at /api and the MCP server at /mcp, at https://app.example.com.
1. Register the authorization server
using AuthEndpoints.OpenIddict;
builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
options.Issuer = new Uri("https://app.example.com/");
// Two resources on this host. A token is for one of them and is accepted only there.
options.Audience = "https://app.example.com/api";
options.AdditionalResources.Add("https://app.example.com/mcp");
options.AcceptedAudiences.Add("https://app.example.com/mcp");
// What a person can let an assistant do for them.
options.Scopes.Add("mcp");
options.Scopes.Add("reports.read");
options.Scopes.Add("account"); // your own first-party clients only
options.LoginUrl = "https://app.example.com/sign-in";
options.ConsentUrl = "https://app.example.com/oauth/consent";
options.Certificates.Path = "/var/lib/myapp/oauth-keys";
// Assistants identify themselves with a metadata document, or register as a fallback.
options.ClientMetadataDocuments.Enabled = true;
options.DynamicRegistration.Enabled = true;
// Clients that anyone can bring may hold only these scopes (plus offline_access).
options.DynamicRegistration.AllowedScopes.Add("mcp");
options.DynamicRegistration.AllowedScopes.Add("reports.read");
// Discovery: one RFC 9728 document per resource, and a 401 that points at it.
options.ProtectedResource.Enabled = true;
options.ProtectedResource.ResourceName = "Example API";
options.ProtectedResource.ChallengePaths.Add("/api");
options.ProtectedResource.Resources.Add(new OAuthProtectedResourceDefinition
{
Resource = "https://app.example.com/mcp",
ResourceName = "Example MCP server",
Scopes = { "mcp", "reports.read" },
ChallengePaths = { "/mcp" },
});
// Tokens carry the person's roles and user id, so existing checks work.
options.AccessTokenClaims.Roles = true;
options.AccessTokenClaims.UserId = true;
})
.BindConfiguration("OAuthServer"); // scope descriptions and host lists can live in appsettings
Keep any scope that acts as the person's whole account (here account) out of DynamicRegistration.AllowedScopes. Clients that anyone can bring, by metadata document or by registration, then cannot ask for it. Configured clients and developer apps can still use it.
Describe the scopes
The consent page should say "Read your reports", not reports.read, in the person's language:
{
"OAuthServer": {
"ScopeDefinitions": [
{
"Name": "mcp",
"DisplayName": "Use the assistant tools",
"Description": "Run the tools of this app's MCP server as you, with your permissions.",
"DisplayNames": { "fr": "Utiliser les outils de l'assistant" }
},
{
"Name": "reports.read",
"DisplayName": "Read your reports",
"Description": "See the reports you can open. It cannot change them."
},
{
"Name": "offline_access",
"DisplayName": "Stay connected",
"Description": "Keep access until you disconnect it."
}
]
}
}
The text is chosen for the request culture. Add app.UseRequestLocalization(…) if your consent page sends Accept-Language or a culture cookie. To load the text from a database or resource files instead, implement IOAuthScopeDescriptions and register it with AddScopeDescriptions<T>().
Limit which assistants can connect (optional)
Metadata document clients come from any public host by default. To accept only some hosts:
options.ClientMetadataDocuments.AllowedHosts.Add("assistant.example.com");
options.ClientMetadataDocuments.AllowedHosts.Add("*.trusted.example");
For a rule the lists cannot express, register an IOAuthClientMetadataHostFilter with AddClientMetadataHostFilter<T>(). To keep only metadata documents, leave DynamicRegistration.Enabled off. Many MCP clients still fall back to registration, so test the assistants you care about first.
2. Add the tables
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.UseAuthEndpointsOpenIddict<AppUser>();
}
dotnet ef migrations add OAuthServer
3. Map the routes
var app = builder.Build();
app.UseOAuthResourceChallenge(); // before authentication, so every 401 carries resource_metadata
app.UseAuthEndpoints(); // or UseAuthentication, UseAuthorization, UseAntiforgery
app.MapOAuthServer(); // authorize, register, metadata, and the consent API under /oauth
MapOAuthServer serves /connect/authorize, /connect/token, /connect/revoke, /connect/register, /.well-known/oauth-authorization-server, /.well-known/oauth-protected-resource and /.well-known/oauth-protected-resource/mcp, and the consent API at /oauth/requests/{id}.
4. Protect the MCP server
Write one policy for the MCP endpoint. It accepts only tokens issued for /mcp, requires the mcp scope, and keeps the role check the same feature has for cookie users:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("mcp", policy => policy
.RequireOAuthAudience("https://app.example.com/mcp") // a token for /api gets 403 here
.RequireOAuthScope("mcp") // and so does one without the scope
.RequireRole("Member")); // the person's own role, from AccessTokenClaims.Roles
});
app.MapMcp("/mcp").RequireAuthorization("mcp"); // or your own MCP endpoint
MapMcp here is the endpoint of an MCP server library, such as the ModelContextProtocol.AspNetCore package. Any endpoint that serves MCP over HTTP works the same way: put the policy on it.
A tool that needs more than mcp checks the scope inside the handler, through the caller's principal. In a plain endpoint, Results.Forbid() answers a token caller with 403:
public sealed class ReportTools(IHttpContextAccessor http, ReportService reports)
{
public async Task<IReadOnlyList<Report>> ListReports(CancellationToken ct)
{
var user = http.HttpContext!.User;
if (user.IsOAuthDelegated() && !user.HasOAuthScope("reports.read"))
{
throw new UnauthorizedAccessException("The person did not allow this assistant to read reports.");
}
// The same service and the same role checks that cookie users go through.
return await reports.ListForAsync(user, ct);
}
}
With AccessTokenClaims.UserId on, UserManager.GetUserId(user) and ClaimTypes.NameIdentifier return the person's id, so services written for cookie users work unchanged. With AccessTokenClaims.Roles on, IsInRole and RequireRole see the person's Identity roles. They are read again at every refresh, so a role change reaches the assistant within one access token lifetime (15 minutes by default).
A scope never widens what the person may do. It narrows it. Keep the role or policy check every route already has, and add the scope check next to it.
Routes that cookie users and assistants share
If an assistant should also call some of your /api routes, accept both callers there and add the scope check only for tokens:
using OpenIddict.Abstractions; // HasAudience
options.AddPolicy("reports.read", policy => policy
.AddAuthenticationSchemes(IdentityConstants.ApplicationScheme, OAuthServerServiceCollectionExtensions.ValidationScheme)
.RequireRole("Member")
.RequireOAuthScopeWhenDelegated("reports.read")
// A token must be for /api. An /mcp token gets 403 here, even with the scope.
.RequireAssertion(context => !context.User.IsOAuthDelegated()
|| context.User.HasAudience("https://app.example.com/api")));
A cookie caller passes the scope and audience checks. A token caller needs reports.read and the /api audience, and gets 403 without either. It gets a status code, not the cookie's redirect to its access-denied page, because a request with Authorization: Bearer skips the cookie's redirects (BearerRequestsSkipCookieRedirects, on by default). Do not use RequireOAuthAudience here: it accepts only token callers, so cookie users would get 401. To let an assistant call /api, it asks for resource=https://app.example.com/api in its own authorization request.
5. Build the consent page
/connect/authorize sends the signed-in person to ConsentUrl?request={id}. Your page reads the card and shows it:
GET /oauth/requests/0193c5d4-…
{
"id": "0193c5d4-…",
"clientId": "https://assistant.example.com/oauth/client.json",
"clientName": "Example Assistant",
"clientHost": "assistant.example.com",
"redirectHost": "assistant.example.com",
"resource": "https://app.example.com/mcp",
"scopes": [ "mcp", "reports.read", "offline_access" ],
"scopeDetails": [
{ "name": "mcp", "displayName": "Use the assistant tools", "description": "Run the tools of this app's MCP server as you, with your permissions." },
{ "name": "reports.read", "displayName": "Read your reports", "description": "See the reports you can open. It cannot change them." },
{ "name": "offline_access", "displayName": "Stay connected", "description": "Keep access until you disconnect it." }
],
"expiresAt": "…"
}
- Show
clientNametogether withclientHost. The name is whatever the client claims, andclientHostis the domain that published it. For a dynamically registered client,clientHostisnull, so showredirectHost, where the code will be sent. - List
scopeDetailsas the things the person allows. - Approve with
POST /oauth/requests/{id}/approveand deny withPOST /oauth/requests/{id}/deny, both with your CSRF header. Each returns{ redirectUrl }. Send the browser there.
The full contract, including approving from your own endpoint, is in The consent step.
6. What the assistant does
You do not write this part. It helps to know what the assistant sends when you read your logs.
GET /mcp
→ 401 WWW-Authenticate: Bearer resource_metadata="https://app.example.com/.well-known/oauth-protected-resource/mcp"
GET /.well-known/oauth-protected-resource/mcp
→ { "resource": "https://app.example.com/mcp", "authorization_servers": ["https://app.example.com/"],
"scopes_supported": ["mcp", "reports.read"], "resource_name": "Example MCP server", … }
GET /.well-known/oauth-authorization-server
→ { …, "client_id_metadata_document_supported": true, "registration_endpoint": "https://app.example.com/connect/register",
"code_challenge_methods_supported": ["S256"], … }
GET /connect/authorize?client_id=https%3A%2F%2Fassistant.example.com%2Foauth%2Fclient.json
&redirect_uri=…&response_type=code&code_challenge=…&code_challenge_method=S256
&scope=mcp%20reports.read%20offline_access&resource=https%3A%2F%2Fapp.example.com%2Fmcp&state=…
→ (sign-in if needed) → 302 to ConsentUrl?request=… → after approval, 302 to the assistant with code, state, iss
POST /connect/token grant_type=authorization_code&code=…&code_verifier=…&client_id=…&redirect_uri=…&resource=…
→ { "access_token": "…", "refresh_token": "…", "expires_in": 900, … }
When the client_id is a URL, your server fetches that document once and caches it within bounds. It refuses private and loopback addresses, redirects, and documents over 5 KB. The client must be public, its redirect_uris must follow the same rules as dynamic registration, and its scopes are limited to DynamicRegistration.AllowedScopes. The client is stored in OpenIddict's application store, so refresh, revocation, and cleanup work as for any other client.
7. Disconnect an assistant
MapOAuthServer maps the connected apps routes for the signed-in person: GET /oauth/authorizations lists the assistants they connected (name, kind, host when known, scopes, resource, created, and last used with RecordLastUsed), and DELETE /oauth/authorizations/{id} disconnects one. The routes take the sign-in cookie only, so an assistant's token cannot call them. For an admin page, call IOAuthConnectedAppService with the user id.
To end one assistant's access from your own code, revoke its authorization. That also revokes every token issued from it:
app.MapDelete("/api/connections/{authorizationId}", async (string authorizationId, IOAuthConsentService consent) =>
await consent.RevokeAuthorizationAsync(authorizationId) ? Results.NoContent() : Results.NotFound())
.RequireAuthorization("admin")
.RequireAntiforgery(allowBearer: false);
ApproveAsync returns the authorization id when your own approve endpoint calls it, so you can store it next to the person. Before you revoke an authorization on a person's behalf, check that it belongs to them.
To end every grant for a person, change their security stamp with UserManager.UpdateSecurityStampAsync(user). The next refresh of each grant fails and the grant is revoked. An access token that was already issued works until it expires.
Checklist
- Assistant tokens work only on
/mcp, throughRequireOAuthAudience. A token for/apigets403there. - Every MCP route has a scope check and the same role or policy check that cookie users go through.
DynamicRegistration.AllowedScopeslists only the scopes that clients anyone can bring may ask for.- The consent page shows
clientHost(orredirectHost) next toclientName, and usesscopeDetails. - Token callers get
401and403, never the sign-in cookie's redirects (keepBearerRequestsSkipCookieRedirectson). - Behind a reverse proxy, forwarded headers are configured, so rate limits see the real client IP and the server sees
https. - Routes that change a password, two-factor, passkeys, or approve consent keep
RequireAntiforgery(allowBearer: false), so a token cannot call them. - Your own person-only routes (account deletion, API keys, billing) add
RequireDirectPerson(), so an assistant's token gets403there before you give it write tools. See People and agents.
Not covered yet
These are tracked in the roadmap issue #438:
private_key_jwtclient authentication for metadata document clients.