Browse Source

Add dynamic client registration support to the client stack

- OpenIddictClientService.RegisterAsync (RFC 7591) and GetRegistrationAsync, UpdateRegistrationAsync,
  DeleteRegistrationAsync (RFC 7592), with registration request/response events and error mapping.
- System.Net.Http integration sending JSON payloads with bearer initial/registration access tokens.
- Discovery extraction of the registration_endpoint metadata.
pull/2549/head
pieroviano 2 months ago
parent
commit
aa4d3ff502
  1. 42
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 160
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Registration.cs
  3. 1
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  4. 122
      src/OpenIddict.Client/OpenIddictClientEvents.Registration.cs
  5. 43
      src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
  6. 129
      src/OpenIddict.Client/OpenIddictClientHandlers.Registration.cs
  7. 1
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  8. 165
      src/OpenIddict.Client/OpenIddictClientModels.cs
  9. 276
      src/OpenIddict.Client/OpenIddictClientService.cs
  10. 4
      src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs
  11. 349
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Registration.cs

42
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2065,6 +2065,37 @@ To apply registration responses, create a class implementing 'IOpenIddictServerH
<data name="ID0807" xml:space="preserve">
<value>The registration operation cannot be processed because the client application couldn't be resolved.</value>
</data>
<data name="ID0808" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0809" xml:space="preserve">
<value>The authorization server doesn't expose a dynamic client registration endpoint.</value>
</data>
<data name="ID0810" xml:space="preserve">
<value>An error occurred while preparing the registration request.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0811" xml:space="preserve">
<value>An error occurred while sending the registration request.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0812" xml:space="preserve">
<value>An error occurred while extracting the registration response.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0813" xml:space="preserve">
<value>An error occurred while handling the registration response.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID2000" xml:space="preserve">
<value>The security token is missing.</value>
</data>
@ -2962,7 +2993,7 @@ To apply registration responses, create a class implementing 'IOpenIddictServerH
<value>The client application is not allowed to manage its registration.</value>
</data>
<data name="ID2415" xml:space="preserve">
<value>The specified client secret doesn't match the client secret of the client application.</value>
<value>An error occurred while processing the dynamic client registration request.</value>
</data>
<data name="ID2416" xml:space="preserve">
<value>The client metadata was rejected by the application manager.</value>
@ -4044,6 +4075,15 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6609" xml:space="preserve">
<value>The response was successfully returned as an empty 204 response.</value>
</data>
<data name="ID6610" xml:space="preserve">
<value>The registration request was successfully sent to {Uri}: {Request}.</value>
</data>
<data name="ID6611" xml:space="preserve">
<value>The registration response returned by {Uri} was successfully extracted: {Response}.</value>
</data>
<data name="ID6612" xml:space="preserve">
<value>The registration request was rejected by the remote authorization server: {Response}.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

160
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<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Registration request processing:
*/
CreateHttpClient<PrepareRegistrationRequestContext>.Descriptor,
PrepareRegistrationHttpRequest.Descriptor,
AttachHttpVersion<PrepareRegistrationRequestContext>.Descriptor,
AttachJsonAcceptHeaders<PrepareRegistrationRequestContext>.Descriptor,
AttachUserAgentHeader<PrepareRegistrationRequestContext>.Descriptor,
AttachFromHeader<PrepareRegistrationRequestContext>.Descriptor,
AttachBearerAccessToken.Descriptor,
AttachJsonHttpParameters.Descriptor,
SendHttpRequest<ApplyRegistrationRequestContext>.Descriptor,
DisposeHttpRequest<ApplyRegistrationRequestContext>.Descriptor,
/*
* Registration response processing:
*/
DecompressResponseContent<ExtractRegistrationResponseContext>.Descriptor,
ExtractJsonHttpResponse<ExtractRegistrationResponseContext>.Descriptor,
ExtractWwwAuthenticateHeader<ExtractRegistrationResponseContext>.Descriptor,
ExtractEmptyHttpResponse<ExtractRegistrationResponseContext>.Descriptor,
ValidateHttpResponse<ExtractRegistrationResponseContext>.Descriptor,
DisposeHttpResponse<ExtractRegistrationResponseContext>.Descriptor
];
/// <summary>
/// Contains the logic responsible for preparing an HTTP request message using the method attached to the context.
/// </summary>
public sealed class PrepareRegistrationHttpRequest : IOpenIddictClientHandler<PrepareRegistrationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<PrepareRegistrationHttpRequest>()
.SetOrder(PreparePostHttpRequest<PrepareRegistrationRequestContext>.Descriptor.Order)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for attaching the initial access token or
/// the registration access token to the standard HTTP Authorization header.
/// </summary>
public sealed class AttachBearerAccessToken : IOpenIddictClientHandler<PrepareRegistrationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachBearerAccessToken>()
.SetOrder(AttachJsonHttpParameters.Descriptor.Order - 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// 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).
/// </summary>
public sealed class AttachJsonHttpParameters : IOpenIddictClientHandler<PrepareRegistrationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>()
.AddFilter<RequireHttpUri>()
.UseSingletonHandler<AttachJsonHttpParameters>()
.SetOrder(AttachHttpParameters<PrepareRegistrationRequestContext>.Descriptor.Order)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
}
}

1
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
];

122
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
{
/// <summary>
/// Represents an abstract base class used by the dynamic client registration events (RFC 7591 and RFC 7592).
/// </summary>
public abstract class BaseRegistrationContext : BaseExternalContext
{
/// <summary>
/// Creates a new instance of the <see cref="BaseRegistrationContext"/> class.
/// </summary>
protected BaseRegistrationContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
/// <summary>
/// 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).
/// </summary>
public string RequestMethod { get; set; } = "POST";
/// <summary>
/// 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.
/// </summary>
public string? AccessToken { get; set; }
}
/// <summary>
/// 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.
/// </summary>
public sealed class PrepareRegistrationRequestContext : BaseRegistrationContext
{
/// <summary>
/// Creates a new instance of the <see cref="PrepareRegistrationRequestContext"/> class.
/// </summary>
public PrepareRegistrationRequestContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
}
/// <summary>
/// Represents an event called for each request to the registration endpoint
/// to send the registration request to the remote authorization server.
/// </summary>
public sealed class ApplyRegistrationRequestContext : BaseRegistrationContext
{
/// <summary>
/// Creates a new instance of the <see cref="ApplyRegistrationRequestContext"/> class.
/// </summary>
public ApplyRegistrationRequestContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
}
/// <summary>
/// Represents an event called for each registration response
/// to extract the response parameters from the server response.
/// </summary>
public sealed class ExtractRegistrationResponseContext : BaseRegistrationContext
{
/// <summary>
/// Creates a new instance of the <see cref="ExtractRegistrationResponseContext"/> class.
/// </summary>
public ExtractRegistrationResponseContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the response, or <see langword="null"/> if it wasn't extracted yet.
/// </summary>
public OpenIddictResponse? Response
{
get => Transaction.Response;
set => Transaction.Response = value;
}
}
/// <summary>
/// Represents an event called for each registration response.
/// </summary>
public sealed class HandleRegistrationResponseContext : BaseRegistrationContext
{
/// <summary>
/// Creates a new instance of the <see cref="HandleRegistrationResponseContext"/> class.
/// </summary>
public HandleRegistrationResponseContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the response.
/// </summary>
public OpenIddictResponse Response
{
get => Transaction.Response!;
set => Transaction.Response = value;
}
}
}

43
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
}
}
/// <summary>
/// Contains the logic responsible for extracting the dynamic client registration endpoint URI from the discovery document.
/// </summary>
public sealed class ExtractRegistrationEndpoint : IOpenIddictClientHandler<HandleConfigurationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleConfigurationResponseContext>()
.UseSingletonHandler<ExtractRegistrationEndpoint>()
.SetOrder(ExtractPushedAuthorizationEndpoint.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for extracting the revocation endpoint URI from the discovery document.
/// </summary>

129
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<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Registration response handling:
*/
ValidateWellKnownParameters.Descriptor,
HandleErrorResponse.Descriptor
];
/// <summary>
/// Contains the logic responsible for validating the well-known parameters contained in the registration response.
/// </summary>
public sealed class ValidateWellKnownParameters : IOpenIddictClientHandler<HandleRegistrationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleRegistrationResponseContext>()
.UseSingletonHandler<ValidateWellKnownParameters>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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
};
}
}
/// <summary>
/// Contains the logic responsible for surfacing potential errors from the registration response.
/// </summary>
public sealed class HandleErrorResponse : IOpenIddictClientHandler<HandleRegistrationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleRegistrationResponseContext>()
.UseSingletonHandler<HandleErrorResponse>()
.SetOrder(ValidateWellKnownParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
}
}

1
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

165
src/OpenIddict.Client/OpenIddictClientModels.cs

