Wiaoj.WellKnown.Discovery 0.5.1-alpha

This is a prerelease version of Wiaoj.WellKnown.Discovery.
dotnet add package Wiaoj.WellKnown.Discovery --version 0.5.1-alpha
                    
NuGet\Install-Package Wiaoj.WellKnown.Discovery -Version 0.5.1-alpha
                    
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="Wiaoj.WellKnown.Discovery" Version="0.5.1-alpha" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Wiaoj.WellKnown.Discovery" Version="0.5.1-alpha" />
                    
Directory.Packages.props
<PackageReference Include="Wiaoj.WellKnown.Discovery" />
                    
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 Wiaoj.WellKnown.Discovery --version 0.5.1-alpha
                    
#r "nuget: Wiaoj.WellKnown.Discovery, 0.5.1-alpha"
                    
#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 Wiaoj.WellKnown.Discovery@0.5.1-alpha
                    
#: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=Wiaoj.WellKnown.Discovery&version=0.5.1-alpha&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Wiaoj.WellKnown.Discovery&version=0.5.1-alpha&prerelease
                    
Install as a Cake Tool

Wiaoj.WellKnown.Discovery

Finds out, from a protected API itself, which authorization server issues its tokens and where that server's endpoints are. It reads RFC 9728 protected resource metadata and then RFC 8414 authorization server metadata. Each document is validated before it is used.

It uses Microsoft.Extensions.Http for HTTP client registration, Wiaoj.Http for HTTP primitives, and neutral Wiaoj.WellKnown for the shared metadata URIs and builder. Discovery does not require the ASP.NET Core server package, the ASP.NET Core shared runtime, or a JWT/token library, so it works in a service, a worker, or a CLI. It is Native AOT compatible.

Register with the WellKnown builder

services.AddWellKnown(wellKnown => wellKnown.AddDiscovery(discovery => {
    discovery.Options.Configure(options =>
        options.TrustedAuthorizationServers.Add("https://auth.example.com"));
    discovery.HttpClient.ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(15));
}));

Inject OAuthDiscoveryClient where needed. AddWellKnown() alone does not register it. The standalone services.AddOAuthDiscoveryClient(...) method configures the same named HTTP client and shared document cache. The default primary handler disables automatic redirects and response draining. If replacing it via ConfigurePrimaryHttpMessageHandler, preserve both settings: rejecting an already-followed redirect does not undo the outbound request.

Installation

dotnet add package Wiaoj.WellKnown.Discovery

Usage

Use the builder registration above, then inject OAuthDiscoveryClient and choose how to locate the resource.

From a known resource identifier (between our services)

public sealed class PrismClient(OAuthDiscoveryClient discovery) {
    public async Task<string?> TokenEndpointAsync(CancellationToken ct) {
        OAuthDiscoveryResult found = await discovery.DiscoverAsync("https://prism.example.com/v1", ct);

        // found.ProtectedResource.Resource        "https://prism.example.com/v1" — the token's audience (RFC 8707 resource)
        // found.ProtectedResource.ScopesSupported
        // found.AuthorizationServer.DeviceAuthorizationEndpoint — RFC 8628, for a CLI
        return found.AuthorizationServer.TokenEndpoint;   // obtain a token with your OAuth client
    }
}

From a 401 (a client that doesn't know the API)

For URLs received from users, configure and enforce an outbound policy on the HTTP client that obtains the 401. The separate discovery client's settings do not protect this initial resource request.

using HttpResponseMessage response = await http.GetAsync(userSuppliedUrl, ct);

if(response.StatusCode == HttpStatusCode.Unauthorized
   && await discovery.DiscoverAsync(response, ct) is { } found) {
    // resource == userSuppliedUrl (RFC 9728 §3.3)
}

GetProtectedResourceMetadataAsync and GetAuthorizationServerMetadataAsync fetch one document each. Parameters without a property of their own are available in Json.

The client stops before getting a token. How the token is obtained (client credentials, device flow, token exchange) belongs to your OAuth client.

What is checked

Each failure throws OAuthDiscoveryException, and its Failure says why.

Check Failure Source
resource is identical to the identifier looked up, code point for code point IdentifierMismatch RFC 9728 §3.3, §6
issuer is identical to the issuer looked up IdentifierMismatch RFC 8414 §3.3, §6.2
From a 401, resource is identical to the challenged URL (see below) IdentifierMismatch RFC 9728 §3.3
Documents are fetched over https (http only on loopback, for development) InsecureTransport RFC 9728 §7.1, RFC 8414 §3
The client refuses a cross-origin redirect and rejects a response returned from another origin by a custom handler CrossOriginRedirect
At most MaxRedirects same-origin redirects TooManyRedirects
200, application/json, a JSON object, known parameters of the right type, at most MaxDocumentBytes HttpError, InvalidDocument, DocumentTooLarge RFC 9728 §3.2, RFC 8414 §3.2
The resource lists an authorization server, and a trusted one when TrustedAuthorizationServers is set NoAuthorizationServer, UntrustedAuthorizationServer RFC 9728 §7.6, §7.7
The parameter occurs at most once per challenge; usable challenges do not advertise different metadata URLs AmbiguousChallenge Identical URLs across distinct challenges are accepted.
The challenge list uses valid RFC 9110 HTTP syntax MalformedChallenge Quote absolute URLs: an unquoted https://… value is no longer accepted. No candidate is used from a malformed list.

The checks run on every call, whether the document comes from the network or from the cache.

A 401 or the identifier?

RFC 9728 §3.3 says that metadata found through a 401 is used only if its resource is identical to the URL that was requested. There are two ways to discover an API:

Situation Call
The client doesn't know the API, and the user gives it a URL (for example an MCP server's single endpoint) DiscoverAsync(unauthorizedResponse)
The client knows the API's identifier, for example from config (Verba → https://prism.example.com/v1) DiscoverAsync("https://prism.example.com/v1")

In the first case, a 401 from …/v1/keys can't use metadata for …/v1, because the RFC forbids it. When the identifier is known, the second call is used. It fetches the document from the URL derived from the identifier and requires resource to be identical to that identifier, so a 401 isn't needed.

Choosing the authorization server

If TrustedAuthorizationServers is empty, the first entry in authorization_servers is used.

If it is set, the first listed server that is also trusted is used. A resource that lists none of them is refused before anything is fetched from those servers.

RFC 9728 §7.7 warns that fetching whatever a resource names enables server-side request forgery. Between services that know each other, the trusted list is the control. The client does not block private IP addresses itself.

For direct connections, applications can restrict discovery traffic with the optional Wiaoj.Net package. It is an application dependency, not a dependency of this discovery package. For known partners, configure both the exact trusted issuer identifier and the DNS names allowed to serve the metadata:

using Wiaoj.Net;

builder.Services.AddOAuthDiscoveryClient(options =>
        options.TrustedAuthorizationServers.Add("https://login.partner.example"))
    .AddOutboundNetworkPolicy(OutboundNetworkPolicy.WebOnly with {
        AllowedHosts = new HashSet<string> { "api.partner.example", "login.partner.example" }
    });

For discovery from arbitrary public HTTPS APIs, use the same policy without the host list. WebOnly permits public addresses on ports 80 and 443; discovery itself requires HTTPS. A permitted DNS name is still subject to the address and port checks. Keep the discovery client's default primary handler so it can enforce its same-origin redirect rules. This policy applies to metadata fetches only: configure any separate token, resource or JWKS HTTP clients independently.

For local development use a test-only HTTPS endpoint and a separate, narrow policy for its address and port; do not disable production protection to reach a development endpoint. For proxy deployments see Wiaoj.Net's proxy guidance rather than assuming the direct connection policy checks the destination behind a proxy.

Discover an OpenID Provider explicitly

If the application already knows the issuer of an OpenID Connect provider, call GetOpenIdProviderConfigurationAsync. This is a distinct choice from the RFC 9728 → RFC 8414 DiscoverAsync flow. Neither method silently falls back to the other.

builder.Services.AddOAuthDiscoveryClient(options =>
    options.TrustedAuthorizationServers.Add("https://id.example.com/team"));

// An injected OAuthDiscoveryClient:
OpenIdProviderConfigurationDocument provider =
    await client.GetOpenIdProviderConfigurationAsync("https://id.example.com/team", ct);
Console.WriteLine(provider.AuthorizationEndpoint);

For this issuer, the OIDC request goes to /team/.well-known/openid-configuration; RFC 8414 uses a different, prefix-style path. The response's issuer must exactly match the requested issuer, and a configured trusted issuer list applies before the request. The client uses the same HTTPS, redirect, JSON/media/size and optional application egress protections shown above. The existing HTTP-on-loopback development option is not for production providers.

The modeled subset validates the issuer, authorization and JWK Set URLs, token endpoint (unless implicit-only), optional UserInfo URL and relevant capability lists. Unknown parameters remain available in Json without further validation. This is metadata discovery only, not full OIDC client conformance: no WebFinger, login, token fetching or validation, or JWK Set fetching.

See OpenID Connect Discovery, sections 3–4 and RFC 8414, section 5.

Optional live-provider smoke tests

Default tests use local fixtures; no external request is made unless explicitly enabled. Set WIAOJ_OIDC_TEST_GOOGLE=1 for Google public discovery metadata. Set WIAOJ_OIDC_TEST_ENTRA_TENANT to the concrete tenant GUID you intend to test for Microsoft Entra v2.0. Then run the WellKnown integration project. These tests fetch only anonymous HTTPS metadata from the official hosts and require exact issuers. The Entra tenant value is not a credential; common and organizations are not accepted by this strict tenant-specific smoke test.

Caching

Documents are cached by URL and document type, according to their response. OpenID configurations are also scoped to the exact requested issuer, and an issuer mismatch is rejected before cache publication:

  • Freshness. A document is cached for max-age minus Age, capped at MaxCacheDuration. It is never served after that.
  • Not cached. Nothing is cached under no-store or no-cache, or when max-age is missing. Failures are not cached either.
  • Size bound. At most MaxCachedDocuments completed documents are kept. This is not an admission limit on distinct URLs being fetched. When the cache is full, expired documents go first, then the ones fetched longest ago.
  • Concurrent requests. Requests for the same document share one refresh; one caller cancelling does not fail the others. By default, a cache starts at most 16 concurrent refreshes (MaxConcurrentRefreshes) and fails new distinct work immediately with RefreshSaturated when already full. Fresh cache hits and existing refresh waiters do not consume additional slots.
  • Whole-refresh deadline. A shared budget of 10 seconds (RefreshTimeout) includes admission to the worker, all redirects, body reading and parsing. On expiry, callers receive RefreshTimedOut and the producer is cancelled; a subsequent request can start once the producer has stopped. No stale document is served beyond existing freshness/challenge rules. The default handler does not drain abandoned response bodies in the background. A custom transport must honor cancellation and must not detach background work; while its refresh task remains active, it keeps its slot even after observers time out, and any late result is discarded. These limits are local to a DI container or a manually constructed client/cache, not a distributed limit.
  • Challenges. A new resource_metadata challenge means the metadata may have changed (§5.2). It re-fetches the document if the cached copy is older than ChallengeRefreshInterval (30 seconds). A burst of 401s therefore causes at most one fetch.

AddOAuthDiscoveryClient shares one cache across every typed client instance. Without dependency injection, keep one OAuthDiscoveryClient instance, because a new instance starts with an empty cache.

Handlers

The registered primary handler has AllowAutoRedirect = false, so a cross-origin redirect is refused before it is followed. If you replace the primary handler with ConfigurePrimaryHttpMessageHandler, the client can reject a response from another origin, but it cannot prevent or undo a request already made by that handler. Keep automatic redirects disabled.

Not supported

  • signed_metadata
  • Automatic fallback between OAuth and OpenID discovery, or serving OpenID Provider configuration documents
Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
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
0.5.1-alpha 0 12/6/2026
0.5.0-alpha.1 0 12/5/2026
0.4.2-alpha.2 54 12/3/2026
0.4.2-alpha.1 52 12/2/2026
0.4.1-alpha.3 62 11/30/2026
0.4.1-alpha.2 59 11/29/2026
0.4.1-alpha.1 65 11/28/2026
0.4.0-alpha.5 65 11/27/2026
0.4.0-alpha.4 63 11/15/2026
0.4.0-alpha.3 61 11/4/2026
0.4.0-alpha.1 67 10/30/2026
0.3.0-alpha.1 977 10/5/2026
0.2.0-alpha.3 67 9/24/2026
0.2.0-alpha.2 63 9/24/2026
0.2.0-alpha.1 69 9/24/2026
0.1.0-alpha.9 68 9/21/2026
0.1.0-alpha.8 64 9/21/2026
0.1.0-alpha.7 66 9/18/2026
0.1.0-alpha.6 61 9/16/2026
0.1.0-alpha.5 65 9/16/2026
Loading failed