Skip to content

feat: add MetadataAddress support to ClientCredentialsClient for OIDC discovery - #358

Merged
Erwinvandervalk merged 7 commits into
DuendeSoftware:mainfrom
paulomorgado:feature/MetadataAddress
Nov 3, 2026
Merged

Erwinvandervalk merged 7 commits into
DuendeSoftware:mainfrom
paulomorgado:feature/MetadataAddress

Conversation

@paulomorgado

@paulomorgado paulomorgado commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds OpenID Connect discovery to client credentials token acquisition. ClientCredentialsClient can now be configured with an Authority instead of a hardcoded TokenEndpoint, and the token endpoint is resolved from the discovery document.

This follows the discovery model already used by OAuth2IntrospectionOptions and OidcClient, so discovery is configured the same way across the libraries.

What changed

Public API

  • ClientCredentialsClient.Authority (string?): the authority to run discovery against. A full discovery URL is also accepted when it ends in DiscoveryPolicy.DiscoveryDocumentPath (by default .well-known/openid-configuration).
  • ClientCredentialsClient.DiscoveryPolicy (DiscoveryPolicy): the policy used to validate the discovery document. Defaults to new(), the same as OAuth2IntrospectionOptions.DiscoveryPolicy.

Validation

A client needs a ClientId and either a TokenEndpoint or an Authority.

Token endpoint resolution

  • When TokenEndpoint is set, it's used directly and no discovery happens.
  • Otherwise the endpoint is resolved with GetDiscoveryDocumentAsync and the configured DiscoveryPolicy. This gives issuer validation, endpoint validation and the HTTPS requirement (with the loopback exception).
  • Discovery runs lazily, once per options instance, through an AsyncLazy created in a post-configurer. Concurrent first requests share one discovery call. The result is kept for the lifetime of the options, and TokenEndpoint is never modified.
  • A failed discovery isn't cached; the next request tries again. A caller cancelling only stops that caller's wait, not the shared discovery.
  • Authority and TokenEndpoint are read after all post-configurers have run, so apps can set or clear them in their own PostConfigure.
  • Discovery uses the same HttpClient as the token request: an explicit HttpClient, then the named client, then the default backchannel.
  • DPoP proofs use the resolved endpoint as htu, including on the nonce retry.

Errors

Discovery failures throw InvalidOperationException. The message depends on ResponseErrorType, as in PostConfigureOAuth2IntrospectionOptions, and the underlying exception is kept as the inner exception. A discovery document without a token_endpoint gets its own message, which names the client.

Tests

ClientCredentialsDiscoveryTests covers resolution, policy enforcement (issuer, HTTPS, key set, additional endpoint hosts), concurrency and cancellation, retry after failure, late configuration through PostConfigure, choice of HttpClient, DPoP, and the error paths. ClientTokenManagementTests covers validation and TokenEndpoint precedence.

Copilot AI review requested due to automatic review settings July 22, 2026 10:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Discovery currently weakens HTTPS enforcement, mishandles custom metadata URLs, unnecessarily depends on JWKS availability, and obscures discovery errors.

4 open findings

🧠 Review effort: Balanced

@paulomorgado
paulomorgado force-pushed the feature/MetadataAddress branch 2 times, most recently from f9fe6ef to b8719d9 Compare October 13, 2026 09:48
@paulomorgado
paulomorgado requested a balanced review from Copilot October 13, 2026 09:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The implementation preserves compatibility and comprehensively validates and tests the discovery flow.

0 open findings

4 resolved since last review

🧠 Review effort: Balanced

@bhazen

bhazen commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Hi @paulomorgado, thanks for this PR. Discovery support for client credentials is something we'd like to have, and we've spent some time as a team looking at how it should fit into the library.

We'd like to take it in a slightly different direction, mainly so it matches how discovery already works elsewhere in this repo. The introspection handler (OAuth2IntrospectionOptions) and OidcClient both take an Authority, expose a DiscoveryPolicy, and resolve endpoints with GetDiscoveryDocumentAsync. We'd like ClientCredentialsClient to follow the same model so users only have one way of configuring discovery to learn across our libraries.

Concretely, that means:

  1. Authority instead of MetadataAddress. We know OpenIdConnectOptions and JwtBearerOptions have both, but none of our libraries have a MetadataAddress setting, and we'd rather stay consistent with them. Authority already accepts a full discovery URL when it ends in .well-known/openid-configuration (or the policy's DiscoveryDocumentPath), since DiscoveryEndpoint.ParseUrl treats it as the complete address.
  2. A DiscoveryPolicy property, defaulting to new(), the same as OAuth2IntrospectionOptions.DiscoveryPolicy.
  3. Use GetDiscoveryDocumentAsync with that policy rather than fetching and validating the document by hand. That gives us issuer validation, endpoint validation and the HTTPS requirement (with the loopback exception) from the existing policy, and lets users adjust them the same way they do elsewhere. The current code doesn't validate issuer, which is the main gap we'd want closed.
  4. TokenEndpoint still takes precedence, and validation requires either TokenEndpoint or Authority. Your existing validation change already does this, so it should mostly be a rename.
  5. Resolve the endpoint once per client, not on each request. At the moment ClientCredentialsTokenClient writes the discovered endpoint into the shared options object during the request, so concurrent first requests can each fetch the document and overwrite the value while another request is using it. The introspection handler avoids this by resolving lazily, once, through an AsyncLazy set up in PostConfigure. We'd like the same approach here, with the endpoint kept for the lifetime of the options, as introspection and OidcClient do.
  6. Discovery failures throw InvalidOperationException, mapped by ResponseErrorType the same way PostConfigureOAuth2IntrospectionOptions does, so the messages are consistent.

