diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index dcf8ecf1..5ca99e53 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -2065,6 +2065,37 @@ To apply registration responses, create a class implementing 'IOpenIddictServerH
The registration operation cannot be processed because the client application couldn't be resolved.
+
+ The client registration used to communicate with the authorization server couldn't be resolved.
+To resolve it, specify the registration identifier, the provider name or the issuer of the client registration.
+
+
+ The authorization server doesn't expose a dynamic client registration endpoint.
+
+
+ An error occurred while preparing the registration request.
+Error: {0}
+Error description: {1}
+Error URI: {2}
+
+
+ An error occurred while sending the registration request.
+Error: {0}
+Error description: {1}
+Error URI: {2}
+
+
+ An error occurred while extracting the registration response.
+Error: {0}
+Error description: {1}
+Error URI: {2}
+
+
+ An error occurred while handling the registration response.
+Error: {0}
+Error description: {1}
+Error URI: {2}
+
The security token is missing.
@@ -2962,7 +2993,7 @@ To apply registration responses, create a class implementing 'IOpenIddictServerH
The client application is not allowed to manage its registration.
- The specified client secret doesn't match the client secret of the client application.
+ An error occurred while processing the dynamic client registration request.
The client metadata was rejected by the application manager.
@@ -4044,6 +4075,15 @@ This may indicate that the hashed entry is corrupted or malformed.
The response was successfully returned as an empty 204 response.
+
+ The registration request was successfully sent to {Uri}: {Request}.
+
+
+ The registration response returned by {Uri} was successfully extracted: {Response}.
+
+
+ The registration request was rejected by the remote authorization server: {Response}.
+
https://documentation.openiddict.com/errors/{0}
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Registration.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Registration.cs
new file mode 100644
index 00000000..0e024938
--- /dev/null
+++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Registration.cs
@@ -0,0 +1,160 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+using System.Collections.Immutable;
+using System.Diagnostics;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpConstants;
+
+namespace OpenIddict.Client.SystemNetHttp;
+
+public static partial class OpenIddictClientSystemNetHttpHandlers
+{
+ public static class Registration
+ {
+ public static ImmutableArray DefaultHandlers { get; } =
+ [
+ /*
+ * Registration request processing:
+ */
+ CreateHttpClient.Descriptor,
+ PrepareRegistrationHttpRequest.Descriptor,
+ AttachHttpVersion.Descriptor,
+ AttachJsonAcceptHeaders.Descriptor,
+ AttachUserAgentHeader.Descriptor,
+ AttachFromHeader.Descriptor,
+ AttachBearerAccessToken.Descriptor,
+ AttachJsonHttpParameters.Descriptor,
+ SendHttpRequest.Descriptor,
+ DisposeHttpRequest.Descriptor,
+
+ /*
+ * Registration response processing:
+ */
+ DecompressResponseContent.Descriptor,
+ ExtractJsonHttpResponse.Descriptor,
+ ExtractWwwAuthenticateHeader.Descriptor,
+ ExtractEmptyHttpResponse.Descriptor,
+ ValidateHttpResponse.Descriptor,
+ DisposeHttpResponse.Descriptor
+ ];
+
+ ///
+ /// Contains the logic responsible for preparing an HTTP request message using the method attached to the context.
+ ///
+ public sealed class PrepareRegistrationHttpRequest : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(PreparePostHttpRequest.Descriptor.Order)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(PrepareRegistrationRequestContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // Store the HttpRequestMessage in the transaction properties.
+ context.Transaction.SetProperty(typeof(HttpRequestMessage).FullName!,
+ new HttpRequestMessage(new HttpMethod(context.RequestMethod), context.RemoteUri));
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for attaching the initial access token or
+ /// the registration access token to the standard HTTP Authorization header.
+ ///
+ public sealed class AttachBearerAccessToken : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachJsonHttpParameters.Descriptor.Order - 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(PrepareRegistrationRequestContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
+ // this may indicate that the request was incorrectly processed by another client stack.
+ var request = context.Transaction.GetHttpRequestMessage()
+ ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
+
+ // Note: don't overwrite the authorization header if one was already set by another handler.
+ if (request.Headers.Authorization is null && !string.IsNullOrEmpty(context.AccessToken))
+ {
+ request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.AccessToken);
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for attaching the client metadata to the JSON payload
+ /// of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2).
+ ///
+ public sealed class AttachJsonHttpParameters : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachHttpParameters.Descriptor.Order)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(PrepareRegistrationRequestContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
+
+ // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
+ // this may indicate that the request was incorrectly processed by another client stack.
+ var request = context.Transaction.GetHttpRequestMessage()
+ ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
+
+ if (request.Method != HttpMethod.Post && request.Method != HttpMethod.Put)
+ {
+ return ValueTask.CompletedTask;
+ }
+
+ using var stream = new MemoryStream();
+ using (var writer = new Utf8JsonWriter(stream))
+ {
+ context.Transaction.Request.WriteTo(writer);
+ }
+
+ request.Content = new ByteArrayContent(stream.ToArray());
+ request.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypes.Json) { CharSet = "utf-8" };
+
+ return ValueTask.CompletedTask;
+ }
+ }
+ }
+}
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
index b34e21b1..a92d4bd5 100644
--- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
+++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
@@ -30,6 +30,7 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
+ .. Registration.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. UserInfo.DefaultHandlers
];
diff --git a/src/OpenIddict.Client/OpenIddictClientEvents.Registration.cs b/src/OpenIddict.Client/OpenIddictClientEvents.Registration.cs
new file mode 100644
index 00000000..a0b77957
--- /dev/null
+++ b/src/OpenIddict.Client/OpenIddictClientEvents.Registration.cs
@@ -0,0 +1,122 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+namespace OpenIddict.Client;
+
+public static partial class OpenIddictClientEvents
+{
+ ///
+ /// Represents an abstract base class used by the dynamic client registration events (RFC 7591 and RFC 7592).
+ ///
+ public abstract class BaseRegistrationContext : BaseExternalContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ protected BaseRegistrationContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the request.
+ ///
+ public OpenIddictRequest Request
+ {
+ get => Transaction.Request!;
+ set => Transaction.Request = value;
+ }
+
+ ///
+ /// Gets or sets the HTTP method used to send the request: POST for registration requests (RFC 7591)
+ /// and GET, PUT or DELETE for read, update and delete requests (RFC 7592).
+ ///
+ public string RequestMethod { get; set; } = "POST";
+
+ ///
+ /// Gets or sets the bearer token attached to the request (i.e the initial access
+ /// token for registration requests or the registration access token), if applicable.
+ ///
+ public string? AccessToken { get; set; }
+ }
+
+ ///
+ /// Represents an event called for each request to the registration endpoint
+ /// to give the user code a chance to add metadata to the registration request.
+ ///
+ public sealed class PrepareRegistrationRequestContext : BaseRegistrationContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public PrepareRegistrationRequestContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+ }
+
+ ///
+ /// Represents an event called for each request to the registration endpoint
+ /// to send the registration request to the remote authorization server.
+ ///
+ public sealed class ApplyRegistrationRequestContext : BaseRegistrationContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public ApplyRegistrationRequestContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+ }
+
+ ///
+ /// Represents an event called for each registration response
+ /// to extract the response parameters from the server response.
+ ///
+ public sealed class ExtractRegistrationResponseContext : BaseRegistrationContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public ExtractRegistrationResponseContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the response, or if it wasn't extracted yet.
+ ///
+ public OpenIddictResponse? Response
+ {
+ get => Transaction.Response;
+ set => Transaction.Response = value;
+ }
+ }
+
+ ///
+ /// Represents an event called for each registration response.
+ ///
+ public sealed class HandleRegistrationResponseContext : BaseRegistrationContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public HandleRegistrationResponseContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the response.
+ ///
+ public OpenIddictResponse Response
+ {
+ get => Transaction.Response!;
+ set => Transaction.Response = value;
+ }
+ }
+}
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
index 4a2a3a64..2f997ea6 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
@@ -36,6 +36,7 @@ public static partial class OpenIddictClientHandlers
ExtractMtlsTokenEndpoint.Descriptor,
ExtractMtlsUserInfoEndpoint.Descriptor,
ExtractPushedAuthorizationEndpoint.Descriptor,
+ ExtractRegistrationEndpoint.Descriptor,
ExtractRevocationEndpoint.Descriptor,
ExtractTokenEndpoint.Descriptor,
ExtractUserInfoEndpoint.Descriptor,
@@ -119,6 +120,7 @@ public static partial class OpenIddictClientHandlers
Metadata.Issuer or
Metadata.JwksUri or
Metadata.PushedAuthorizationRequestEndpoint or
+ Metadata.RegistrationEndpoint or
Metadata.TokenEndpoint or
Metadata.UserInfoEndpoint
=> ((JsonElement) value).ValueKind is JsonValueKind.String,
@@ -767,6 +769,47 @@ public static partial class OpenIddictClientHandlers
}
}
+ ///
+ /// Contains the logic responsible for extracting the dynamic client registration endpoint URI from the discovery document.
+ ///
+ public sealed class ExtractRegistrationEndpoint : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ExtractPushedAuthorizationEndpoint.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleConfigurationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // See https://datatracker.ietf.org/doc/html/rfc8414#section-2 for more information.
+ var endpoint = (string?) context.Response[Metadata.RegistrationEndpoint];
+ if (!string.IsNullOrEmpty(endpoint))
+ {
+ if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) || OpenIddictHelpers.IsImplicitFileUri(uri))
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2100(Metadata.RegistrationEndpoint),
+ uri: SR.FormatID8000(SR.ID2100));
+
+ return ValueTask.CompletedTask;
+ }
+
+ context.Configuration.RegistrationEndpoint = uri;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
///
/// Contains the logic responsible for extracting the revocation endpoint URI from the discovery document.
///
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Registration.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Registration.cs
new file mode 100644
index 00000000..ba52ea92
--- /dev/null
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Registration.cs
@@ -0,0 +1,129 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+using System.Collections.Immutable;
+using System.Text.Json;
+using Microsoft.Extensions.Logging;
+
+namespace OpenIddict.Client;
+
+public static partial class OpenIddictClientHandlers
+{
+ public static class Registration
+ {
+ public static ImmutableArray DefaultHandlers { get; } =
+ [
+ /*
+ * Registration response handling:
+ */
+ ValidateWellKnownParameters.Descriptor,
+ HandleErrorResponse.Descriptor
+ ];
+
+ ///
+ /// Contains the logic responsible for validating the well-known parameters contained in the registration response.
+ ///
+ public sealed class ValidateWellKnownParameters : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(int.MinValue + 100_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleRegistrationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ foreach (var parameter in context.Response.GetParameters())
+ {
+ if (!ValidateParameterType(parameter.Key, parameter.Value))
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2107(parameter.Key),
+ uri: SR.FormatID8000(SR.ID2107));
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ return ValueTask.CompletedTask;
+
+ // See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1 for more information.
+ static bool ValidateParameterType(string name, OpenIddictParameter value) => name switch
+ {
+ // The following parameters MUST be formatted as unique strings:
+ Parameters.Error or Parameters.ErrorDescription or Parameters.ErrorUri or
+ ClientMetadata.ClientId or ClientMetadata.ClientSecret or
+ ClientMetadata.RegistrationAccessToken or ClientMetadata.RegistrationClientUri
+ => ((JsonElement) value).ValueKind is JsonValueKind.String,
+
+ // The following parameters MUST be formatted as numeric dates:
+ ClientMetadata.ClientIdIssuedAt or ClientMetadata.ClientSecretExpiresAt
+ => ((JsonElement) value).ValueKind is JsonValueKind.Number,
+
+ // Other metadata can be of any type.
+ _ => true
+ };
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for surfacing potential errors from the registration response.
+ ///
+ public sealed class HandleErrorResponse : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ValidateWellKnownParameters.Descriptor.Order + 1_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleRegistrationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ if (!string.IsNullOrEmpty(context.Response.Error))
+ {
+ context.Logger.LogInformation(6612, SR.GetResourceString(SR.ID6612), context.Response);
+
+ // Note: the standard registration errors are preserved to allow the caller to determine
+ // why the registration was rejected (e.g because a redirect URI was not accepted).
+ //
+ // See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2 for more information.
+ context.Reject(
+ error: context.Response.Error switch
+ {
+ Errors.InvalidClientMetadata or Errors.InvalidRedirectUri or
+ Errors.InvalidSoftwareStatement or Errors.UnapprovedSoftwareStatement or
+ Errors.InvalidToken or Errors.InsufficientScope or
+ Errors.InsufficientAccess or Errors.InvalidRequest
+ => context.Response.Error,
+
+ _ => Errors.ServerError
+ },
+ description: SR.GetResourceString(SR.ID2415),
+ uri: SR.FormatID8000(SR.ID2415));
+
+ return ValueTask.CompletedTask;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+ }
+}
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
index 0da21590..ccaa2ba5 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
@@ -244,6 +244,7 @@ public static partial class OpenIddictClientHandlers
.. Introspection.DefaultHandlers,
.. Logout.DefaultHandlers,
.. Protection.DefaultHandlers,
+ .. Registration.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. Session.DefaultHandlers,
.. UserInfo.DefaultHandlers
diff --git a/src/OpenIddict.Client/OpenIddictClientModels.cs b/src/OpenIddict.Client/OpenIddictClientModels.cs
index 2fa45fab..14ae12f1 100644
--- a/src/OpenIddict.Client/OpenIddictClientModels.cs
+++ b/src/OpenIddict.Client/OpenIddictClientModels.cs
@@ -1742,4 +1742,167 @@ public static partial class OpenIddictClientModels
///
public required OpenIddictResponse RevocationResponse { get; init; }
}
-}
+
+ ///
+ /// Represents a dynamic client registration request (RFC 7591).
+ ///
+ public sealed record class ClientRegistrationRequest
+ {
+ ///
+ /// Gets or sets the cancellation token that will be
+ /// used to determine if the operation was aborted.
+ ///
+ public CancellationToken CancellationToken { get; init; }
+
+ ///
+ /// Gets or sets the initial access token attached to the registration request, if applicable.
+ ///
+ public string? InitialAccessToken { get; init; }
+
+ ///
+ /// Gets or sets the issuer used to resolve the client registration.
+ ///
+ ///
+ /// Note: if multiple client registrations point to the same issuer,
+ /// the property must be explicitly set.
+ ///
+ public Uri? Issuer { get; init; }
+
+ ///
+ /// Gets or sets the client metadata sent to the authorization server (e.g "redirect_uris" or "grant_types").
+ ///
+ public Dictionary? Metadata { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that will be added to the context.
+ ///
+ public Dictionary? Properties { get; init; }
+
+ ///
+ /// Gets or sets the provider name used to resolve the client registration.
+ ///
+ ///
+ /// Note: if multiple client registrations use the same provider name.
+ /// the property must be explicitly set.
+ ///
+ public string? ProviderName { get; init; }
+
+ ///
+ /// Gets or sets the URI of the registration endpoint. If this property is not set, the
+ /// URI is resolved from the "registration_endpoint" node of the server configuration.
+ ///
+ public Uri? RegistrationEndpoint { get; init; }
+
+ ///
+ /// Gets or sets the unique identifier of the client registration that will be used.
+ ///
+ public string? RegistrationId { get; init; }
+ }
+
+ ///
+ /// Represents a request sent to the client configuration endpoint to read,
+ /// update or delete the registration of a client application (RFC 7592).
+ ///
+ public sealed record class ClientConfigurationRequest
+ {
+ ///
+ /// Gets or sets the cancellation token that will be
+ /// used to determine if the operation was aborted.
+ ///
+ public CancellationToken CancellationToken { get; init; }
+
+ ///
+ /// Gets or sets the client identifier. If this property is not set, the client
+ /// identifier is resolved from the query string of .
+ ///
+ public string? ClientId { get; init; }
+
+ ///
+ /// Gets or sets the issuer used to resolve the client registration.
+ ///
+ public Uri? Issuer { get; init; }
+
+ ///
+ /// Gets or sets the client metadata sent to the authorization server when updating a client registration.
+ ///
+ ///
+ /// Note: update requests use full replace semantics: metadata that are not included are removed or reset.
+ ///
+ public Dictionary? Metadata { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that will be added to the context.
+ ///
+ public Dictionary? Properties { get; init; }
+
+ ///
+ /// Gets or sets the provider name used to resolve the client registration.
+ ///
+ public string? ProviderName { get; init; }
+
+ ///
+ /// Gets or sets the registration access token returned by the authorization server.
+ ///
+ public required string RegistrationAccessToken { get; init; }
+
+ ///
+ /// Gets or sets the client configuration endpoint URI returned by the authorization server.
+ ///
+ public required Uri RegistrationClientUri { get; init; }
+
+ ///
+ /// Gets or sets the unique identifier of the client registration that will be used.
+ ///
+ public string? RegistrationId { get; init; }
+ }
+
+ ///
+ /// Represents a dynamic client registration result (RFC 7591 and RFC 7592).
+ ///
+ public sealed record class ClientRegistrationResult
+ {
+ ///
+ /// Gets the client identifier issued by the authorization server, if available.
+ ///
+ public string? ClientId => (string?) RegistrationResponse[ClientMetadata.ClientId];
+
+ ///
+ /// Gets the date at which the client identifier was issued, if available.
+ ///
+ public DateTimeOffset? ClientIdIssuedAt => (long?) RegistrationResponse[ClientMetadata.ClientIdIssuedAt]
+ is long value ? DateTimeOffset.FromUnixTimeSeconds(value) : null;
+
+ ///
+ /// Gets the client secret issued by the authorization server, if available.
+ ///
+ public string? ClientSecret => (string?) RegistrationResponse[ClientMetadata.ClientSecret];
+
+ ///
+ /// Gets the date at which the client secret will expire, or
+ /// if no expiration date was returned or if the client secret never expires.
+ ///
+ public DateTimeOffset? ClientSecretExpiresAt => (long?) RegistrationResponse[ClientMetadata.ClientSecretExpiresAt]
+ is long value and > 0 ? DateTimeOffset.FromUnixTimeSeconds(value) : null;
+
+ ///
+ /// Gets or sets the application-specific properties that were present in the context.
+ ///
+ public required Dictionary Properties { get; init; }
+
+ ///
+ /// Gets the registration access token returned by the authorization server, if available.
+ ///
+ public string? RegistrationAccessToken => (string?) RegistrationResponse[ClientMetadata.RegistrationAccessToken];
+
+ ///
+ /// Gets the client configuration endpoint URI returned by the authorization server, if available.
+ ///
+ public Uri? RegistrationClientUri => Uri.TryCreate((string?) RegistrationResponse[ClientMetadata.RegistrationClientUri],
+ UriKind.Absolute, out Uri? uri) ? uri : null;
+
+ ///
+ /// Gets or sets the registration response (that is empty for delete operations).
+ ///
+ public required OpenIddictResponse RegistrationResponse { get; init; }
+ }
+}
\ No newline at end of file
diff --git a/src/OpenIddict.Client/OpenIddictClientService.cs b/src/OpenIddict.Client/OpenIddictClientService.cs
index 4fcf8dc3..3dc72083 100644
--- a/src/OpenIddict.Client/OpenIddictClientService.cs
+++ b/src/OpenIddict.Client/OpenIddictClientService.cs
@@ -1591,6 +1591,282 @@ public partial class OpenIddictClientService
};
}
+ ///
+ /// Registers a client application using OAuth 2.0 Dynamic Client Registration (RFC 7591).
+ ///
+ /// The registration request.
+ /// The registration result, that contains the client information response.
+ /// The registration request was rejected by the authorization server.
+ public virtual async ValueTask RegisterAsync(ClientRegistrationRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ request.CancellationToken.ThrowIfCancellationRequested();
+
+ var registration = await ResolveClientRegistrationAsync(
+ request.RegistrationId, request.ProviderName, request.Issuer, request.CancellationToken);
+
+ var configuration = new OpenIddictConfiguration();
+ var uri = request.RegistrationEndpoint;
+
+ if (uri is null)
+ {
+ if (registration.ConfigurationManager is null)
+ {
+ throw new InvalidOperationException(SR.GetResourceString(SR.ID0422));
+ }
+
+ configuration = await registration.ConfigurationManager
+ .GetConfigurationAsync(request.CancellationToken)
+ .WaitAsync(request.CancellationToken)
+ ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
+
+ uri = configuration.RegistrationEndpoint ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0809));
+ }
+
+ var response = await SendRegistrationRequestAsync(registration, configuration,
+ new OpenIddictRequest(request.Metadata ?? []), uri, "POST",
+ request.InitialAccessToken, request.CancellationToken);
+
+ return new()
+ {
+ Properties = request.Properties is not null ? new(request.Properties, StringComparer.Ordinal) : new(StringComparer.Ordinal),
+ RegistrationResponse = response
+ };
+ }
+
+ ///
+ /// Retrieves the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
+ ///
+ /// The client configuration request.
+ /// The registration result, that contains the client information response.
+ ///
+ /// Note: the authorization server may issue a new registration access token that must be used for subsequent operations.
+ ///
+ /// The request was rejected by the authorization server.
+ public virtual ValueTask GetRegistrationAsync(ClientConfigurationRequest request)
+ => SendClientConfigurationRequestAsync(request, "GET");
+
+ ///
+ /// Updates the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
+ ///
+ /// The client configuration request, that contains the updated client metadata.
+ /// The registration result, that contains the client information response.
+ ///
+ /// Note: the authorization server may issue a new registration access token that must be used for subsequent operations.
+ ///
+ /// The request was rejected by the authorization server.
+ public virtual ValueTask UpdateRegistrationAsync(ClientConfigurationRequest request)
+ => SendClientConfigurationRequestAsync(request, "PUT");
+
+ ///
+ /// Deletes the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
+ ///
+ /// The client configuration request.
+ /// The registration result, whose response is empty.
+ /// The request was rejected by the authorization server.
+ public virtual ValueTask DeleteRegistrationAsync(ClientConfigurationRequest request)
+ => SendClientConfigurationRequestAsync(request, "DELETE");
+
+ private async ValueTask SendClientConfigurationRequestAsync(ClientConfigurationRequest request, string method)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ if (string.IsNullOrEmpty(request.RegistrationAccessToken))
+ {
+ throw new ArgumentException(SR.FormatID0366(nameof(request.RegistrationAccessToken)), nameof(request));
+ }
+
+ if (request.RegistrationClientUri is not { IsAbsoluteUri: true } || OpenIddictHelpers.IsImplicitFileUri(request.RegistrationClientUri))
+ {
+ throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(request));
+ }
+
+ request.CancellationToken.ThrowIfCancellationRequested();
+
+ var registration = await ResolveClientRegistrationAsync(
+ request.RegistrationId, request.ProviderName, request.Issuer, request.CancellationToken);
+
+ var parameters = new OpenIddictRequest();
+
+ // Update requests MUST include the client metadata and the client identifier in the JSON payload.
+ //
+ // See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information.
+ if (method is "PUT")
+ {
+ parameters = new OpenIddictRequest(request.Metadata ?? []);
+ parameters.ClientId = request.ClientId ?? parameters.ClientId ??
+ (OpenIddictHelpers.ParseQuery(request.RegistrationClientUri.Query).TryGetValue(Parameters.ClientId, out var values)
+ ? (string?) values : null);
+ }
+
+ var response = await SendRegistrationRequestAsync(registration, new OpenIddictConfiguration(), parameters,
+ request.RegistrationClientUri, method, request.RegistrationAccessToken, request.CancellationToken);
+
+ return new()
+ {
+ Properties = request.Properties is not null ? new(request.Properties, StringComparer.Ordinal) : new(StringComparer.Ordinal),
+ RegistrationResponse = response
+ };
+ }
+
+ private async ValueTask ResolveClientRegistrationAsync(
+ string? identifier, string? name, Uri? issuer, CancellationToken cancellationToken)
+ {
+ if (!string.IsNullOrEmpty(identifier))
+ {
+ return await GetClientRegistrationByIdAsync(identifier, cancellationToken);
+ }
+
+ if (!string.IsNullOrEmpty(name))
+ {
+ return await GetClientRegistrationByProviderNameAsync(name, cancellationToken);
+ }
+
+ if (issuer is not null)
+ {
+ return await GetClientRegistrationByIssuerAsync(issuer, cancellationToken);
+ }
+
+ return await GetClientRegistrationsAsync(cancellationToken) is [OpenIddictClientRegistration registration]
+ ? registration
+ : throw new InvalidOperationException(SR.GetResourceString(SR.ID0808));
+ }
+
+ ///
+ /// Sends the registration request and retrieves the corresponding response.
+ ///
+ /// The client registration.
+ /// The server configuration.
+ /// The registration request.
+ /// The uri of the remote registration or client configuration endpoint.
+ /// The HTTP method used to send the request.
+ /// The bearer token attached to the request, if applicable.
+ /// The that can be used to abort the operation.
+ /// The response extracted from the registration response.
+ internal async ValueTask SendRegistrationRequestAsync(
+ OpenIddictClientRegistration registration, OpenIddictConfiguration configuration,
+ OpenIddictRequest request, Uri uri, string method, string? token, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(registration);
+ ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(uri);
+
+ if (!uri.IsAbsoluteUri || OpenIddictHelpers.IsImplicitFileUri(uri))
+ {
+ throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(uri));
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ await using var scope = _provider.CreateAsyncScope();
+
+ var dispatcher = scope.ServiceProvider.GetRequiredService();
+ var options = scope.ServiceProvider.GetRequiredService>();
+
+ var transaction = new OpenIddictClientTransaction
+ {
+ CancellationToken = cancellationToken,
+ Options = options.CurrentValue,
+ ServiceProvider = scope.ServiceProvider
+ };
+
+ request = await PrepareRegistrationRequestAsync();
+ request = await ApplyRegistrationRequestAsync();
+
+ var response = await ExtractRegistrationResponseAsync();
+
+ return await HandleRegistrationResponseAsync();
+
+ void Populate(BaseRegistrationContext context)
+ {
+ context.AccessToken = token;
+ context.Configuration = configuration;
+ context.Registration = registration;
+ context.RemoteUri = uri;
+ context.Request = request;
+ context.RequestMethod = method;
+ }
+
+ async ValueTask PrepareRegistrationRequestAsync()
+ {
+ var context = new PrepareRegistrationRequestContext(transaction);
+ Populate(context);
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0810(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ (token, method) = (context.AccessToken, context.RequestMethod);
+
+ return context.Request;
+ }
+
+ async ValueTask ApplyRegistrationRequestAsync()
+ {
+ var context = new ApplyRegistrationRequestContext(transaction);
+ Populate(context);
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0811(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ context.Logger.LogInformation(6610, SR.GetResourceString(SR.ID6610), context.RemoteUri, context.Request);
+
+ return context.Request;
+ }
+
+ async ValueTask ExtractRegistrationResponseAsync()
+ {
+ var context = new ExtractRegistrationResponseContext(transaction);
+ Populate(context);
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0812(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ Debug.Assert(context.Response is not null, SR.GetResourceString(SR.ID4007));
+
+ context.Logger.LogInformation(6611, SR.GetResourceString(SR.ID6611), context.RemoteUri, context.Response);
+
+ return context.Response;
+ }
+
+ async ValueTask HandleRegistrationResponseAsync()
+ {
+ var context = new HandleRegistrationResponseContext(transaction);
+ Populate(context);
+ context.Response = response;
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0813(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ return context.Response;
+ }
+ }
+
///
/// Retrieves the OpenID Connect server configuration from the specified uri.
///
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs
index 4aca6299..db046c48 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs
+++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs
@@ -725,8 +725,8 @@ public static partial class OpenIddictServerHandlers
{
context.Reject(
error: Errors.InvalidRequest,
- description: SR.GetResourceString(SR.ID2415),
- uri: SR.FormatID8000(SR.ID2415));
+ description: SR.FormatID2403(ClientMetadata.ClientSecret),
+ uri: SR.FormatID8000(SR.ID2403));
return;
}
diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Registration.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Registration.cs
new file mode 100644
index 00000000..66f5ce18
--- /dev/null
+++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Registration.cs
@@ -0,0 +1,349 @@
+using System.Collections.Immutable;
+using System.Net.Http;
+using System.Text.Json;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+using OpenIddict.Client.SystemNetHttp;
+using Xunit;
+using static OpenIddict.Client.OpenIddictClientEvents;
+using static OpenIddict.Client.OpenIddictClientModels;
+
+namespace OpenIddict.Client.Tests;
+
+public class OpenIddictClientHandlersRegistrationTests
+{
+ [Fact]
+ public async Task ExtractRegistrationEndpoint_EndpointIsExtracted()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var options = provider.GetRequiredService>().CurrentValue;
+
+ var context = new HandleConfigurationResponseContext(CreateTransaction(provider))
+ {
+ Response = new OpenIddictResponse(JsonSerializer.Deserialize(
+ """{ "registration_endpoint": "https://www.contoso.com/connect/register" }"""))
+ };
+
+ // Act
+ await new OpenIddictClientHandlers.Discovery.ExtractRegistrationEndpoint().HandleAsync(context);
+
+ // Assert
+ Assert.False(context.IsRejected);
+ Assert.Equal(new Uri("https://www.contoso.com/connect/register"), context.Configuration.RegistrationEndpoint);
+ }
+
+ [Fact]
+ public async Task ExtractRegistrationEndpoint_InvalidEndpointCausesAnError()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+
+ var context = new HandleConfigurationResponseContext(CreateTransaction(provider))
+ {
+ Response = new OpenIddictResponse(JsonSerializer.Deserialize(
+ """{ "registration_endpoint": "/connect/register" }"""))
+ };
+
+ // Act
+ await new OpenIddictClientHandlers.Discovery.ExtractRegistrationEndpoint().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(SR.FormatID2100(Metadata.RegistrationEndpoint), context.ErrorDescription);
+ }
+
+ [Theory]
+ [InlineData("""{ "client_id": 42 }""", ClientMetadata.ClientId)]
+ [InlineData("""{ "client_id": "Fabrikam", "client_id_issued_at": "now" }""", ClientMetadata.ClientIdIssuedAt)]
+ [InlineData("""{ "client_id": "Fabrikam", "registration_access_token": [ "token" ] }""", ClientMetadata.RegistrationAccessToken)]
+ public async Task ValidateWellKnownParameters_InvalidParameterTypeCausesAnError(string payload, string name)
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = new HandleRegistrationResponseContext(CreateTransaction(provider))
+ {
+ Request = new OpenIddictRequest(),
+ Response = new OpenIddictResponse(JsonSerializer.Deserialize(payload))
+ };
+
+ // Act
+ await new OpenIddictClientHandlers.Registration.ValidateWellKnownParameters().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(SR.FormatID2107(name), context.ErrorDescription);
+ }
+
+ [Theory]
+ [InlineData(Errors.InvalidRedirectUri, Errors.InvalidRedirectUri)]
+ [InlineData(Errors.InvalidClientMetadata, Errors.InvalidClientMetadata)]
+ [InlineData(Errors.UnapprovedSoftwareStatement, Errors.UnapprovedSoftwareStatement)]
+ [InlineData(Errors.InvalidToken, Errors.InvalidToken)]
+ [InlineData("custom_error", Errors.ServerError)]
+ public async Task HandleErrorResponse_ErrorsAreMapped(string error, string expected)
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = new HandleRegistrationResponseContext(CreateTransaction(provider))
+ {
+ Request = new OpenIddictRequest(),
+ Response = new OpenIddictResponse { Error = error }
+ };
+
+ // Act
+ await new OpenIddictClientHandlers.Registration.HandleErrorResponse().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(expected, context.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2415), context.ErrorDescription);
+ }
+
+ [Theory]
+ [InlineData("POST", true)]
+ [InlineData("PUT", true)]
+ [InlineData("GET", false)]
+ [InlineData("DELETE", false)]
+ public async Task SystemNetHttpHandlers_RequestIsCorrectlyPrepared(string method, bool payload)
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = new PrepareRegistrationRequestContext(CreateTransaction(provider))
+ {
+ AccessToken = "registration-token",
+ RemoteUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam"),
+ Request = new OpenIddictRequest
+ {
+ ClientId = "Fabrikam",
+ ["redirect_uris"] = new OpenIddictParameter(ImmutableArray.Create("https://www.fabrikam.com/callback"))
+ },
+ RequestMethod = method
+ };
+
+ // Act
+ await new OpenIddictClientSystemNetHttpHandlers.Registration.PrepareRegistrationHttpRequest().HandleAsync(context);
+ await new OpenIddictClientSystemNetHttpHandlers.Registration.AttachBearerAccessToken().HandleAsync(context);
+ await new OpenIddictClientSystemNetHttpHandlers.Registration.AttachJsonHttpParameters().HandleAsync(context);
+
+ // Assert
+ using var request = context.Transaction.GetProperty(typeof(HttpRequestMessage).FullName!)!;
+
+ Assert.Equal(method, request.Method.Method);
+ Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
+ Assert.Equal("registration-token", request.Headers.Authorization?.Parameter);
+
+ if (payload)
+ {
+ Assert.NotNull(request.Content);
+ Assert.Equal("application/json", request.Content.Headers.ContentType?.MediaType);
+
+ using var document = JsonDocument.Parse(await request.Content.ReadAsStringAsync());
+ Assert.Equal("Fabrikam", document.RootElement.GetProperty("client_id").GetString());
+ Assert.Equal("https://www.fabrikam.com/callback",
+ document.RootElement.GetProperty("redirect_uris")[0].GetString());
+ }
+
+ else
+ {
+ Assert.Null(request.Content);
+ }
+ }
+
+ [Fact]
+ public async Task RegisterAsync_RegistrationEndpointIsResolvedFromTheServerConfiguration()
+ {
+ // Arrange
+ BaseRegistrationContext? sent = null;
+
+ using var provider = CreateProvider(options =>
+ {
+ options.AddEventHandler(builder => builder.UseInlineHandler(context =>
+ {
+ sent = context;
+ return ValueTask.CompletedTask;
+ }));
+
+ options.AddEventHandler(builder => builder.UseInlineHandler(context =>
+ {
+ context.Response = new OpenIddictResponse(JsonSerializer.Deserialize("""
+ {
+ "client_id": "Fabrikam",
+ "client_secret": "secret",
+ "client_id_issued_at": 1700000000,
+ "client_secret_expires_at": 0,
+ "registration_access_token": "registration-token",
+ "registration_client_uri": "https://www.contoso.com/connect/register?client_id=Fabrikam"
+ }
+ """));
+
+ return ValueTask.CompletedTask;
+ }));
+ });
+
+ var service = provider.GetRequiredService();
+
+ // Act
+ var result = await service.RegisterAsync(new ClientRegistrationRequest
+ {
+ InitialAccessToken = "initial-token",
+ Metadata = new(StringComparer.Ordinal)
+ {
+ [ClientMetadata.GrantTypes] = new OpenIddictParameter(ImmutableArray.Create(GrantTypes.ClientCredentials))
+ }
+ });
+
+ // Assert
+ Assert.NotNull(sent);
+ Assert.Equal("POST", sent.RequestMethod);
+ Assert.Equal("initial-token", sent.AccessToken);
+ Assert.Equal(new Uri("https://www.contoso.com/connect/register"), sent.RemoteUri);
+ Assert.Equal(GrantTypes.ClientCredentials, ((ImmutableArray?) sent.Request[ClientMetadata.GrantTypes])?[0]);
+
+ Assert.Equal("Fabrikam", result.ClientId);
+ Assert.Equal("secret", result.ClientSecret);
+ Assert.Null(result.ClientSecretExpiresAt);
+ Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1700000000), result.ClientIdIssuedAt);
+ Assert.Equal("registration-token", result.RegistrationAccessToken);
+ Assert.Equal(new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam"), result.RegistrationClientUri);
+ }
+
+ [Fact]
+ public async Task RegisterAsync_ThrowsAnExceptionWhenNoRegistrationEndpointIsAvailable()
+ {
+ // Arrange
+ using var provider = CreateProvider(configuration: new OpenIddictConfiguration
+ {
+ Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute)
+ });
+
+ var service = provider.GetRequiredService();
+
+ // Act and assert
+ var exception = await Assert.ThrowsAsync(async () =>
+ await service.RegisterAsync(new ClientRegistrationRequest()));
+
+ Assert.Equal(SR.GetResourceString(SR.ID0809), exception.Message);
+ }
+
+ [Theory]
+ [InlineData("GET")]
+ [InlineData("PUT")]
+ [InlineData("DELETE")]
+ public async Task ClientConfigurationMethods_RequestsAreSentToTheClientConfigurationEndpoint(string method)
+ {
+ // Arrange
+ BaseRegistrationContext? sent = null;
+
+ using var provider = CreateProvider(options =>
+ {
+ options.AddEventHandler(builder => builder.UseInlineHandler(context =>
+ {
+ sent = context;
+ return ValueTask.CompletedTask;
+ }));
+
+ options.AddEventHandler(builder => builder.UseInlineHandler(context =>
+ {
+ context.Response = new OpenIddictResponse();
+ return ValueTask.CompletedTask;
+ }));
+ });
+
+ var service = provider.GetRequiredService();
+ var request = new ClientConfigurationRequest
+ {
+ Metadata = new(StringComparer.Ordinal)
+ {
+ [ClientMetadata.ClientName] = "Updated"
+ },
+ RegistrationAccessToken = "registration-token",
+ RegistrationClientUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam")
+ };
+
+ // Act
+ var result = method switch
+ {
+ "GET" => await service.GetRegistrationAsync(request),
+ "PUT" => await service.UpdateRegistrationAsync(request),
+ _ => await service.DeleteRegistrationAsync(request)
+ };
+
+ // Assert
+ Assert.NotNull(sent);
+ Assert.Equal(method, sent.RequestMethod);
+ Assert.Equal("registration-token", sent.AccessToken);
+ Assert.Equal(request.RegistrationClientUri, sent.RemoteUri);
+ Assert.NotNull(result.RegistrationResponse);
+
+ if (method is "PUT")
+ {
+ Assert.Equal("Fabrikam", sent.Request.ClientId);
+ Assert.Equal("Updated", (string?) sent.Request[ClientMetadata.ClientName]);
+ }
+
+ else
+ {
+ Assert.Equal(0, sent.Request.Count);
+ }
+ }
+
+ [Fact]
+ public async Task ClientConfigurationMethods_ThrowAnExceptionForMissingRegistrationAccessToken()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var service = provider.GetRequiredService();
+
+ // Act and assert
+ await Assert.ThrowsAsync(async () => await service.GetRegistrationAsync(new ClientConfigurationRequest
+ {
+ RegistrationAccessToken = string.Empty,
+ RegistrationClientUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam")
+ }));
+ }
+
+ private static ServiceProvider CreateProvider(
+ Action? configure = null, OpenIddictConfiguration? configuration = null)
+ {
+ var services = new ServiceCollection();
+
+ services.AddOpenIddict()
+ .AddClient(options =>
+ {
+ options.AllowClientCredentialsFlow();
+
+ options.AddEphemeralEncryptionKey()
+ .AddEphemeralSigningKey();
+
+ options.AddRegistration(new OpenIddictClientRegistration
+ {
+ ClientId = "Fabrikam",
+ Configuration = configuration ?? new OpenIddictConfiguration
+ {
+ Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute),
+ RegistrationEndpoint = new Uri("https://www.contoso.com/connect/register", UriKind.Absolute)
+ },
+ Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute)
+ });
+
+ configure?.Invoke(options);
+ });
+
+ return services.BuildServiceProvider();
+ }
+
+ private static OpenIddictClientTransaction CreateTransaction(IServiceProvider provider)
+ {
+ var options = provider.GetRequiredService>().CurrentValue;
+
+ return new OpenIddictClientTransaction
+ {
+ CancellationToken = CancellationToken.None,
+ Configuration = new OpenIddictConfiguration(),
+ Options = options,
+ Registration = options.Registrations[0],
+ ServiceProvider = provider
+ };
+ }
+}