@ -1742,4 +1742,167 @@ public static partial class OpenIddictClientModels
/// </summary>
public required OpenIddictResponse RevocationResponse { get; init; }
}
}
/// <summary>
/// Represents a dynamic client registration request (RFC 7591).
/// </summary>
public sealed record class ClientRegistrationRequest
{
/// <summary>
/// Gets or sets the cancellation token that will be
/// used to determine if the operation was aborted.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Gets or sets the initial access token attached to the registration request, if applicable.
/// </summary>
public string? InitialAccessToken { get; init; }
/// <summary>
/// Gets or sets the issuer used to resolve the client registration.
/// </summary>
/// <remarks>
/// Note: if multiple client registrations point to the same issuer,
/// the <see cref="RegistrationId"/> property must be explicitly set.
/// </remarks>
public Uri? Issuer { get; init; }
/// <summary>
/// Gets or sets the client metadata sent to the authorization server (e.g "redirect_uris" or "grant_types").
/// </summary>
public Dictionary<string, OpenIddictParameter>? Metadata { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that will be added to the context.
/// </summary>
public Dictionary<string, string?>? Properties { get; init; }
/// <summary>
/// Gets or sets the provider name used to resolve the client registration.
/// </summary>
/// <remarks>
/// Note: if multiple client registrations use the same provider name.
/// the <see cref="RegistrationId"/> property must be explicitly set.
/// </remarks>
public string? ProviderName { get; init; }
/// <summary>
/// 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.
/// </summary>
public Uri? RegistrationEndpoint { get; init; }
/// <summary>
/// Gets or sets the unique identifier of the client registration that will be used.
/// </summary>
public string? RegistrationId { get; init; }
}
/// <summary>
/// Represents a request sent to the client configuration endpoint to read,
/// update or delete the registration of a client application (RFC 7592).
/// </summary>
public sealed record class ClientConfigurationRequest
{
/// <summary>
/// Gets or sets the cancellation token that will be
/// used to determine if the operation was aborted.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Gets or sets the client identifier. If this property is not set, the client
/// identifier is resolved from the query string of <see cref="RegistrationClientUri"/>.
/// </summary>
public string? ClientId { get; init; }
/// <summary>
/// Gets or sets the issuer used to resolve the client registration.
/// </summary>
public Uri? Issuer { get; init; }
/// <summary>
/// Gets or sets the client metadata sent to the authorization server when updating a client registration.
/// </summary>
/// <remarks>
/// Note: update requests use full replace semantics: metadata that are not included are removed or reset.
/// </remarks>
public Dictionary<string, OpenIddictParameter>? Metadata { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that will be added to the context.
/// </summary>
public Dictionary<string, string?>? Properties { get; init; }
/// <summary>
/// Gets or sets the provider name used to resolve the client registration.
/// </summary>
public string? ProviderName { get; init; }
/// <summary>
/// Gets or sets the registration access token returned by the authorization server.
/// </summary>
public required string RegistrationAccessToken { get; init; }
/// <summary>
/// Gets or sets the client configuration endpoint URI returned by the authorization server.
/// </summary>
public required Uri RegistrationClientUri { get; init; }
/// <summary>
/// Gets or sets the unique identifier of the client registration that will be used.
/// </summary>
public string? RegistrationId { get; init; }
}
/// <summary>
/// Represents a dynamic client registration result (RFC 7591 and RFC 7592).
/// </summary>
public sealed record class ClientRegistrationResult
{
/// <summary>
/// Gets the client identifier issued by the authorization server, if available.
/// </summary>
public string? ClientId => (string?) RegistrationResponse[ClientMetadata.ClientId];
/// <summary>
/// Gets the date at which the client identifier was issued, if available.
/// </summary>
public DateTimeOffset? ClientIdIssuedAt => (long?) RegistrationResponse[ClientMetadata.ClientIdIssuedAt]
is long value ? DateTimeOffset.FromUnixTimeSeconds(value) : null;
/// <summary>
/// Gets the client secret issued by the authorization server, if available.
/// </summary>
public string? ClientSecret => (string?) RegistrationResponse[ClientMetadata.ClientSecret];
/// <summary>
/// Gets the date at which the client secret will expire, or <see langword="null"/>
/// if no expiration date was returned or if the client secret never expires.
/// </summary>
public DateTimeOffset? ClientSecretExpiresAt => (long?) RegistrationResponse[ClientMetadata.ClientSecretExpiresAt]
is long value and > 0 ? DateTimeOffset.FromUnixTimeSeconds(value) : null;
/// <summary>
/// Gets or sets the application-specific properties that were present in the context.
/// </summary>
public required Dictionary<string, string?> Properties { get; init; }
/// <summary>
/// Gets the registration access token returned by the authorization server, if available.
/// </summary>
public string? RegistrationAccessToken => (string?) RegistrationResponse[ClientMetadata.RegistrationAccessToken];
/// <summary>
/// Gets the client configuration endpoint URI returned by the authorization server, if available.
/// </summary>
public Uri? RegistrationClientUri => Uri.TryCreate((string?) RegistrationResponse[ClientMetadata.RegistrationClientUri],
UriKind.Absolute, out Uri? uri) ? uri : null;
/// <summary>
/// Gets or sets the registration response (that is empty for delete operations).
/// </summary>
public required OpenIddictResponse RegistrationResponse { get; init; }
}
}

276
src/OpenIddict.Client/OpenIddictClientService.cs

@ -1591,6 +1591,282 @@ public partial class OpenIddictClientService
};
}
/// <summary>
/// Registers a client application using OAuth 2.0 Dynamic Client Registration (RFC 7591).
/// </summary>
/// <param name="request">The registration request.</param>
/// <returns>The registration result, that contains the client information response.</returns>
/// <exception cref="ProtocolException">The registration request was rejected by the authorization server.</exception>
public virtual async ValueTask<ClientRegistrationResult> 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
};
}
/// <summary>
/// Retrieves the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
/// </summary>
/// <param name="request">The client configuration request.</param>
/// <returns>The registration result, that contains the client information response.</returns>
/// <remarks>
/// Note: the authorization server may issue a new registration access token that must be used for subsequent operations.
/// </remarks>
/// <exception cref="ProtocolException">The request was rejected by the authorization server.</exception>
public virtual ValueTask<ClientRegistrationResult> GetRegistrationAsync(ClientConfigurationRequest request)
=> SendClientConfigurationRequestAsync(request, "GET");
/// <summary>
/// Updates the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
/// </summary>
/// <param name="request">The client configuration request, that contains the updated client metadata.</param>
/// <returns>The registration result, that contains the client information response.</returns>
/// <remarks>
/// Note: the authorization server may issue a new registration access token that must be used for subsequent operations.
/// </remarks>
/// <exception cref="ProtocolException">The request was rejected by the authorization server.</exception>
public virtual ValueTask<ClientRegistrationResult> UpdateRegistrationAsync(ClientConfigurationRequest request)
=> SendClientConfigurationRequestAsync(request, "PUT");
/// <summary>
/// Deletes the registration of a client application using OAuth 2.0 Dynamic Client Registration Management (RFC 7592).
/// </summary>
/// <param name="request">The client configuration request.</param>
/// <returns>The registration result, whose response is empty.</returns>
/// <exception cref="ProtocolException">The request was rejected by the authorization server.</exception>
public virtual ValueTask<ClientRegistrationResult> DeleteRegistrationAsync(ClientConfigurationRequest request)
=> SendClientConfigurationRequestAsync(request, "DELETE");
private async ValueTask<ClientRegistrationResult> 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<OpenIddictClientRegistration> 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));
}
/// <summary>
/// Sends the registration request and retrieves the corresponding response.
/// </summary>
/// <param name="registration">The client registration.</param>
/// <param name="configuration">The server configuration.</param>
/// <param name="request">The registration request.</param>
/// <param name="uri">The uri of the remote registration or client configuration endpoint.</param>
/// <param name="method">The HTTP method used to send the request.</param>
/// <param name="token">The bearer token attached to the request, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The response extracted from the registration response.</returns>
internal async ValueTask<OpenIddictResponse> 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<IOpenIddictClientDispatcher>();
var options = scope.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
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<OpenIddictRequest> 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<OpenIddictRequest> 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<OpenIddictResponse> 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<OpenIddictResponse> 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;
}
}
/// <summary>
/// Retrieves the OpenID Connect server configuration from the specified uri.
/// </summary>