Your tests are a good base. Most of the scenarios (precedence, missing token endpoint, failed request, endpoint reuse) still apply, and we'd add a couple for concurrent first requests and issuer validation.

Would you like to rework the PR along these lines? If you'd rather not, no problem at all. Just let us know and we'll pick it up from here and credit you in our PR.

@paulomorgado
paulomorgado marked this pull request as draft October 15, 2026 19:36
@paulomorgado

Copy link
Copy Markdown
Contributor Author

Hi @bhazen,

Let me look into this, but I think I can handle it,

@paulomorgado

Copy link
Copy Markdown
Contributor Author

Hi @bhazen,

Check out the latest commit.

@paulomorgado
paulomorgado marked this pull request as ready for review October 19, 2026 17:43

@bhazen bhazen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @paulomorgado for making the changes based on the direction we discussed

A few things about this round of changes:

  1. CI failure. ConventionTests.All_async_methods_should_end_with_Async_and_have_cancellation_token_as_last_parameter fails on AsyncLazy<T>.Value. Details inline.

  2. Discovery isn't set up if Authority is configured late. Details inline on PostConfigureClientCredentialsClient.

  3. Test organization. The discovery tests added to ClientTokenManagementTests.cs would sit better in ClientCredentialsDiscoveryTests.cs, where the existing helpers would cut most of their setup. Could you move them over, apart from Missing_tokenEndpoint_and_authority_throw_exception and TokenEndpoint_should_take_precedence_over_authority, which fit where they are?

  4. One missing test. Nothing covers DPoP with Authority. A test that the proof's htu is the discovered token endpoint (including the nonce retry, if it's easy to include) would close that gap. The code already does the right thing, so this is just about locking it in.

  5. Merge conflict with main. There's a conflict in ServiceCollectionExtensions.cs since main added a validator registration on the same line. Keeping both lines resolves it:

    services.TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<ClientCredentialsTokenManagementOptions>, ClientCredentialsTokenManagementOptions.Validator>());
    services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<ClientCredentialsClient>, PostConfigureClientCredentialsClient>());

There are also a couple of small nits inline. Thanks again for turning this around so quickly.

Added MetadataAddress to ClientCredentialsClient for OIDC discovery. Validation now requires TokenEndpoint or MetadataAddress. ClientCredentialsTokenClient resolves token endpoint from metadata if needed, with improved error handling. Tests updated for new scenarios and API changes.
Require an explicit metadata document URI, fetch metadata JSON directly, validate only the discovered token endpoint, enforce HTTPS except for localhost/127.0.0.1 loopback HTTP, reject malformed or cross-authority endpoints, skip JWKS/signing-key retrieval, and expand tests for explicit URLs, ignored fields, malformed JSON, loopback exceptions, and endpoint validation.
Replace MetadataAddress with Authority and expose DiscoveryPolicy.
Use GetDiscoveryDocumentAsync for standard discovery and validation.

Initialize shared, retryable discovery lazily during post-configuration,
retaining the resolved endpoint for the options lifetime without mutating
TokenEndpoint. Isolate caller cancellation from shared discovery.

Preserve explicit TokenEndpoint precedence and configured backchannels.
Map discovery failures to InvalidOperationException consistently with
introspection, preserving underlying exceptions.
Create lazy discovery whenever TokenEndpoint is absent and defer Authority
validation until discovery runs, allowing later PostConfigure callbacks.

Use configured client names in discovery errors and move shared HTTP
client selection onto ClientCredentialsClient.

Consolidate discovery tests and cover late configuration, explicit
endpoint precedence, and DPoP endpoint binding including nonce retry.
Exempt AsyncLazy from async conventions while preserving its Value API.
@paulomorgado
paulomorgado force-pushed the feature/MetadataAddress branch from ae20782 to 176ab0d Compare October 21, 2026 08:06

@paulomorgado paulomorgado left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed these points, including the inline comments. I moved the discovery tests into ClientCredentialsDiscoveryTests and reused its setup helpers, leaving Missing_tokenEndpoint_and_authority_throw_exception and TokenEndpoint_should_take_precedence_over_authority in ClientTokenManagementTests.

Added coverage using real DPoP proofs to check that htu is the discovered token endpoint on both the initial request and the nonce retry, including checking the retry’s nonce.

Rebased onto main and resolved the registration conflict by keeping both the management-options validator and the discovery post-configurer. All 125 targeted tests pass locally, including the convention test.

@paulomorgado

Copy link
Copy Markdown
Contributor Author

Hi @bhazen, is anything missing from my part?

Copilot AI balanced review requested due to automatic review settings November 2, 2026 07:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The advertised MetadataAddress API is missing, and post-configuration ordering can leave endpoint discovery uninitialized, causing token acquisition to fail.

2 open issues

Review effort: Balanced

Erwinvandervalk
Erwinvandervalk previously approved these changes Nov 3, 2026
Copilot AI balanced review requested due to automatic review settings November 3, 2026 07:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Valid post-configuration can leave discovery uninitialized and cause token acquisition to fail, while the Authority API does not provide the advertised exact metadata-URL behavior.

3 open issues

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 3, 2026 07:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the authority-based OpenID Connect discovery changes.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

@Erwinvandervalk
Erwinvandervalk merged commit 2cace75 into DuendeSoftware:main Nov 3, 2026
@Erwinvandervalk

Copy link
Copy Markdown
Contributor

@paulomorgado Thank you for providing this PR. We currently have this scheduled to be released in ATM 4.4, which will hopefully land soon after the .Net 11 release.

@paulomorgado
paulomorgado deleted the feature/MetadataAddress branch November 3, 2026 15:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants