AuthEndpoints.OpenIddict 4.0.0-preview.5

This is a prerelease version of AuthEndpoints.OpenIddict.
dotnet add package AuthEndpoints.OpenIddict --version 4.0.0-preview.5
                    
NuGet\Install-Package AuthEndpoints.OpenIddict -Version 4.0.0-preview.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AuthEndpoints.OpenIddict" Version="4.0.0-preview.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AuthEndpoints.OpenIddict" Version="4.0.0-preview.5" />
                    
Directory.Packages.props
<PackageReference Include="AuthEndpoints.OpenIddict" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AuthEndpoints.OpenIddict --version 4.0.0-preview.5
                    
#r "nuget: AuthEndpoints.OpenIddict, 4.0.0-preview.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AuthEndpoints.OpenIddict@4.0.0-preview.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AuthEndpoints.OpenIddict&version=4.0.0-preview.5&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=AuthEndpoints.OpenIddict&version=4.0.0-preview.5&prerelease
                    
Install as a Cake Tool

AuthEndpoints.OpenIddict

An opt-in OAuth 2.0 and OpenID Connect authorization server for AuthEndpoints apps, built on OpenIddict 7.7. Other apps, CLIs, and tool clients (MCP clients, for example) sign users in through your app and receive access, refresh, and ID tokens.

The core AuthEndpoints package does not change and has no OpenIddict dependency. Install this package only in the app that issues tokens.

Preview. This release covers OAuth 2.0 (authorization code + PKCE, refresh, revocation, metadata, and optional dynamic registration) and opt-in OpenID Connect: ID tokens, userinfo, logout, and the email, email_verified, and amr claims. See Limitations.

What you get

Route Served by Notes
GET /connect/authorize this package Validated by OpenIddict first, then stores a pending consent and redirects to your consent page. Signed-out users go to your login page.
POST /connect/token OpenIddict authorization_code and refresh_token grants.
POST /connect/revoke OpenIddict RFC 7009. Public clients send client_id.
GET /.well-known/oauth-authorization-server OpenIddict RFC 8414 metadata. Endpoint URLs come from Issuer, never from the request Host.
GET /.well-known/jwks OpenIddict The public signing keys.
GET /.well-known/openid-configuration, GET\|POST /connect/userinfo, GET\|POST /connect/logout OpenIddict, this package OpenID Connect. Only with the openid scope. See OpenID Connect.
POST /connect/register this package RFC 7591. Off by default.
client_id as an https URL at /connect/authorize this package Client ID metadata documents. Off by default.
GET /.well-known/oauth-protected-resource, GET /.well-known/oauth-protected-resource/{path} this package RFC 9728, one document per accepted resource. Off by default.
GET /oauth/requests/{id}, POST …/approve, POST …/deny this package JSON consent API. Mapped by MapOAuthServer unless turned off.
GET\|POST /oauth/apps, GET\|PUT\|DELETE /oauth/apps/{id}, POST …/secret this package Developer console API. Mapped by MapOAuthServer unless turned off.

Defaults:

  • Authorization code flow only, with PKCE required and S256 only (plain is rejected).
  • Reference access and refresh tokens, stored in your database, so revocation takes effect at once.
  • Access tokens last 15 minutes. Refresh tokens last 30 days and rotate on every use, with zero reuse leeway.
  • Authorization codes last 5 minutes. Consent requests last 10 minutes and work once.
  • ClockSkew is zero for both issuing and validating.
  • Every code exchange and refresh checks the approving user again. See When the user changes.
  • HTTPS is required. Token audiences (RFC 8707 resources) are validated, and each client needs a permission for each resource.
  • The issuer, endpoint URLs, and audience come from configuration. The request Host header is never trusted.

Setup

The default recipe is one registration call, one model call, and one map call, in the style of AddPasswordAuth / MapPasswordAuth. It turns on the authorization server (code + PKCE, refresh, revocation, metadata), the JSON consent API, and developer app management. Anonymous (dynamic) registration stays off. Everything else keeps the defaults above, and each optional part can be turned off.

1. Register the server

using AuthEndpoints.OpenIddict;

builder.Services.AddPasswordAuth<AppUser, AppDbContext>(); // or your existing AuthEndpoints setup

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
    options.Issuer = new Uri("https://auth.example.com/");
    options.Audience = "https://api.example.com/";
    options.Scopes.Add("api");
    options.DefaultScopes.Add("api");
    options.LoginUrl = "https://app.example.com/sign-in";
    options.ConsentUrl = "https://app.example.com/oauth/consent";
    options.Certificates.Path = "/var/lib/myapp/oauth-keys";
})
.BindConfiguration("OAuthServer"); // optional: appsettings values override the code above

TUser is your Identity user type and must derive from IdentityUser<TKey>, as everywhere else in AuthEndpoints. The key type (string, Guid, …) is read from it.

The app fails at startup when a required setting is missing: Issuer, Audience, LoginUrl, ConsentUrl, and exactly one certificate source. These are the settings only your app can decide. Scopes lists what clients may ask for.

AddOAuthServer also registers the authorization and antiforgery services that the consent and developer app routes need. It returns OAuthServerBuilder, so AddPrincipalFactory<T>(), AddDeveloperAppOwnerDisplay<T>(), BindConfiguration(…), and .OpenIddict work as before. Call it once, instead of AddAuthEndpointsOpenIddict (see Without the recipe).

2. Add the tables

public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : IdentityDbContext<AppUser>(options)
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.UseAuthEndpointsOpenIddict<AppUser>();
    }
}

This adds the four OpenIddict tables (OpenIddictApplications, OpenIddictAuthorizations, OpenIddictScopes, OpenIddictTokens, with ReferenceId widened to 512 characters) an OAuthRequests table for pending consents, and an OAuthDeveloperApps table for developer apps, each with a cascading foreign key to the user. Then add a migration:

dotnet ef migrations add OAuthServer

Pass userForeignKey: false when the users table is in a different DbContext.

3. Map the routes

app.UseAuthEndpoints(); // or UseAuthentication, UseAuthorization, UseAntiforgery

app.MapOAuthServer();

// After migrations, when options.Clients lists clients:
await app.Services.SeedOAuthClientsAsync();
app.Run();

MapOAuthServer maps /connect/authorize, the consent API under /oauth, and the developer app API under /oauth/apps, plus /connect/register and /.well-known/oauth-protected-resource (with one path-suffixed document per accepted resource) when they are enabled in the options, and /connect/userinfo and /connect/logout when openid is in Scopes. OpenIddict serves the token, revocation, metadata, and key set endpoints itself. MapOAuthServer checks the settings, and that UseAuthEndpointsOpenIddict<TUser>() is in the model, when it runs, so a missing setting or a forgotten model call fails at startup instead of on the first request. The model check builds the EF model only; it does not connect to the database.

The recipe does not seed options.Clients. Seeding writes to the database, so it has to run after the schema exists, and only your app knows when that is (Migrate() at startup, a migration job, or EnsureCreated in tests). Call SeedOAuthClientsAsync() at that point. It creates a missing client and updates an existing one.

Turning parts off
var oauth = app.MapOAuthServer(parts =>
{
    parts.ConsentApi = false;                       // approve through IOAuthConsentService from your own routes
    parts.DeveloperAppsPrefix = "/developers/apps"; // keep developer apps, under another path
    // parts.DeveloperApps = false;                 // or no developer console API at all
});
oauth.DeveloperApps!.RequireRateLimiting("developer-apps"); // the mapped groups take conventions
Part Default Where
Authorization server (authorize, token, revocation, metadata) on Always mapped.
OpenID Connect (userinfo, logout, discovery) off Add openid to options.Scopes.
Consent API on, /oauth parts.ConsentApi, parts.ConsentPrefix
Developer apps on, /oauth/apps parts.DeveloperApps, parts.DeveloperAppsPrefix. Approval and limits: options.DeveloperApps.
Connected apps on, /oauth/authorizations parts.ConnectedApps, parts.ConnectedAppsPrefix. Cookie only, so OAuth tokens cannot call it.
Anonymous registration (RFC 7591) off options.DynamicRegistration.Enabled
Protected resource metadata (RFC 9728) off options.ProtectedResource.Enabled

Anonymous registration and protected resource metadata are server settings, not route switches, because they also change what the metadata advertises. With developer apps on, any signed-in user can register up to DeveloperApps.MaxAppsPerUser (10) clients. Set options.DeveloperApps.RequireApproval = true to review them first, or turn the part off.

MapOAuthServer returns the consent, developer app, and connected apps groups (null when off). Turning off the consent API does not turn off consent: /connect/authorize still sends users to ConsentUrl, and your page approves through IOAuthConsentService (option B).

Without the recipe

The recipe is a shortcut for these calls, which stay public for hosts that want them one by one:

builder.Services.AddAuthorization();
builder.Services.AddAntiforgery();
builder.Services.AddAuthEndpointsOpenIddict<AppUser, AppDbContext>(options => { … });

app.MapAuthEndpointsOpenIddict();        // authorize, plus registration and resource metadata when enabled
app.MapOAuthConsentEndpoints();          // optional JSON consent API
app.MapOAuthDeveloperAppEndpoints();     // optional developer console API
app.MapOAuthConnectedAppEndpoints();     // optional connected apps API
await app.Services.SeedOAuthClientsAsync();

Use one or the other. Mapping MapOAuthServer and also MapOAuthConsentEndpoints maps the same routes twice.

There is no sample host or template yet. The login, consent, and developer console pages are your app's UI, and this package only provides their JSON APIs.

4. Protect your API with the issued tokens

The package registers OpenIddict validation for this host. By default it accepts only tokens whose audience is Audience.

builder.Services.AddAuthorization(options => options.AddPolicy("api", policy => policy
    .AddAuthenticationSchemes(OAuthServerServiceCollectionExtensions.ValidationScheme)
    .RequireAuthenticatedUser()));

app.MapGet("/api/me", (ClaimsPrincipal user) => user.FindFirst("sub")?.Value)
    .RequireAuthorization("api");

Access tokens are reference tokens, validated against this server's database. APIs in other processes are not supported yet (that needs introspection or JWT access tokens, see Limitations).

One host, more than one resource

A token's audience is the resource the client asked for at /connect/authorize (one per request), or Audience when it sent none. To let this host accept tokens for some of its AdditionalResources too, list them in AcceptedAudiences. Each entry must be Audience or in AdditionalResources, or startup fails. Resources left out of AcceptedAudiences stay rejected here, so keep resources that only other APIs serve in AdditionalResources alone.

Once AcceptedAudiences has entries, ValidationScheme lets a token for any accepted audience through, and a policy that only requires an authenticated user no longer tells them apart. Check the audience on each route. RequireOAuthAudience authenticates with ValidationScheme and requires the token's aud to contain the given resource:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
    options.Audience = "https://auth.example.com/api";
    options.AdditionalResources.Add("https://auth.example.com/mcp");
    options.AcceptedAudiences.Add("https://auth.example.com/mcp");
    // ...
});

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("api", policy => policy.RequireOAuthAudience("https://auth.example.com/api"));
    options.AddPolicy("mcp", policy => policy.RequireOAuthAudience("https://auth.example.com/mcp"));
});

app.MapGroup("/api").RequireAuthorization("api");
app.MapGroup("/mcp").RequireAuthorization("mcp");

A token for /mcp then gets 403 from /api, and the other way round. With protected resource metadata on, each accepted resource gets its own document; see One document per resource.

Roles and the user id on tokens

A validated access token has sub and the granted scopes, but no roles and no ClaimTypes.NameIdentifier, so RequireRole policies and UserManager.GetUserId(User) see a token caller as a user without either. Turn on AccessTokenClaims to add them:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
    // ...
    options.AccessTokenClaims.Roles = true;  // the approving user's Identity roles, as `role` claims
    options.AccessTokenClaims.UserId = true; // ClaimTypes.NameIdentifier from sub
});

builder.Services.AddAuthorization(options => options.AddPolicy("reports", policy => policy
    .AddAuthenticationSchemes(OAuthServerServiceCollectionExtensions.ValidationScheme)
    .RequireRole("Reports")));
  • Roles adds the approving user's Identity roles as role claims. That is the role claim type of the identity ValidationScheme creates, so IsInRole, RequireRole, and [Authorize(Roles = "…")] work. Code that reads ClaimTypes.Role claims directly does not see them. It needs Identity roles (AddRoles<TRole>()); without them, mapping the server fails at startup.
  • UserId adds ClaimTypes.NameIdentifier, UserIdClaimType, and IdentityOptions.ClaimsIdentity.UserIdClaimType, each set to sub.
  • Both are read at every code exchange and refresh, and written to the access token only, never to the code, the refresh token, or the ID token. A role change reaches the client at its next refresh. An access token that was already issued keeps its roles until it expires (15 minutes by default).
  • Both apply only when sub is the approving user. A principal factory that issues tokens for another subject gets neither, because the user's roles would describe the wrong subject. A factory that keeps the user id as sub keeps its own claims, and the user's roles are added next to any role claims it sends to the access token.
  • The security stamp and the grant's internal claims are never copied. Both options are off by default.
Require scopes

A scope is what the person allowed the client to do for them. It narrows what the user's account may do and never widens it, so keep the role or policy check a route already has and add the scope next to it. RequireOAuthScope authenticates with ValidationScheme and requires every listed scope; a token missing one gets 403:

builder.Services.AddAuthorization(options =>
{
    // A route only OAuth clients call.
    options.AddPolicy("mcp", policy => policy
        .RequireOAuthAudience("https://auth.example.com/mcp")
        .RequireOAuthScope("mcp"));

    // A route that cookie users and OAuth clients share.
    options.AddPolicy("reports.read", policy => policy
        .AddAuthenticationSchemes(IdentityConstants.ApplicationScheme, OAuthServerServiceCollectionExtensions.ValidationScheme)
        .RequireAuthenticatedUser() // and the route's existing role or policy check
        .RequireOAuthScopeWhenDelegated("reports.read"));
});

RequireOAuthScopeWhenDelegated adds only the scope check. A caller without an OAuth access token (cookie, Identity bearer, JWT) passes it, and a token caller needs every listed scope, even when the same request also carries a valid cookie. It adds no scheme, so list ValidationScheme in the policy, or the token is never read. Both helpers add an OAuthScopeRequirement, which you can also add to a policy you build by hand. A role check on a shared route sees a token caller's roles only with AccessTokenClaims.Roles on; see Roles and the user id on tokens.

For code that authorizes inside a service instead of on the endpoint, such as an MCP tool handler, use the ClaimsPrincipal helpers:

if (user.IsOAuthDelegated() && !user.HasOAuthScope("reports.read"))
{
    return Results.Forbid();
}

IsOAuthDelegated(), GetOAuthScopes(), and HasOAuthScope(scope) read only the identity built from the access token, so a cookie identity never contributes scopes. HasOAuthScope is false for a caller with no token, so check IsOAuthDelegated() first in code that cookie users reach too. The granted scopes include offline_access when the client got a refresh token.

People and agents

Every validated access token is a delegated caller: OAuth validation adds ae:caller = delegated (CallerKinds.ClaimType) and the RFC 8693 act claim, {"client_id":"…"}, naming the client that acts for sub. Core's User.GetCallerKind() returns delegated for it and person for the cookie, Identity bearer, and JWT, and User.GetActingClientId() returns the client. To keep a route for people only, add RequireDirectPerson(); a token caller gets 403, even when the same request also carries the person's cookie:

app.MapPost("/billing/close-account", CloseAccount)
    .RequireAuthorization("reports.read") // a policy that also reads ValidationScheme
    .RequireDirectPerson();

The consent API, the connected apps API, and the developer app API refuse access tokens and API keys with 403, even when AuthenticationScheme is a host scheme that forwards tokens. Core's AddAnyCallerScheme reads each request with exactly one handler; set its BearerScheme to ValidationScheme when assistants call with OAuth tokens. See People and agents.

Where the token is read from

Breaking change. Earlier builds of this package also accepted the access token from the access_token query parameter and from an access_token form field, on every route. Now only Authorization: Bearer is read. A token in a URL ends up in server logs, proxy logs, and browser history, and a form field lets any HTML form send one.

The form body is never read. To accept ?access_token= on chosen paths, list their prefixes in QueryStringTokenPaths. This is what SignalR and raw WebSocket hosts need, because a browser cannot set headers on a WebSocket or EventSource request:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
    // ...
    options.QueryStringTokenPaths.Add("/hubs");
});

app.MapHub<ChatHub>("/hubs/chat").RequireAuthorization("api");

Prefixes match whole path segments: /hubs covers /hubs, /hubs/chat, and /hubs/chat/negotiate, but not /hubsevil. They are relative to PathBase, like routes. Each must start with / and must not end with one. On a listed path the Authorization header still wins when both are sent.

Upgrading a SignalR host: if a hub's clients pass the token with accessTokenFactory (JavaScript) or AccessTokenProvider (.NET), add the hub's path prefix to QueryStringTokenPaths. Without it, the WebSocket and Server-Sent Events transports get 401 after upgrading. Clients that send Authorization: Bearer and form posts that put the token in the header need no change.

On a route that reads both the Identity cookie and an access token, a refused token caller used to get the cookie's answer. That meant a 302 to the login or access-denied page when the cookie challenged or forbade, for example from Results.Forbid() or Results.Challenge() with the default scheme, or a 403 that still carried the cookie's Location header. An OAuth client cannot follow either.

By default (BearerRequestsSkipCookieRedirects = true), a request that carries Authorization: Bearer gets 401 where the cookie would redirect to its login page, and 403 where it would redirect to its access-denied page. This applies to the Identity application cookie and to AuthenticationScheme. Requests without the header, such as browser navigation, are unchanged. Your own OnRedirectToLogin and OnRedirectToAccessDenied still run for them, and an EventsType you set is kept. To keep the cookie's redirects for every request:

options.BearerRequestsSkipCookieRedirects = false;
CSRF on routes that take a token

AddAuthEndpointsOpenIddict (and so AddOAuthServer) adds the validation scheme (OAuthServerServiceCollectionExtensions.ValidationScheme) to AuthEndpointsAntiforgeryOptions.BearerSchemes. A route that accepts both the cookie and an OAuth access token, mapped with RequireAntiforgery(), no longer asks the token caller for a CSRF token. A cross-site request cannot set Authorization: Bearer, and a request the application cookie authenticates is still checked. A token read from the query string on a QueryStringTokenPaths prefix does not skip the check, because it is not in the header.

Use RequireAntiforgery(allowBearer: false) on routes a token must never call on its own, such as your own consent approval or account deletion. The package's consent and developer app writes already do. To check every OAuth caller again, take the scheme back out after registering the server:

builder.Services.PostConfigure<AuthEndpointsAntiforgeryOptions>(options =>
    options.BearerSchemes.Remove(OAuthServerServiceCollectionExtensions.ValidationScheme));

Clients

Clients from configuration

{
  "OAuthServer": {
    "Clients": [
      {
        "ClientId": "my-cli",
        "DisplayName": "My CLI",
        "RedirectUris": [ "http://127.0.0.1:8765/callback" ],
        "Scopes": [ "api" ]
      }
    ]
  }
}

SeedOAuthClientsAsync creates each client or updates it in place. A client with no ClientSecret is public. A client with a secret is confidential; keep the secret in a secret store, not in appsettings.json. Empty Scopes or Resources means every configured one. Every client must use PKCE.

Dynamic registration (optional)

options.DynamicRegistration.Enabled = true;
options.DynamicRegistration.PermitsPerMinute = 10; // per client IP
options.DynamicRegistration.AllowedScopes.Add("mcp"); // optional: scopes anyone may register for

POST /connect/register accepts only public clients (token_endpoint_auth_method none, no client_secret), the authorization_code and refresh_token grants, the code response type, and configured scopes. Each redirect URI must be https, or http on localhost, 127.0.0.1, or [::1], with no fragment and no user info. The rate limit runs inside the endpoint, so it works without UseRateLimiter. Behind a proxy, configure forwarded headers so the client IP is right.

By default a registered client may hold every configured scope. Anyone can register, so if a scope is meant only for your own clients (for example one that acts as the user's whole account), list the scopes registered clients may use in AllowedScopes. Each must be in Scopes; offline_access is always allowed, and openid must be listed for registered clients to use OpenID Connect. A registration asking for another scope is rejected with invalid_client_metadata, and /connect/authorize holds clients registered before the list was set to it too. Configured clients and developer apps are not affected.

A registered client that no user approved within UnusedClientLifetime (24 hours) is deleted by the background cleanup. Seeded clients are never deleted.

Client ID metadata documents (optional)

The MCP authorization spec prefers this over dynamic registration. A client uses an https URL as its client_id, and serves a JSON document there that describes it (draft-ietf-oauth-client-id-metadata-document):

{
  "client_id": "https://assistant.example.com/oauth/client.json",
  "client_name": "Example Assistant",
  "redirect_uris": [ "https://assistant.example.com/oauth/callback" ],
  "grant_types": [ "authorization_code", "refresh_token" ],
  "token_endpoint_auth_method": "none"
}
options.ClientMetadataDocuments.Enabled = true;
options.DynamicRegistration.AllowedScopes.Add("mcp"); // also limits these clients

With it on, the authorization server metadata has client_id_metadata_document_supported: true, and /connect/authorize resolves a client_id that is an https URL before OpenIddict looks the client up:

  • The URL must be https, with a path other than /, and no query, fragment, user info, or ./.. segments. It is compared as a string and never normalized. It may be up to 255 characters.
  • The fetch goes only to public addresses. The host name is resolved first and every address must be public: loopback, private (10/8, 172.16/12, 192.168/16, fc00::/7), link-local (169.254/16, fe80::/10, which covers cloud metadata endpoints), shared, documentation, and multicast addresses are refused, and the connection goes only to the addresses that were checked, so a second DNS answer cannot redirect it. Redirects are not followed; no cookies, credentials, or proxy are used; it times out after FetchTimeout (5 seconds) and reads at most MaxDocumentBytes (5 KB). Accept: application/json is sent and only 200 is accepted. Fetches are not logged.
  • The document must have client_id equal to the URL, and redirect_uris under the same rules as dynamic registration (https, or http on a loopback host, where 127.0.0.1 and [::1] may use any port). Only public clients are accepted: no client_secret, no shared-secret method, and none must be the client's token_endpoint_auth_method or one of its token_endpoint_auth_methods_supported (a document with neither means none). grant_types, when present, must include authorization_code (a refresh token is issued only if it also lists refresh_token), and response_types must include code. client_name is optional; without it, the card shows the host.
  • Scopes follow DynamicRegistration.AllowedScopes, as for registered clients. The document's own scope is ignored, because one document serves every server. Metadata document clients and registered clients are both self-asserted and unauthenticated, so they share AllowedScopes, UnusedClientLifetime, MaxRedirectUris, and MaxClientNameLength. Separate settings can be added later, falling back to these.
  • Storage. The client is stored in OpenIddict's application store, as a public client, so authorizations, refresh, revocation, and RevokeAuthorizationAsync work as for any client. It carries the same creation marker as a registered client, so the cleanup deletes one that no user approved within DynamicRegistration.UnusedClientLifetime; it is simply fetched again next time. A configured client, developer app, or registered client is never replaced by a fetched document, even if its id is a URL.
  • Caching. The stored copy is reused until its Cache-Control: max-age runs out, kept between MinCacheDuration (5 minutes, also used for no-cache, no-store, or no header) and MaxCacheDuration (24 hours). Then the next authorize request fetches it again and updates the stored client in place. If that fetch fails on the network (timeout, connection error, 5xx, 429), the stored copy is used and fetched again on the next request. If the new document's client_id no longer matches its URL, the request is refused and every authorization and token the client holds is revoked, as the draft recommends. Any other invalid document refuses new authorizations only: grants the client already holds keep working. Errors are never cached.
  • Errors. A refused client gets invalid_client on this server's error page. The browser is never sent to the client's redirect URI.
  • Limits. Fetches are limited per caller IP address with ClientMetadataDocuments.FetchesPerMinute (20 by default), because an anonymous authorize request can cause one; a stored copy is reused without counting. Behind a proxy, configure forwarded headers so the caller IP is right.
  • Hosts. DeniedHosts and AllowedHosts take host names, or *.example.com for subdomains. Empty AllowedHosts accepts any public host. For a decision the lists cannot express, register a filter; it runs before every fetch and before a stored client is reused:
builder.Services.AddOAuthServer<AppUser, AppDbContext>(options => { … })
    .AddClientMetadataHostFilter<TrustedClientHosts>();

public sealed class TrustedClientHosts(AppDbContext db) : IOAuthClientMetadataHostFilter
{
    public async ValueTask<bool> IsAllowedAsync(Uri clientId, CancellationToken ct)
        => await db.TrustedClientHosts.AnyAsync(host => host.Name == clientId.IdnHost, ct);
}

The consent card gets clientHost, the host of the client_id URL (with the port when it is not the default), so your page can show which domain published the client next to its name. Turning the option off stops clients created from metadata documents everywhere: /connect/authorize refuses them, and so does /connect/token, for both code exchange and refresh (invalid_client). Access tokens they already hold work until they expire (AccessTokenLifetime, 15 minutes by default).

private_key_jwt client authentication (with jwks or jwks_uri) is not supported yet. A document that offers it next to none is accepted as a public client; one that offers only private_key_jwt is refused with invalid_client and the description "private_key_jwt is not supported for client ID metadata documents yet".

The client_id columns of OpenIddictApplications and OAuthRequests are 255 characters wide, so a metadata URL fits. Add a migration after upgrading (dotnet ef migrations add WidenOAuthClientId, then apply it as you apply your other migrations).

Developer apps

Signed-in users register OAuth apps they own and get a client id (and, for a confidential app, a client secret), the way the GitHub and Google developer consoles work. MapOAuthServer() maps a JSON API for your developer console page (or MapOAuthDeveloperAppEndpoints() without the recipe; parts.DeveloperApps = false turns it off). Every route requires the signed-in user (AuthenticationScheme), and the writes require a CSRF token from every caller, as the consent API does.

Route
GET /oauth/apps The caller's apps.
POST /oauth/apps Register an app. 201 with { app, clientSecret }.
GET /oauth/apps/{id} One app.
PUT /oauth/apps/{id} Edit the name, homepage, description, and redirect URIs.
DELETE /oauth/apps/{id} Delete the app and every authorization and token issued to it.
POST /oauth/apps/{id}/secret Confidential apps only: replace the secret. { app, clientSecret }. The old secret stops working at once.
{
  "name": "My dashboard",
  "homepageUrl": "https://dashboard.example.com",
  "description": "Optional",
  "redirectUris": [ "https://dashboard.example.com/oauth/callback" ],
  "confidential": true
}

There is no SPA, native, or web type to pick. The only choice is whether the app can keep a secret:

  • Confidential ("confidential": true, for server-side apps): a client secret is generated and returned once, with Cache-Control: no-store. Only its hash is stored. The app authenticates at the token endpoint with client_secret_basic or client_secret_post, and still uses PKCE.
  • Public (the default, for SPAs, desktop and mobile apps, and CLIs): no secret, PKCE only.

confidential is fixed at creation and ignored on edit. Each redirect URI is checked on its own:

Redirect URI Public Confidential
https://… yes yes
http://localhost, http://127.0.0.1, http://[::1] yes yes
A reverse-domain private-use scheme (RFC 8252 §7.1), for example com.example.app:/callback yes no
http:// on any other host, single-word schemes (myapp:, javascript:, data:, file:), a fragment, or user info no no

Loopback IP redirects may use any port. See Redirect URIs.

Settings, under options.DeveloperApps:

Option Default
RequireApproval false New apps start as PendingApproval and cannot sign anyone in until an admin approves them.
MaxAppsPerUser 10 A user at the limit gets 409.
MaxRedirectUris 10

Admin review is in IOAuthDeveloperAppService, not in the mapped API, because only your app knows who an admin is. ListByStatusAsync(OAuthDeveloperAppStatus.PendingApproval) returns the review queue, and SetStatusAsync approves (Active) or turns an app off (Disabled). Setting any status other than Active through SetStatusAsync revokes the app's authorizations and tokens. The authorize endpoint answers unauthorized_client for an app that is not active, and so does the token endpoint for a code or refresh token issued before the change. Protect your admin endpoints yourself.

With RequireApproval, an edit that changes an active app's name or redirect URIs sends it back to PendingApproval, so an owner cannot swap in a new redirect or a misleading name after approval. Until an admin approves it again, new sign-ins and token refreshes get unauthorized_client. Existing grants are not revoked, so they work again once the app is approved. Access tokens that were already issued keep working until they expire. Homepage and description edits do not need review, and editing a disabled app leaves it disabled.

The owner methods of the same service (ListAsync, CreateAsync, UpdateAsync, …) take the caller's user id, for hosts that want their own routes.

When an owner's account is deleted, the cascade removes the app's row. From then on, the authorize and token endpoints refuse its client, and the next cleanup pass deletes it. Developer apps are never treated as unused dynamic registrations.

Developer apps and dynamic registration are separate. Anonymous registration stays the path for native apps and CLIs that register themselves. Developer apps are for people building an integration with your service. On the user side, the connected apps routes disconnect one app from one account.

Redirect URIs

An authorize request's redirect_uri must match one of the client's registered redirect URIs exactly, with one exception from RFC 8252 §7.3: on a loopback IP literal, http://127.0.0.1 or http://[::1], the port may differ. A native app or CLI can register http://127.0.0.1/callback and listen on whatever port is free. The scheme, host, path, and query must still match, so http://127.0.0.1:51234/callback matches a registered http://127.0.0.1:9/callback, but /other, 127.0.0.2, or [::1] do not. This applies to every client: from configuration, dynamic registration, or developer apps.

localhost is matched exactly, port included. RFC 8252 §8.3 recommends the IP literals over localhost, so register http://127.0.0.1/… for a native app. The token request must repeat the redirect_uri sent at authorize, port included.

The authorize endpoint never shows a page. When the user is signed in, it stores a pending request and redirects to:

{ConsentUrl}?request={id}

When the user is signed out, it redirects to:

{LoginUrl}?returnUrl=/connect/authorize?client_id=…

returnUrl is a path on this server, rebuilt from the incoming request. After sign-in, send the browser there (prefix it with the server's origin if your login page is on another origin) and the flow resumes. The user is read from AuthenticationScheme (default: the Identity application cookie), so bearer-only apps need the cookie enabled for this step. prompt=none returns login_required or consent_required to the client instead of a page.

MapOAuthServer() maps (or MapOAuthConsentEndpoints("/oauth") without the recipe), for the signed-in user:

Route Response
GET /oauth/requests/{id} { id, clientId, clientName, redirectHost, scopes, scopeDetails, resource, expiresAt, homepageUrl, description, confidential, owner, clientHost }
POST /oauth/requests/{id}/approve { redirectUrl } with code, state, and iss
POST /oauth/requests/{id}/deny { redirectUrl } with error=access_denied

The POSTs require a CSRF token from every caller, an OAuth access token included (RequireAntiforgery(allowBearer: false)). Unknown, expired, used, and other users' requests are all 404. Your consent page shows clientName and redirectHost, then sends the browser to redirectUrl. For a client identified by a client ID metadata document, clientHost is the host of its client_id URL; show it next to the name, because that domain published the name. It is null for other clients. See Client ID metadata documents.

The client is checked again when the user answers, because it can be deleted or edited, or a developer app disabled or sent back to review, after /connect/authorize stored the request. A request whose client no longer exists, whose developer app is not Active, or whose redirect URI is no longer registered for the client (with the same loopback any-port rule as authorize), is also 404 on all three routes (OAuthConsentStatus.NotFound from IOAuthConsentService). No code is issued, and deny does not redirect to that client. Approve and deny consume the request, so re-enabling the app does not revive it; the user starts a new authorize request. The card fetch does not consume it.

Scope descriptions

A person approving a client should read "Read your reports", not reports.read. Describe each scope once, in code or appsettings, optionally per culture:

{
  "OAuthServer": {
    "Scopes": [ "reports.read" ],
    "ScopeDefinitions": [
      {
        "Name": "reports.read",
        "DisplayName": "Read your reports",
        "Description": "See the reports you can open. It cannot change them.",
        "DisplayNames": { "fr": "Lire vos rapports" },
        "Descriptions": { "fr": "Voir les rapports que vous pouvez ouvrir. Il ne peut pas les modifier." }
      },
      { "Name": "offline_access", "DisplayName": "Stay connected", "Description": "Keep access when you are not using the app." }
    ]
  }
}

The card then has scopeDetails next to scopes, in the same order:

"scopes": [ "reports.read", "offline_access" ],
"scopeDetails": [
  { "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 when you are not using the app." }
]
  • scopes stays a list of names, so existing consent pages keep working. Read scopeDetails for the words.
  • The text is resolved for the request culture (CultureInfo.CurrentUICulture, which UseRequestLocalization sets from Accept-Language, a cookie, or the query string): the culture (pt-BR), then its parents (pt), then DisplayName and Description. A scope without a definition gets its name as displayName and null as description.
  • Each Name must be in Scopes, or be offline_access, and appear once. Culture keys must be culture names. A wrong entry fails at startup.
  • OAuthPendingRequest.ScopeDetails has the same list for IOAuthConsentService.FindAsync and principal factories.
  • The text comes from your configuration, never from the client, so a client cannot change what the card says a scope does.
  • The text is resolved by IOAuthScopeDescriptions. The default reads ScopeDefinitions. To load it from a database or resource files instead, implement the interface and register it with AddScopeDescriptions<T>() on the server builder (or before AddOAuthServer, which only adds the default when none is registered). It is called on every card fetch and approval, so cache anything slow.
Developer app details on the card

When the client is a developer app, the card also tells the user what they are approving, since another user built it:

Field Value
homepageUrl The app's homepage.
description The app's description, or null when it has none.
confidential true for an app with a client secret (a server-side app), false for a public app (SPA, native, CLI).
owner Who built the app, from your IOAuthDeveloperAppOwnerDisplay. null unless you register one.

For seeded and dynamically registered clients all four are null. OAuthPendingRequest (from IOAuthConsentService.FindAsync, and OAuthPrincipalContext.Request on approve) has the same fields.

clientName is copied when /connect/authorize runs, as before. The other fields are read from the app when the card is fetched, in the same query as the request, so an owner's homepage or description edit shows up on a pending card.

The owner's email and user name may be private, so the package never shows them. To show something, such as a developer or organization name the owner chose to make public, register a display:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options => { … })
    .AddDeveloperAppOwnerDisplay<DeveloperProfileOwnerDisplay>();

public sealed class DeveloperProfileOwnerDisplay(AppDbContext db) : IOAuthDeveloperAppOwnerDisplay
{
    public async ValueTask<string?> GetOwnerAsync(OAuthDeveloperAppOwnerContext context, CancellationToken ct)
        => await db.DeveloperProfiles
            .Where(profile => profile.UserId == context.OwnerId && profile.Public)
            .Select(profile => profile.DisplayName)
            .FirstOrDefaultAsync(ct);
}

It is called once per card fetch for a developer app, with the app id, client id, and owner id. null or blank text shows owner: null.

Option B: your own approve endpoint

When the consent page has extra choices, call IOAuthConsentService from your own endpoint:

app.MapPost("/api/oauth/requests/{id:guid}/approve", async (
    Guid id, ApproveBody body, ClaimsPrincipal user, IOAuthConsentService consent, AppDbContext db) =>
{
    var userId = user.FindFirstValue(ClaimTypes.NameIdentifier)!;
    await using var transaction = await db.Database.BeginTransactionAsync();
    var result = await consent.ApproveAsync(id, userId, async context =>
    {
        var agent = await db.Agents.FindAsync(body.AgentId);
        if (agent?.OwnerId != userId)
        {
            return null; // declined: the request is not consumed
        }

        return OAuthPrincipals.ForSubject(agent.Id.ToString());
    });

    if (result.Status != OAuthConsentStatus.Approved)
    {
        return Results.NotFound();
    }

    db.Grants.Add(new Grant { UserId = userId, AuthorizationId = result.AuthorizationId! });
    await db.SaveChangesAsync();
    await transaction.CommitAsync();
    return Results.Ok(new { redirectUrl = result.RedirectUrl });
}).RequireAuthorization().RequireAntiforgery(allowBearer: false);

The service uses the scoped DbContext, so your transaction also covers the OpenIddict rows. Keep RevokeAuthorizationAsync(authorizationId) for a "disconnect app" button: it revokes the authorization and every token from it.

Bind a host context to the grant

To keep a client in the organization, workspace, or region the person chose at consent, do not read the person's stored current context on token calls. Instead:

  1. Post the choice to your own approve endpoint. Check membership, then call ApproveAsync(id, userId, createPrincipal) and add a claim such as org_id with SetDestinations(OpenIddictConstants.Destinations.AccessToken). It is kept in the refresh token, so every access token from the grant carries it.
  2. In the API, read the claim when User.IsOAuthDelegated().
  3. To re-check membership at refresh, replace IOAuthUserValidator with a wrapper around IdentityOAuthUserValidator<TUser> and override ValidateAsync(OAuthUserValidationContext context, …). It runs at every code exchange and refresh, and context.Grant holds the claims of the code or refresh token, such as org_id, with the package's internal claims and OpenIddict's oi_* claims removed. Call the Identity checks with context.UserId and context.SecurityStamp, then check membership. Register it with services.Replace(ServiceDescriptor.Scoped<IOAuthUserValidator, …>()) after AddOAuthServer. ValidateAsync defaults to IsValidAsync(userId, stamp), so older validators keep working.

The full, tested code is in the guide Bind a host context to an OAuth grant.

Who is the token subject

By default sub is the Identity user id. Replace it for every approval:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(…)
    .AddPrincipalFactory<MyPrincipalFactory>();

IOAuthPrincipalFactory.CreateAsync gets the signed-in user id and the pending request, and returns the principal (or null to decline without consuming the request). The principal needs a sub claim. Other claims reach the access token only when you call SetDestinations on them.

With OpenID Connect, the ID token sub is the same sub, so a custom factory changes both. See Claims.

With AccessTokenClaims on, the user's roles and id are added only while sub is the approving user's id. See Roles and the user id on tokens.

Who is the token subject

By default sub is the Identity user id. Replace it for every approval:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(…)
    .AddPrincipalFactory<MyPrincipalFactory>();

IOAuthPrincipalFactory.CreateAsync gets the signed-in user id and the pending request, and returns the principal (or null to decline without consuming the request). The principal needs a sub claim. Other claims reach the access token only when you call SetDestinations on them.

With OpenID Connect, the ID token sub is the same sub, so a custom factory changes both. See Claims.

With AccessTokenClaims on, the user's roles and id are added only while sub is the approving user's id. See Roles and the user id on tokens.

When the user changes

Each grant remembers the user who approved it and that user's security stamp. On every code exchange and refresh, the server checks that the user still exists, can sign in (SignInManager.CanSignInAsync), is not locked out, and has the same security stamp. If any check fails, the request gets invalid_grant, and the authorization and all its tokens are revoked.

Identity changes the security stamp when the password changes or is reset, an authenticator is reset, two-factor is turned off, or an external login is removed. Call UserManager.UpdateSecurityStampAsync(user) to end every OAuth grant for a user on demand, for example from a "sign out everywhere" button.

The check happens at the token endpoint, so an access token that was already issued keeps working until it expires (15 minutes by default) or until the client next refreshes. To stop it sooner, call IOAuthConsentService.RevokeAuthorizationAsync.

The approving user's id and stamp are stored in the code and refresh token only. They are never copied into access tokens or ID tokens, even when a principal factory sends every claim to the access token. The user id is also kept on the authorization in the database, so userinfo, logout, audit events, and the connected apps list can find the user. Replace IOAuthUserValidator to apply your own rules, or set RevalidateUser = false to turn the check off.

Connected apps

A signed-in person can see which clients they connected and disconnect one. MapOAuthServer maps two JSON routes for that, at /oauth/authorizations (parts.ConnectedApps, parts.ConnectedAppsPrefix):

Route Response
GET /oauth/authorizations [{ authorizationId, clientId, clientName, clientKind, clientHost, scopes, scopeDetails, resource, createdAt, lastUsedAt }], newest first
DELETE /oauth/authorizations/{authorizationId} 204, or 404 when the grant is unknown, someone else's, or already revoked
  • Only live grants are listed: not revoked, and still holding a valid token. A grant whose refresh token expired drops off.
  • A grant belongs to the user who approved it, even when a principal factory issued its tokens for another sub.
  • clientKind is configured, dynamic, metadata_document, or developer_app (OAuthClientKinds). clientHost is the host of a metadata document client's URL, or of a developer app's homepage, and null for other clients, whose names are self-asserted.
  • lastUsedAt is null unless RecordLastUsed is on.
  • The routes authenticate with AuthenticationScheme (the Identity cookie), so an OAuth access token cannot list or revoke grants. The DELETE needs a CSRF token (RequireAntiforgery(allowBearer: false)).
  • Disconnecting revokes the grant and every token from it, and raises AuthorizationRevoked with RevokedBy = User.

For your own page, or for an admin page about another user, call IOAuthConnectedAppService. The package does not decide who is an admin: check that first.

app.MapDelete("/admin/users/{userId}/connected-apps/{authorizationId}", async (
        string userId, string authorizationId, ClaimsPrincipal admin, IOAuthConnectedAppService apps) =>
    await apps.RevokeAsync(userId, authorizationId, OAuthRevokedBy.Admin, admin.FindFirstValue(ClaimTypes.NameIdentifier))
        ? Results.NoContent()
        : Results.NotFound())
    .RequireAuthorization("admin")
    .RequireAntiforgery(allowBearer: false);

ListAsync(userId) returns the same items as the GET route.

Audit events

Implement IOAuthServerEvents to keep an audit trail of what the OAuth server did, and register it with AddServerEvents<T>(). Register as many as you need; each gets every event, in registration order. With none registered (the default), nothing is raised.

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options => { /* … */ })
    .AddServerEvents<OAuthAuditLog>();

public sealed class OAuthAuditLog(AppDbContext db) : IOAuthServerEvents
{
    public async ValueTask OnEventAsync(OAuthServerEvent e, CancellationToken cancellationToken)
    {
        db.AuditEntries.Add(new AuditEntry(e.Type.ToString(), e.OccurredAt, e.UserId, e.ClientId, e.AuthorizationId));
        await db.SaveChangesAsync(cancellationToken);
    }
}
Type Raised when
ConsentApproved The user approved a consent request and a code was issued.
ConsentDenied The user denied a consent request.
CodeExchanged The client exchanged the code for tokens.
TokenRefreshed The client refreshed.
GrantRefused A code exchange or refresh was refused by user revalidation. The grant was revoked. GrantType says which grant.
AuthorizationRevoked A grant was revoked. RevokedBy is User, Admin (also IOAuthConsentService.RevokeAuthorizationAsync and an admin turning a developer app off), Cleanup (a developer app whose owner is gone), or ClientDeleted (a developer app deleted by its owner).
ClientRegistered Dynamic registration, the first stored copy of a client ID metadata document, or a new developer app (UserId is its owner).

Each event has UserId (the approving user, even when a principal factory chose another sub), ClientId, ClientKind (configured, dynamic, metadata_document, or developer_app; see OAuthClientKinds), AuthorizationId, Scopes, and Resource, where they apply. Events never carry a token, an authorization code, a client secret, or the security stamp.

Subscribers are scoped and run in the request, one after another, so keep them fast or hand the event to a queue. A subscriber that throws is logged (event type and subscriber type only) and skipped: the OAuth response does not change and the next subscriber still runs. Calls to your own API are not events; audit those in the API.

Events follow your transaction. When you call IOAuthConsentService or IOAuthConnectedAppService while a transaction is open on the server's DbContext (db.Database.BeginTransactionAsync(), as in your own approve endpoint), the events wait: subscribers get them once the transaction commits, and never if it rolls back, so an audit log does not record a grant that was rolled back. Commit or roll back through the IDbContextTransaction EF Core returned. A transaction EF Core cannot see (TransactionScope, or a DbTransaction you commit yourself) does not hold events back. Without a transaction, events are raised at once.

Last used

Set RecordLastUsed = true to record when each grant was last used. The time is written to the authorization at the code exchange and at a refresh, at most once per LastUsedInterval (1 hour by default), so a client that refreshes every few minutes does not write on every refresh. A call to the API with an access token does not update it. A write that loses a race with another request is skipped, and the grant is reloaded so later writes in the same token request still succeed; the next refresh records the time.

The package also stores the approving user's id and the approved resource on every authorization (properties ae_user_id and ae_resource, see OAuthServerConstants).

OpenID Connect (optional)

Add the openid scope to turn on OpenID Connect. Without it, the server stays OAuth 2.0 only: openid is rejected and the routes below do not exist.

options.Scopes.Add("openid");
options.Scopes.Add("email");                            // optional: releases email and email_verified
options.LogoutUrl = "https://app.example.com/sign-out"; // optional: see Logout

OAuthRequests has two nullable columns for OpenID Connect, Nonce and AuthenticationMethods. If you created the tables from an earlier build of this package, add a migration, whether or not you turn OpenID Connect on.

Route Served by Notes
GET /.well-known/openid-configuration OpenIddict Discovery. The same document as the RFC 8414 metadata, with endpoint URLs from Issuer, never from the request Host.
GET\|POST /connect/userinfo this package sub, plus the email claims with the email scope.
GET\|POST /connect/logout this package RP-initiated logout.
GET /.well-known/jwks OpenIddict The keys that validate ID tokens.

A request with openid gets an id_token from the token endpoint, on the code exchange and on every refresh. It is a JWT signed with the signing certificate (RS256). It lasts 20 minutes, OpenIddict's default; change it with builder.OpenIddict.AddServer(o => o.SetIdentityTokenLifetime(…)).

Claims

Claim In Value
iss ID token Issuer.
aud, azp ID token The client id.
sub ID token, userinfo, access token From IOAuthPrincipalFactory: the Identity user id by default.
nonce ID token The authorize request's nonce, when it sent one. At most 512 characters.
amr ID token How the user signed in. See How the user signed in. Left out when unknown.
email, email_verified ID token, userinfo With the email scope only. email_verified is the user's EmailConfirmed.

These claims never reach access tokens. An access token still carries sub, plus what your principal factory sends to it.

The email claims come from the Identity user only when sub is that user's id. A principal factory that issues tokens for another subject (a service account the user picked, say) does not get the approving user's email attached to it. A claim the factory already set is kept as it is.

ID token claims are read when the user approves, and a refreshed ID token repeats them. userinfo reads the user on every call.

How the user signed in

Sign-in amr
Password ["pwd"]
Password, then an authenticator or recovery code ["pwd", "otp", "mfa"]
Passkey, when Identity requires user verification (the .NET default) ["pop", "mfa"]
Passkey, when it does not ["pop"]
External provider (GitHub, Google, …) ["fed"]
Email code ["otp"]

The values are from RFC 8176, except fed: RFC 8176 has none for a federated sign-in, and fed is the value Microsoft Entra ID uses. A recovery code counts as a one-time code, like an authenticator code. A passkey is mfa only when IdentityPasskeyOptions.UserVerificationRequirement is required: Identity then rejects any passkey sign-in where the authenticator did not check a PIN or biometric, so the key and that check are two factors. With preferred or discouraged, the check may not have happened, so a passkey is pop alone.

amr is read from the sign-in cookie when /connect/authorize runs. AuthEndpoints password sign-in already writes amr to the cookie (pwd, or mfa after a second factor), and so do Identity's PasswordSignInAsync and TwoFactorSignInAsync. Passkey, external, and email-code sign-in write nothing, so with openid on, this package wraps the sign-in completers and adds amr to the cookie they write. That covers the built-in Cookie and IdentityBearer completers, every ISignInCompleter<TUser> you register before AddOAuthServer under any name, and your own obsolete IPasskeySignInCompleter, IEmailCodeSignInCompleter, or IExternalLoginCompleter. The built-in obsolete completers are left as they are, because AuthEndpoints only routes to an obsolete completer that is not the built-in type. It also keeps amr when Identity's security stamp check rebuilds the cookie, which otherwise drops it.

amr is left out when the cookie does not say: a session signed in before openid was turned on (it gets amr at its next sign-in), a completer registered after AddOAuthServer, or a plain SignInManager.SignInAsync outside a completer. MapOAuthServer logs a warning that names every completer registered too late. To supply amr yourself, add an amr claim to the cookie principal when you sign the user in.

userinfo

GET or POST /connect/userinfo with an access token that has the openid scope returns sub, and with the email scope also email and email_verified. A token without openid gets 403 with insufficient_scope. A token whose user was deleted gets 401 with invalid_token when it asks for the email claims.

Logout

GET or POST /connect/logout follows OpenID Connect RP-Initiated Logout 1.0 (id_token_hint, client_id, post_logout_redirect_uri, state):

  • post_logout_redirect_uri must exactly match a post-logout redirect URI registered for the client that client_id or id_token_hint names. Without either, or with any other URI, the request gets 400 and the browser is not redirected. A disabled or unapproved developer app gets 400 too.
  • A signed-in user is signed out (the Identity application, external, and two-factor cookies) only when id_token_hint is an ID token that this server issued to that user. Otherwise the user stays signed in. When LogoutUrl is set, the browser goes there with the logout URL in returnUrl; your page asks the user, signs them out, and sends the browser back to returnUrl, which then completes. Without LogoutUrl, the request gets 400. A link on another site cannot sign your users out.
  • A signed-out browser goes straight to the validated post_logout_redirect_uri, with state. With no post_logout_redirect_uri, the endpoint answers 200 with no body.

Each client registers its own post-logout redirect URIs:

Client Where
From configuration PostLogoutRedirectUris on the entry in options.Clients.
Dynamic registration post_logout_redirect_uris, under the same rules as redirect_uris.
Developer apps postLogoutRedirectUris in the create and edit body, under the same rules as redirectUris, and returned with the app. Leave it out of an edit to keep the list. With RequireApproval, a change sends an active app back to review.

Client permissions

A client gets the openid scope and the logout endpoint permission when openid is among its scopes: every configured scope by default, or the Scopes of a configured client. Unlike plain OpenIddict, openid needs that permission here, so a configured client whose Scopes leave it out cannot use OpenID Connect. Clients that existed before you added openid get the permissions at the next SeedOAuthClientsAsync (configured clients) or the next edit (developer apps). A dynamically registered client keeps the permissions it registered with, so it registers again.

prompt=login and max_age are refused with invalid_request instead of being ignored, because the server does not record when the user signed in.

Certificates

Set exactly one source in options.Certificates:

Setting Use it for
Path A self-signed RSA signing and encryption pair, created on first start in that directory and reused. Treat the directory like Data Protection keys: persistent, private, and shared by every instance. Files are created with owner-only permissions on Linux and macOS.
SigningCertificate + EncryptionCertificate Certificates you manage (Key Vault, a mounted secret, the machine store). Both need a private key.
UseEphemeralKeys Tests and local runs only. Keys are lost on restart, which invalidates every issued token.

To rotate, add the new certificates through builder.OpenIddict.AddServer(o => o.AddSigningCertificate(…)) before removing the old ones, so tokens signed with the old key still validate until they expire.

Protected resource metadata (optional)

For APIs whose clients discover the authorization server on their own (MCP clients, for example):

options.ProtectedResource.Enabled = true;
options.ProtectedResource.ResourceName = "My API";
options.ProtectedResource.ChallengePaths.Add("/mcp");

app.UseOAuthResourceChallenge(); // before UseAuthentication

GET /.well-known/oauth-protected-resource returns Audience, the issuer, and the scopes (ProtectedResource.Scopes, or every scope when it is empty). A 401 on a challenge path gets WWW-Authenticate: Bearer resource_metadata="…/.well-known/oauth-protected-resource". Existing Bearer parameters are kept.

One document per resource

When this host serves more than one resource (see One host, more than one resource), each needs its own document, because a client checks that the document's resource is the URL it called. Audience and every AcceptedAudiences entry whose identifier has a path get a document at the RFC 9728 path-suffixed URL: https://auth.example.com/mcp is described at https://auth.example.com/.well-known/oauth-protected-resource/mcp. Name a resource, list its scopes, and send its 401 responses there with an entry in ProtectedResource.Resources:

options.Audience = "https://auth.example.com/api";
options.AdditionalResources.Add("https://auth.example.com/mcp");
options.AcceptedAudiences.Add("https://auth.example.com/mcp");

options.ProtectedResource.Enabled = true;
options.ProtectedResource.ResourceName = "My API";
options.ProtectedResource.ChallengePaths.Add("/api");
options.ProtectedResource.Resources.Add(new OAuthProtectedResourceDefinition
{
    Resource = "https://auth.example.com/mcp",
    ResourceName = "My MCP server",
    Scopes = { "mcp" },
    ChallengePaths = { "/mcp" },
});

A 401 on /mcp then points at …/.well-known/oauth-protected-resource/mcp, and one on /api at the root document. The longest matching challenge path wins. When ProtectedResource.ChallengePaths is empty, every path that no resource claims points at the root document. An accepted resource without an entry still gets a document, with no name and every scope. Scopes is the document's scopes_supported: it tells clients what to ask for and does not limit what a token may hold.

The document URL takes its host from the resource identifier, and the endpoint never reads the request Host header. Clients fetch it from the resource's host, so that host has to route /.well-known/oauth-protected-resource/… to this app. Two accepted resources with the same path on different hosts (https://a.example/mcp and https://b.example/mcp) cannot be told apart: neither gets a path-suffixed document, and startup fails when a Resources entry names one of them. Startup also fails when an entry names a resource that is not in AcceptedAudiences, names Audience (use the top-level ResourceName, Scopes, and ChallengePaths), has no path or has a query, lists a scope that is not configured, or repeats a challenge path.

Under a PathBase

RFC 9728 puts the well-known segment between the host and the resource's path, so for an app mounted at /app (Issuer https://host/app/, resource https://host/app/mcp) the 401 points at https://host/.well-known/oauth-protected-resource/app/mcp, outside /app. Route that path to the app at the reverse proxy (or from an app at the root). The app answers it both ways:

  • forwarded unchanged, as /.well-known/oauth-protected-resource/app/mcp;
  • under its PathBase, as /app/.well-known/oauth-protected-resource/mcp, the location relative to the app, for clients that look there.

The app takes its PathBase from the Issuer path. At startup, a warning lists accepted resources on the issuer's host whose path is outside it: their documents are reachable only when the proxy forwards the RFC 9728 URL to this app unchanged. The root document is served at {Issuer}.well-known/oauth-protected-resource (/app/.well-known/oauth-protected-resource) and describes Audience.

Expose an MCP server with per-user OAuth

An AI assistant or other MCP client connects to an MCP server your app hosts, and each person signs in as themselves. The assistant's token carries that person's roles and only the scopes they approved. The full guide walks through every step. In short, for an app that serves /api to cookie users and /mcp to assistants:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options =>
{
    options.Issuer = new Uri("https://app.example.com/");
    options.Audience = "https://app.example.com/api";
    options.AdditionalResources.Add("https://app.example.com/mcp");
    options.AcceptedAudiences.Add("https://app.example.com/mcp");
    options.Scopes.Add("mcp");
    options.Scopes.Add("reports.read");
    options.LoginUrl = "https://app.example.com/sign-in";
    options.ConsentUrl = "https://app.example.com/oauth/consent";
    options.Certificates.Path = "/var/lib/myapp/oauth-keys";

    options.ClientMetadataDocuments.Enabled = true; // preferred by the MCP spec
    options.DynamicRegistration.Enabled = true;     // fallback
    options.DynamicRegistration.AllowedScopes.Add("mcp");
    options.DynamicRegistration.AllowedScopes.Add("reports.read");

    options.ProtectedResource.Enabled = true;
    options.ProtectedResource.Resources.Add(new OAuthProtectedResourceDefinition
    {
        Resource = "https://app.example.com/mcp",
        ResourceName = "Example MCP server",
        Scopes = { "mcp", "reports.read" },
        ChallengePaths = { "/mcp" },
    });

    options.AccessTokenClaims.Roles = true;
    options.AccessTokenClaims.UserId = true;
});

builder.Services.AddAuthorization(options => options.AddPolicy("mcp", policy => policy
    .RequireOAuthAudience("https://app.example.com/mcp")
    .RequireOAuthScope("mcp")
    .RequireRole("Member")));

app.UseOAuthResourceChallenge();
app.UseAuthEndpoints();
app.MapOAuthServer();
app.MapMcp("/mcp").RequireAuthorization("mcp"); // or your own MCP endpoint
  • Discovery. A 401 on /mcp points at /.well-known/oauth-protected-resource/mcp, which names this authorization server.
  • Identification. The assistant uses a client ID metadata document or registers. Both are public clients held to DynamicRegistration.AllowedScopes, so keep first-party scopes out of that list.
  • Consent. Your page shows clientName with clientHost (or redirectHost), and the scopes from scopeDetails. Describe them in ScopeDefinitions.
  • Tokens. The assistant asks for resource=https://app.example.com/mcp. RequireOAuthAudience keeps that token on /mcp, RequireOAuthScope checks the grant, and the role check is the one cookie users go through. Inside tool handlers, use User.IsOAuthDelegated() and User.HasOAuthScope(...).
  • Shared routes. On routes that cookie users also call, use RequireOAuthScopeWhenDelegated(...) next to the existing role check, and check the audience only for token callers. A refused token caller gets 403, not the cookie's redirect (BearerRequestsSkipCookieRedirects, on by default).
  • Disconnecting. The connected apps routes (GET /oauth/authorizations, DELETE /oauth/authorizations/{id}) let the person see and disconnect each assistant; IOAuthConnectedAppService does the same for an admin page. UserManager.UpdateSecurityStampAsync(user) ends every grant at its next refresh.

A scope never widens what the person may do: keep every route's existing role or policy check.

Rate limits

OpenIddict serves /connect/token and /connect/revoke from its middleware, during UseAuthentication, so RequireRateLimiting cannot reach them. Turn on the built-in limit instead:

options.TokenRateLimit.Enabled = true;       // default false
options.TokenRateLimit.PermitLimit = 60;     // per endpoint, client id, and IP address
options.TokenRateLimit.PermitLimitPerAddress = null; // per endpoint and IP address; null means 4 × PermitLimit
options.TokenRateLimit.Window = TimeSpan.FromMinutes(1);

The check runs inside OpenIddict, after the request is parsed and before client authentication or any database read. A request over the limit gets an OAuth error with 429 Too Many Requests and Retry-After (seconds):

HTTP/1.1 429 Too Many Requests
Retry-After: 42

{ "error": "temporarily_unavailable", "error_description": "Too many requests. Try again later." }

A request needs a permit from two limits. The first counts every request from one IP address to the endpoint, whatever client_id it sends (PermitLimitPerAddress, 4 × PermitLimit by default). The client_id is read before the client is authenticated, so without it a caller could send a new made-up value on each request and get a fresh window every time. The second counts per IP address and client_id (PermitLimit), so one noisy client behind a shared address does not use up the others' budget. Requests without a client_id share one window per IP address.

Behind a reverse proxy, call UseForwardedHeaders first, or every client shares the proxy's address. Many users behind one NAT share the per-address limit, and those who use the same configured client share the per-client one too, so size both for that: a client refreshes about once per AccessTokenLifetime.

For another algorithm or partition, pass your own limiter. It replaces the built-in one and turns the limit on:

builder.Services.AddOAuthServer<AppUser, AppDbContext>(options => { /* … */ })
    .AddTokenRateLimiter(_ => PartitionedRateLimiter.Create<OAuthRateLimitContext, string>(context =>
        RateLimitPartition.GetTokenBucketLimiter(
            $"{context.Endpoint}:{context.ClientId}",
            _ => new TokenBucketRateLimiterOptions { TokenLimit = 20, TokensPerPeriod = 20, ReplenishmentPeriod = TimeSpan.FromMinutes(1) })));

OAuthRateLimitContext has the HttpContext, the Endpoint (Token or Revocation), and the ClientId as sent (not yet authenticated).

Dynamic registration has its own limit (DynamicRegistration.PermitsPerMinute). /connect/authorize and the JSON APIs are endpoints, so RequireRateLimiting works on them: MapOAuthServer returns their groups (oauth.Consent!.RequireRateLimiting("consent")).

Settings

Option Default
Issuer required Absolute; https unless DisableTransportSecurityRequirement. Use the app root (https://host/), or the app's PathBase.
Audience required Default resource. This host always accepts it.
AdditionalResources empty Other resources clients may request. Rejected by this host unless also in AcceptedAudiences.
AcceptedAudiences empty Resources (Audience or AdditionalResources entries) this host's validation also accepts. Check aud per route, see One host, more than one resource.
Scopes / DefaultScopes empty offline_access is always registered. Add openid for OpenID Connect, and email for the email claims.
ScopeDefinitions empty Display names and descriptions for the consent card, optionally per culture. See Scope descriptions.
AlwaysIssueRefreshToken true Adds offline_access when the client has the refresh grant.
LoginUrl, LoginReturnUrlParameter required, returnUrl
ConsentUrl, ConsentRequestParameter required, request
LogoutUrl none OpenID Connect only. The sign-out page for a logout without a matching id_token_hint. Gets the logout URL in LoginReturnUrlParameter.
AuthenticationScheme, UserIdClaimType Identity cookie, NameIdentifier
BearerRequestsSkipCookieRedirects true A request with Authorization: Bearer gets 401/403 instead of the sign-in cookie's redirects. See Token callers and cookie redirects.
AccessTokenLifetime 15 minutes
RefreshTokenLifetime 30 days Rotating, no reuse leeway.
AuthorizationCodeLifetime 5 minutes
ConsentLifetime 10 minutes
DynamicRegistration off See Dynamic registration. AllowedScopes, MaxRedirectUris, MaxClientNameLength, and UnusedClientLifetime also apply to metadata document clients.
ClientMetadataDocuments off; 5 s, 5 KB, cache 5 min to 24 h, 20 fetches per minute See Client ID metadata documents.
DeveloperApps approval off, 10 apps, 10 redirects See Developer apps.
CleanupInterval, PruneAfter 1 hour, 14 days Background sweep of unused clients, developer apps without an owner, expired consents, old tokens. Zero turns it off; IOAuthServerCleanup.SweepAsync runs it on demand.
RevalidateUser true Re-check the approving user on every code exchange and refresh.
RecordLastUsed, LastUsedInterval off, 1 hour Record when each grant was last used, at most once per interval. See Last used.
TokenRateLimit off; 60 per minute Per endpoint, client id, and IP on /connect/token and /connect/revoke. 429 with temporarily_unavailable and Retry-After. See Rate limits.
AccessTokenClaims off Roles and UserId add the approving user's Identity roles and user id to access tokens. See Roles and the user id on tokens.
DisableTransportSecurityRequirement false Local development only.
DisableResourceValidation false Token endpoint only. Authorize still accepts configured resources only.
IgnoreResourcePermissions false Skips per-client rsrc: permissions.
QueryStringTokenPaths empty Path prefixes that also accept ?access_token=, for SignalR and WebSockets. Elsewhere only Authorization: Bearer is read. See Where the token is read from.

The fixed routes are in OAuthServerConstants. Anything else can be set on OAuthServerBuilder.OpenIddict.

How this relates to external sign-in

External providers (AuthEndpoints.OAuth.GitHub, AuthEndpoints.OAuth.Google) let users sign in to your app with another account. This package makes your app the provider for other clients. They combine: with cookie-mode external sign-in, a user who signs in with GitHub has an Identity cookie, and the authorize step accepts it like any other sign-in. JWT-mode sign-in does not set that cookie.

Limitations

This is a preview. These are known gaps, not bugs:

  • OpenID Connect covers sign-in and logout, not every option. The claims are sub, email, email_verified, and amr; there are no profile, phone, or address claims, and no auth_time, so prompt=login and max_age are refused. Logout is RP-initiated only: there is no front-channel or back-channel logout and no session (sid) claim. There is no implicit or hybrid flow, so ID tokens come from the token endpoint only.
  • amr depends on the cookie. A session signed in before openid was turned on has no amr until the user signs in again, and neither does a sign-in through a completer registered after AddOAuthServer. See How the user signed in.
  • Only this server validates tokens. Access tokens are reference tokens, so an API in another process cannot validate them. There is no introspection endpoint and no JWT access token option yet.
  • Issued access tokens outlive a user change. A locked-out user or a changed password stops the grant at the next code exchange or refresh. An access token that was already issued works until it expires. See When the user changes.
  • Fixed routes. The endpoints are always under /connect and /.well-known (see OAuthServerConstants), relative to the app's PathBase.
  • Client ID metadata documents are public clients only. private_key_jwt with jwks or jwks_uri is not supported yet; a document that offers only that method is refused with invalid_client.
  • Cookie sign-in only at the authorize step. The user is read from AuthenticationScheme (the Identity cookie by default). Password, two-factor, passkey, and cookie-mode external sign-in all end with that cookie. A sign-in that is still waiting for a second factor, or an external sign-in that has not been completed, does not count.

An OIDC client for AuthEndpoints (the other direction) is tracked separately in issue #380.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.0-preview.5 63 11/21/2026
4.0.0-preview.1 274 11/6/2026