4
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;
}

349
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<IOptionsMonitor<OpenIddictClientOptions>>().CurrentValue;
var context = new HandleConfigurationResponseContext(CreateTransaction(provider))
{
Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>(
"""{ "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<JsonElement>(
"""{ "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<JsonElement>(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<string?>("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<HttpRequestMessage>(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<ApplyRegistrationRequestContext>(builder => builder.UseInlineHandler(context =>
{
sent = context;
return ValueTask.CompletedTask;
}));
options.AddEventHandler<ExtractRegistrationResponseContext>(builder => builder.UseInlineHandler(context =>
{
context.Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>("""
{
"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<OpenIddictClientService>();
// Act
var result = await service.RegisterAsync(new ClientRegistrationRequest
{
InitialAccessToken = "initial-token",
Metadata = new(StringComparer.Ordinal)
{
[ClientMetadata.GrantTypes] = new OpenIddictParameter(ImmutableArray.Create<string?>(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<string?>?) 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<OpenIddictClientService>();
// Act and assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(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<ApplyRegistrationRequestContext>(builder => builder.UseInlineHandler(context =>
{
sent = context;
return ValueTask.CompletedTask;
}));
options.AddEventHandler<ExtractRegistrationResponseContext>(builder => builder.UseInlineHandler(context =>
{
context.Response = new OpenIddictResponse();
return ValueTask.CompletedTask;
}));
});
var service = provider.GetRequiredService<OpenIddictClientService>();
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<OpenIddictClientService>();
// Act and assert
await Assert.ThrowsAsync<ArgumentException>(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<OpenIddictClientBuilder>? 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<IOptionsMonitor<OpenIddictClientOptions>>().CurrentValue;
return new OpenIddictClientTransaction
{
CancellationToken = CancellationToken.None,
Configuration = new OpenIddictConfiguration(),
Options = options,
Registration = options.Registrations[0],
ServiceProvider = provider
};
}
}
Loading…
Cancel
Save