Browse Source

Add OAuth 2.0 dynamic client registration and management to the server stack

- Registration endpoint (SetRegistrationEndpointUris, EnableDynamicClientRegistration) implementing
  RFC 7591 registration and RFC 7592 read/update/delete via ?client_id=, with ASP.NET Core/OWIN
  JSON extraction, 201/204 status codes, bearer errors and pass-through mode.
- Initial access tokens (dedicated scopes or anonymous registration), registration access tokens
  stored as reference token entries and rotated on read/update.
- Client metadata validation, software statement validation with trusted keys, mapping to
  application descriptors (permissions, requirements, logout settings, stored metadata).
- Discovery registration_endpoint and configuration validation.
pull/2549/head
pieroviano 2 months ago
parent
commit
ebe69efccb
  1. 72
      src/OpenIddict.Abstractions/OpenIddictConstants.cs
  2. 120
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 5
      src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
  4. 11
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs
  5. 1
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs
  6. 3
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs
  7. 20
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs
  8. 224
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Registration.cs
  9. 21
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
  10. 8
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs
  11. 11
      src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs
  12. 1
      src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs
  13. 3
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs
  14. 20
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs
  15. 219
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Registration.cs
  16. 21
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
  17. 8
      src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs
  18. 124
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  19. 35
      src/OpenIddict.Server/OpenIddictServerConfiguration.cs
  20. 6
      src/OpenIddict.Server/OpenIddictServerEndpointType.cs
  21. 5
      src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs
  22. 240
      src/OpenIddict.Server/OpenIddictServerEvents.Registration.cs
  23. 1
      src/OpenIddict.Server/OpenIddictServerExtensions.cs
  24. 14
      src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
  25. 5
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  26. 1679
      src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs
  27. 35
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  28. 52
      src/OpenIddict.Server/OpenIddictServerOptions.cs
  29. 38
      src/OpenIddict.Server/OpenIddictServerRegistrationRequestType.cs
  30. 59
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs
  31. 197
      test/OpenIddict.Server.Tests/OpenIddictServerRegistrationTests.cs

72
src/OpenIddict.Abstractions/OpenIddictConstants.cs

@ -190,6 +190,64 @@ public static class OpenIddictConstants
public const string Values = "values";
}
public static class ClientMetadata
{
public const string ApplicationType = "application_type";
public const string BackchannelLogoutSessionRequired = "backchannel_logout_session_required";
public const string BackchannelLogoutUri = "backchannel_logout_uri";
public const string ClientId = "client_id";
public const string ClientIdIssuedAt = "client_id_issued_at";
public const string ClientName = "client_name";
public const string ClientSecret = "client_secret";
public const string ClientSecretExpiresAt = "client_secret_expires_at";
public const string ClientUri = "client_uri";
public const string Contacts = "contacts";
public const string DefaultAcrValues = "default_acr_values";
public const string DefaultMaxAge = "default_max_age";
public const string DPoPBoundAccessTokens = "dpop_bound_access_tokens";
public const string FrontchannelLogoutSessionRequired = "frontchannel_logout_session_required";
public const string FrontchannelLogoutUri = "frontchannel_logout_uri";
public const string GrantTypes = "grant_types";
public const string IdTokenEncryptedResponseAlg = "id_token_encrypted_response_alg";
public const string IdTokenEncryptedResponseEnc = "id_token_encrypted_response_enc";
public const string IdTokenSignedResponseAlg = "id_token_signed_response_alg";
public const string InitiateLoginUri = "initiate_login_uri";
public const string Jwks = "jwks";
public const string JwksUri = "jwks_uri";
public const string LogoUri = "logo_uri";
public const string PolicyUri = "policy_uri";
public const string PostLogoutRedirectUris = "post_logout_redirect_uris";
public const string RedirectUris = "redirect_uris";
public const string RegistrationAccessToken = "registration_access_token";
public const string RegistrationClientUri = "registration_client_uri";
public const string RequestObjectEncryptionAlg = "request_object_encryption_alg";
public const string RequestObjectEncryptionEnc = "request_object_encryption_enc";
public const string RequestObjectSigningAlg = "request_object_signing_alg";
public const string RequestUris = "request_uris";
public const string RequireAuthTime = "require_auth_time";
public const string RequirePushedAuthorizationRequests = "require_pushed_authorization_requests";
public const string RequireSignedRequestObject = "require_signed_request_object";
public const string ResponseTypes = "response_types";
public const string Scope = "scope";
public const string SectorIdentifierUri = "sector_identifier_uri";
public const string SoftwareId = "software_id";
public const string SoftwareStatement = "software_statement";
public const string SoftwareVersion = "software_version";
public const string SubjectType = "subject_type";
public const string TlsClientAuthSanDns = "tls_client_auth_san_dns";
public const string TlsClientAuthSanEmail = "tls_client_auth_san_email";
public const string TlsClientAuthSanIp = "tls_client_auth_san_ip";
public const string TlsClientAuthSanUri = "tls_client_auth_san_uri";
public const string TlsClientAuthSubjectDn = "tls_client_auth_subject_dn";
public const string TlsClientCertificateBoundAccessTokens = "tls_client_certificate_bound_access_tokens";
public const string TokenEndpointAuthMethod = "token_endpoint_auth_method";
public const string TokenEndpointAuthSigningAlg = "token_endpoint_auth_signing_alg";
public const string TosUri = "tos_uri";
public const string UserinfoEncryptedResponseAlg = "userinfo_encrypted_response_alg";
public const string UserinfoEncryptedResponseEnc = "userinfo_encrypted_response_enc";
public const string UserinfoSignedResponseAlg = "userinfo_signed_response_alg";
}
public static class ClientAssertionTypes
{
public const string JwtBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
@ -247,12 +305,15 @@ public static class OpenIddictConstants
public const string InteractionRequired = "interaction_required";
public const string InvalidBindingMessage = "invalid_binding_message";
public const string InvalidClient = "invalid_client";
public const string InvalidClientMetadata = "invalid_client_metadata";
public const string InvalidDPoPProof = "invalid_dpop_proof";
public const string InvalidGrant = "invalid_grant";
public const string InvalidRedirectUri = "invalid_redirect_uri";
public const string InvalidRequest = "invalid_request";
public const string InvalidRequestObject = "invalid_request_object";
public const string InvalidRequestUri = "invalid_request_uri";
public const string InvalidScope = "invalid_scope";
public const string InvalidSoftwareStatement = "invalid_software_statement";
public const string InvalidTarget = "invalid_target";
public const string InvalidToken = "invalid_token";
public const string InvalidUserCode = "invalid_user_code";
@ -265,6 +326,7 @@ public static class OpenIddictConstants
public const string ServerError = "server_error";
public const string SlowDown = "slow_down";
public const string TemporarilyUnavailable = "temporarily_unavailable";
public const string UnapprovedSoftwareStatement = "unapproved_software_statement";
public const string UnauthorizedClient = "unauthorized_client";
public const string UnknownUserId = "unknown_user_id";
public const string UnmetAuthenticationRequirements = "unmet_authentication_requirements";
@ -357,6 +419,7 @@ public static class OpenIddictConstants
public const string PromptValuesSupported = "prompt_values_supported";
public const string PushedAuthorizationRequestEndpoint = "pushed_authorization_request_endpoint";
public const string PushedAuthorizationRequestEndpointAuthMethodsSupported = "pushed_authorization_request_endpoint_auth_methods_supported";
public const string RegistrationEndpoint = "registration_endpoint";
public const string RequestObjectEncryptionAlgValuesSupported = "request_object_encryption_alg_values_supported";
public const string RequestObjectEncryptionEncValuesSupported = "request_object_encryption_enc_values_supported";
public const string RequestObjectSigningAlgValuesSupported = "request_object_signing_alg_values_supported";
@ -481,6 +544,7 @@ public static class OpenIddictConstants
public const string EndSession = "ept:end_session";
public const string Introspection = "ept:introspection";
public const string PushedAuthorization = "ept:pushed_authorization";
public const string Registration = "ept:registration";
public const string Revocation = "ept:revocation";
public const string Token = "ept:token";
}
@ -540,6 +604,7 @@ public static class OpenIddictConstants
public static class Properties
{
public const string ClientMetadata = ".client_metadata";
public const string Destinations = ".destinations";
public const string LastPollingDate = ".last_polling_date";
public const string LoginId = ".login_id";
@ -639,6 +704,7 @@ public static class OpenIddictConstants
{
public const string IntrospectionResponse = "intr_rsp:";
public const string Logout = "lgt:";
public const string Registration = "reg:";
public const string TokenLifetime = "tkn_lft:";
}
@ -650,6 +716,11 @@ public static class OpenIddictConstants
public const string FrontchannelLogoutUri = "lgt:fcl_uri";
}
public static class Registration
{
public const string IdentityTokenSigningAlgorithm = "reg:idt_sign_alg";
}
public static class IntrospectionResponse
{
public const string EncryptionAlgorithm = "intr_rsp:enc_alg";
@ -736,6 +807,7 @@ public static class OpenIddictConstants
public const string DPoPProof = "urn:openiddict:params:oauth:token-type:dpop_proof";
public const string IntrospectionResponse = "urn:openiddict:params:oauth:token-type:introspection_response";
public const string LogoutToken = "urn:openiddict:params:oauth:token-type:logout_token";
public const string RegistrationAccessToken = "urn:openiddict:params:oauth:token-type:registration_access_token";
public const string RequestObject = "urn:openiddict:params:oauth:token-type:request_object";
public const string RequestToken = "urn:openiddict:params:oauth:token-type:request_token";
public const string StateToken = "urn:openiddict:params:oauth:token-type:state_token";

120
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2035,6 +2035,36 @@ To apply front-channel logout responses, create a class implementing 'IOpenIddic
To terminate the local session attached to the user agent, set the sign-out scheme using 'services.AddOpenIddict().AddClient().UseAspNetCore().SetFrontchannelLogoutSignOutScheme()' (or 'UseOwin().SetFrontchannelLogoutSignOutAuthenticationType()').
Alternatively, enable the pass-through mode using 'EnableFrontchannelLogoutEndpointPassthrough()', handle 'HandleFrontchannelLogoutRequestContext' using a custom event handler or register an 'IOpenIddictClientSessionStore' implementation and disable session verification using 'services.AddOpenIddict().AddClient().DisableFrontchannelLogoutSessionVerification()'.</value>
</data>
<data name="ID0800" xml:space="preserve">
<value>The registration endpoint must be enabled when dynamic client registration is enabled.
To enable it, use 'services.AddOpenIddict().AddServer().SetRegistrationEndpointUris()'.</value>
</data>
<data name="ID0801" xml:space="preserve">
<value>Dynamic client registration must be enabled when the registration endpoint is enabled.
To enable it, use 'services.AddOpenIddict().AddServer().EnableDynamicClientRegistration()'.</value>
</data>
<data name="ID0802" xml:space="preserve">
<value>Dynamic client registration cannot be used when the degraded mode is enabled or when token storage is disabled.</value>
</data>
<data name="ID0803" xml:space="preserve">
<value>At least one initial access token scope must be configured when anonymous client registration is not allowed.
To configure it, use 'services.AddOpenIddict().AddServer().SetInitialAccessTokenScopes()' or allow open registration using 'AllowAnonymousClientRegistration()'.</value>
</data>
<data name="ID0804" xml:space="preserve">
<value>At least one software statement signing key must be registered when software statements are required.
To register one, use 'services.AddOpenIddict().AddServer().AddSoftwareStatementSigningKey()'.</value>
</data>
<data name="ID0805" xml:space="preserve">
<value>The registration request was not correctly extracted.
To extract registration requests, create a class implementing 'IOpenIddictServerHandler&lt;ExtractRegistrationRequestContext&gt;' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.</value>
</data>
<data name="ID0806" xml:space="preserve">
<value>The registration response was not correctly applied.
To apply registration responses, create a class implementing 'IOpenIddictServerHandler&lt;ApplyRegistrationResponseContext&gt;' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.</value>
</data>
<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="ID2000" xml:space="preserve">
<value>The security token is missing.</value>
</data>
@ -2886,6 +2916,66 @@ Alternatively, enable the pass-through mode using 'EnableFrontchannelLogoutEndpo
<data name="ID2391" xml:space="preserve">
<value>The sessions targeted by the logout request couldn't be terminated.</value>
</data>
<data name="ID2400" xml:space="preserve">
<value>The specified registration access token is invalid.</value>
</data>
<data name="ID2401" xml:space="preserve">
<value>An initial access token is required to register a client application.</value>
</data>
<data name="ID2402" xml:space="preserve">
<value>The specified initial access token doesn't contain a scope allowing the registration of client applications.</value>
</data>
<data name="ID2403" xml:space="preserve">
<value>The '{0}' client metadata is invalid.</value>
</data>
<data name="ID2404" xml:space="preserve">
<value>The '{0}' client metadata value '{1}' is not supported by this authorization server.</value>
</data>
<data name="ID2405" xml:space="preserve">
<value>The '{0}' client metadata must only contain absolute URIs that don't include a fragment.</value>
</data>
<data name="ID2406" xml:space="preserve">
<value>The '{0}' client metadata is required when using the '{1}' grant type.</value>
</data>
<data name="ID2407" xml:space="preserve">
<value>The '{0}' response type cannot be used without the '{1}' grant type.</value>
</data>
<data name="ID2408" xml:space="preserve">
<value>The '{0}' and '{1}' client metadata cannot be used together.</value>
</data>
<data name="ID2409" xml:space="preserve">
<value>The specified software statement is invalid.</value>
</data>
<data name="ID2410" xml:space="preserve">
<value>The specified software statement was not issued or signed by a trusted party.</value>
</data>
<data name="ID2411" xml:space="preserve">
<value>A software statement is required to register a client application.</value>
</data>
<data name="ID2412" xml:space="preserve">
<value>The '{0}' client metadata cannot be specified when updating a client registration.</value>
</data>
<data name="ID2413" xml:space="preserve">
<value>The '{0}' client metadata doesn't match the client identifier of the client configuration endpoint.</value>
</data>
<data name="ID2414" xml:space="preserve">
<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>
</data>
<data name="ID2416" xml:space="preserve">
<value>The client metadata was rejected by the application manager.</value>
</data>
<data name="ID2417" xml:space="preserve">
<value>The '{0}' client metadata is required when using the '{1}' client authentication method.</value>
</data>
<data name="ID2418" xml:space="preserve">
<value>The JSON Web Key Set must only contain public asymmetric keys.</value>
</data>
<data name="ID2419" xml:space="preserve">
<value>The request payload must be a valid JSON object.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>
@ -3924,6 +4014,36 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6570" xml:space="preserve">
<value>The front-channel logout request was rejected because it didn't include the 'iss' and 'sid' parameters and no unique client registration allows omitting them. Ensure the 'frontchannel_logout_session_required' metadata registered at the authorization server matches the 'FrontchannelLogoutSessionRequired' property of the client registration.</value>
</data>
<data name="ID6600" xml:space="preserve">
<value>The registration request was successfully extracted: {Request}.</value>
</data>
<data name="ID6601" xml:space="preserve">
<value>The registration request was successfully validated.</value>
</data>
<data name="ID6602" xml:space="preserve">
<value>The registration request was rejected because the '{Metadata}' client metadata was invalid.</value>
</data>
<data name="ID6603" xml:space="preserve">
<value>The registration request was rejected because the registration access token was invalid.</value>
</data>
<data name="ID6604" xml:space="preserve">
<value>The client application '{ClientId}' was successfully registered.</value>
</data>
<data name="ID6605" xml:space="preserve">
<value>The client application '{ClientId}' was successfully updated.</value>
</data>
<data name="ID6606" xml:space="preserve">
<value>The client application '{ClientId}' was successfully deleted.</value>
</data>
<data name="ID6607" xml:space="preserve">
<value>The registration request was rejected because the software statement couldn't be validated.</value>
</data>
<data name="ID6608" xml:space="preserve">
<value>The registration request was rejected by the application manager.</value>
</data>
<data name="ID6609" xml:space="preserve">
<value>The response was successfully returned as an empty 204 response.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

5
src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs

@ -197,6 +197,11 @@ public sealed class OpenIddictConfiguration
/// </summary>
public HashSet<string> ResponseTypesSupported { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the URI of the dynamic client registration endpoint (RFC 7591).
/// </summary>
public Uri? RegistrationEndpoint { get; set; }
/// <summary>
/// Gets or sets the URI of the revocation endpoint.
/// </summary>

11
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs

@ -84,6 +84,17 @@ public sealed class OpenIddictServerAspNetCoreBuilder
public OpenIddictServerAspNetCoreBuilder EnableBackchannelAuthenticationEndpointPassthrough()
=> Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the dynamic client registration endpoint (RFC 7591 and RFC 7592).
/// When the pass-through mode is used, registration requests are initially validated by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that registration requests
/// can be approved (by triggering a sign-in operation) or rejected (by triggering a challenge operation)
/// at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
/// <returns>The <see cref="OpenIddictServerAspNetCoreBuilder"/> instance.</returns>
public OpenIddictServerAspNetCoreBuilder EnableRegistrationEndpointPassthrough()
=> Configure(options => options.EnableRegistrationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

1
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs

@ -45,6 +45,7 @@ public static class OpenIddictServerAspNetCoreExtensions
builder.Services.TryAddSingleton<RequireUserInfoEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireVerificationEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireRegistrationEndpointPassthroughEnabled>();
// Register the option initializers used by the OpenIddict ASP.NET Core server integration services.
// Note: TryAddEnumerable() is used here to ensure the initializers are only registered once.

3
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs

@ -182,7 +182,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()
=> context.SubjectTokenPrincipal,
OpenIddictServerEndpointType.UserInfo => context.AccessTokenPrincipal,
OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.Registration
=> context.AccessTokenPrincipal,
_ => null
};

20
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs

@ -56,6 +56,26 @@ public static class OpenIddictServerAspNetCoreHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the
/// pass-through mode was not enabled for the registration endpoint.
/// </summary>
public sealed class RequireRegistrationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter<BaseContext>
{
private readonly IOptionsMonitor<OpenIddictServerAspNetCoreOptions> _options;
public RequireRegistrationEndpointPassthroughEnabled(IOptionsMonitor<OpenIddictServerAspNetCoreOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(BaseContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(_options.CurrentValue.EnableRegistrationEndpointPassthrough);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the
/// pass-through mode was not enabled for the end session endpoint.

224
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Registration.cs

@ -0,0 +1,224 @@
/*
* 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.Text.Json;
using Microsoft.AspNetCore;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace OpenIddict.Server.AspNetCore;
public static partial class OpenIddictServerAspNetCoreHandlers
{
public static class Registration
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Registration request extraction:
*/
ExtractRegistrationRequest.Descriptor,
ExtractAccessToken<ExtractRegistrationRequestContext>.Descriptor,
/*
* Registration request handling:
*/
EnablePassthroughMode<HandleRegistrationRequestContext, RequireRegistrationEndpointPassthroughEnabled>.Descriptor,
/*
* Registration response processing:
*/
AttachHttpResponseCode<ApplyRegistrationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyRegistrationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyRegistrationResponseContext>.Descriptor,
ProcessChallengeErrorResponse<ApplyRegistrationResponseContext>.Descriptor,
ProcessNoContentResponse.Descriptor,
ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor
];
/// <summary>
/// Contains the logic responsible for extracting registration requests: client metadata are extracted from
/// the JSON payload of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2) and the
/// client identifier used by the client configuration endpoint is extracted from the query string.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler<ExtractRegistrationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ExtractRegistrationRequestContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ExtractRegistrationRequest>()
.SetOrder(ExtractPostRequest<ExtractRegistrationRequestContext>.Descriptor.Order)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ExtractRegistrationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var query = new OpenIddictRequest(request.Query);
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsDelete(request.Method))
{
context.Transaction.Request = query;
return;
}
if (!HttpMethods.IsPost(request.Method) && !HttpMethods.IsPut(request.Method))
{
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.Method);
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2084),
uri: SR.FormatID8000(SR.ID2084));
return;
}
if (string.IsNullOrEmpty(request.ContentType))
{
context.Logger.LogInformation(6138, SR.GetResourceString(SR.ID6138), HeaderNames.ContentType);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2081(HeaderNames.ContentType),
uri: SR.FormatID8000(SR.ID2081));
return;
}
// May have media/type; charset=utf-8, allow partial match.
if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6139, SR.GetResourceString(SR.ID6139), HeaderNames.ContentType, request.ContentType);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2082(HeaderNames.ContentType),
uri: SR.FormatID8000(SR.ID2082));
return;
}
JsonElement payload;
try
{
using var document = await JsonDocument.ParseAsync(request.Body, cancellationToken: context.CancellationToken);
payload = document.RootElement.Clone();
}
catch (JsonException)
{
payload = default;
}
if (payload.ValueKind is not JsonValueKind.Object)
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2419),
uri: SR.FormatID8000(SR.ID2419));
return;
}
if (!TryMergeQueryParameters(new OpenIddictRequest(payload), query, out var result))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2413(Parameters.ClientId),
uri: SR.FormatID8000(SR.ID2413));
return;
}
context.Transaction.Request = result;
}
}
/// <summary>
/// Contains the logic responsible for processing successful client deletion responses, that MUST
/// be returned as empty 204 responses (RFC 7592, section 2.3).
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ProcessNoContentResponse : IOpenIddictServerHandler<ApplyRegistrationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyRegistrationResponseContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ProcessNoContentResponse>()
.SetOrder(ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ApplyRegistrationResponseContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (response.StatusCode is not 204)
{
return ValueTask.CompletedTask;
}
context.Logger.LogInformation(6609, SR.GetResourceString(SR.ID6609));
context.HandleRequest();
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Merges the query string parameters with the parameters extracted from the JSON payload.
/// </summary>
internal static bool TryMergeQueryParameters(OpenIddictRequest payload, OpenIddictRequest query, out OpenIddictRequest result)
{
result = payload;
foreach (var parameter in query.GetParameters())
{
if (!payload.HasParameter(parameter.Key))
{
payload.SetParameter(parameter.Key, parameter.Value);
continue;
}
// The client identifier specified in the payload of update requests MUST match
// the client identifier used to identify the client configuration endpoint.
//
// See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information.
if (parameter.Key is Parameters.ClientId &&
!string.Equals((string?) payload[Parameters.ClientId], (string?) parameter.Value, StringComparison.Ordinal))
{
return false;
}
}
return true;
}
}
}

21
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs

@ -58,6 +58,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
.. Logout.DefaultHandlers,
.. Registration.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. Session.DefaultHandlers,
.. UserInfo.DefaultHandlers
@ -1011,6 +1012,16 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// See https://datatracker.ietf.org/doc/html/rfc9126#section-2.2 for more information.
(OpenIddictServerEndpointType.PushedAuthorization, null or { Length: 0 }) => 201,
// Note: successful client registration responses MUST use the 201 status code and successful
// client deletion responses MUST use the 204 status code.
//
// See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1
// and https://datatracker.ietf.org/doc/html/rfc7592#section-2.3 for more information.
(OpenIddictServerEndpointType.Registration, null or { Length: 0 }) when string.Equals(
context.Transaction.RequestMethod, "POST", StringComparison.OrdinalIgnoreCase) => 201,
(OpenIddictServerEndpointType.Registration, null or { Length: 0 }) when string.Equals(
context.Transaction.RequestMethod, "DELETE", StringComparison.OrdinalIgnoreCase) => 204,
// Note: the default code may be replaced by another handler (e.g when doing redirects).
(_, null or { Length: 0 }) => 200,
@ -1022,6 +1033,11 @@ public static partial class OpenIddictServerAspNetCoreHandlers
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// Errors caused by missing or invalid initial access tokens or registration access tokens are
// returned as bearer token errors (RFC 7591, section 3 and RFC 7592, section 2).
(OpenIddictServerEndpointType.Registration, Errors.InvalidToken or Errors.MissingToken) => 401,
(OpenIddictServerEndpointType.Registration, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// When client authentication is made using basic authentication, the authorization server
// MUST return a 401 response with a valid WWW-Authenticate header containing the HTTP Basic
// authentication scheme. A similar error MAY be returned even when using client_secret_post.
@ -1129,6 +1145,11 @@ public static partial class OpenIddictServerAspNetCoreHandlers
context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) => Schemes.Bearer,
// Errors caused by missing or invalid initial access tokens or registration
// access tokens are returned as part of the WWW-Authenticate header.
(OpenIddictServerEndpointType.Registration, Errors.InvalidToken or Errors.MissingToken or
Errors.InsufficientAccess or Errors.InsufficientScope) => Schemes.Bearer,
// When client authentication is made using basic authentication, the authorization server
// MUST return a 401 response with a valid WWW-Authenticate header containing the HTTP Basic
// authentication scheme. A similar error MAY be returned even when using client_secret_post.

8
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs

@ -35,6 +35,14 @@ public sealed class OpenIddictServerAspNetCoreOptions
/// </summary>
public bool EnableBackchannelAuthenticationEndpointPassthrough { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the pass-through mode is enabled for the registration endpoint.
/// When the pass-through mode is used, registration requests are initially validated by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that registration requests
/// can be approved or rejected at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
public bool EnableRegistrationEndpointPassthrough { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the pass-through mode is enabled for the end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

11
src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs

@ -84,6 +84,17 @@ public sealed class OpenIddictServerOwinBuilder
public OpenIddictServerOwinBuilder EnableBackchannelAuthenticationEndpointPassthrough()
=> Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the dynamic client registration endpoint (RFC 7591 and RFC 7592).
/// When the pass-through mode is used, registration requests are initially validated by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that registration requests
/// can be approved (by triggering a sign-in operation) or rejected (by triggering a challenge operation)
/// at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
/// <returns>The <see cref="OpenIddictServerOwinBuilder"/> instance.</returns>
public OpenIddictServerOwinBuilder EnableRegistrationEndpointPassthrough()
=> Configure(options => options.EnableRegistrationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

1
src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs

@ -47,6 +47,7 @@ public static class OpenIddictServerOwinExtensions
builder.Services.TryAddSingleton<RequireUserInfoEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireVerificationEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationEndpointPassthroughEnabled>();
builder.Services.TryAddSingleton<RequireRegistrationEndpointPassthroughEnabled>();
// Register the option initializers used by the OpenIddict OWIN server integration services.
// Note: TryAddEnumerable() is used here to ensure the initializers are only registered once.

3
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs

@ -195,7 +195,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()
=> context.SubjectTokenPrincipal,
OpenIddictServerEndpointType.UserInfo => context.AccessTokenPrincipal,
OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.Registration
=> context.AccessTokenPrincipal,
_ => null
};

20
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs

@ -54,6 +54,26 @@ public static class OpenIddictServerOwinHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the
/// pass-through mode was not enabled for the registration endpoint.
/// </summary>
public sealed class RequireRegistrationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter<BaseContext>
{
private readonly IOptionsMonitor<OpenIddictServerOwinOptions> _options;
public RequireRegistrationEndpointPassthroughEnabled(IOptionsMonitor<OpenIddictServerOwinOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(BaseContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(_options.CurrentValue.EnableRegistrationEndpointPassthrough);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the
/// pass-through mode was not enabled for the end session endpoint.

219
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Registration.cs

@ -0,0 +1,219 @@
/*
* 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.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Owin;
using static OpenIddict.Server.Owin.OpenIddictServerOwinConstants;
namespace OpenIddict.Server.Owin;
public static partial class OpenIddictServerOwinHandlers
{
public static class Registration
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Registration request extraction:
*/
ExtractRegistrationRequest.Descriptor,
ExtractAccessToken<ExtractRegistrationRequestContext>.Descriptor,
/*
* Registration request handling:
*/
EnablePassthroughMode<HandleRegistrationRequestContext, RequireRegistrationEndpointPassthroughEnabled>.Descriptor,
/*
* Registration response processing:
*/
AttachHttpResponseCode<ApplyRegistrationResponseContext>.Descriptor,
AttachOwinResponseChallenge<ApplyRegistrationResponseContext>.Descriptor,
SuppressFormsAuthenticationRedirect<ApplyRegistrationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyRegistrationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyRegistrationResponseContext>.Descriptor,
ProcessChallengeErrorResponse<ApplyRegistrationResponseContext>.Descriptor,
ProcessNoContentResponse.Descriptor,
ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor
];
/// <summary>
/// Contains the logic responsible for extracting registration requests: client metadata are extracted from
/// the JSON payload of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2) and the
/// client identifier used by the client configuration endpoint is extracted from the query string.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
/// </summary>
public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler<ExtractRegistrationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ExtractRegistrationRequestContext>()
.AddFilter<RequireOwinRequest>()
.UseSingletonHandler<ExtractRegistrationRequest>()
.SetOrder(ExtractPostRequest<ExtractRegistrationRequestContext>.Descriptor.Order)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ExtractRegistrationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var query = new OpenIddictRequest(
from parameter in request.Query
let values = new StringValues(parameter.Value)
select KeyValuePair.Create(parameter.Key, values));
if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase) ||
string.Equals(request.Method, "DELETE", StringComparison.OrdinalIgnoreCase))
{
context.Transaction.Request = query;
return;
}
if (!string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(request.Method, "PUT", StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.Method);
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2084),
uri: SR.FormatID8000(SR.ID2084));
return;
}
if (string.IsNullOrEmpty(request.ContentType))
{
context.Logger.LogInformation(6138, SR.GetResourceString(SR.ID6138), Headers.ContentType);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2081(Headers.ContentType),
uri: SR.FormatID8000(SR.ID2081));
return;
}
// May have media/type; charset=utf-8, allow partial match.
if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6139, SR.GetResourceString(SR.ID6139), Headers.ContentType, request.ContentType);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2082(Headers.ContentType),
uri: SR.FormatID8000(SR.ID2082));
return;
}
JsonElement payload;
try
{
using var document = await JsonDocument.ParseAsync(request.Body, cancellationToken: context.CancellationToken);
payload = document.RootElement.Clone();
}
catch (JsonException)
{
payload = default;
}
if (payload.ValueKind is not JsonValueKind.Object)
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2419),
uri: SR.FormatID8000(SR.ID2419));
return;
}
var result = new OpenIddictRequest(payload);
foreach (var parameter in query.GetParameters())
{
if (!result.HasParameter(parameter.Key))
{
result.SetParameter(parameter.Key, parameter.Value);
continue;
}
// The client identifier specified in the payload of update requests MUST match
// the client identifier used to identify the client configuration endpoint.
//
// See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information.
if (parameter.Key is Parameters.ClientId &&
!string.Equals((string?) result[Parameters.ClientId], (string?) parameter.Value, StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2413(Parameters.ClientId),
uri: SR.FormatID8000(SR.ID2413));
return;
}
}
context.Transaction.Request = result;
}
}
/// <summary>
/// Contains the logic responsible for processing successful client deletion responses, that MUST
/// be returned as empty 204 responses (RFC 7592, section 2.3).
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
/// </summary>
public sealed class ProcessNoContentResponse : IOpenIddictServerHandler<ApplyRegistrationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyRegistrationResponseContext>()
.AddFilter<RequireOwinRequest>()
.UseSingletonHandler<ProcessNoContentResponse>()
.SetOrder(ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor.Order - 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ApplyRegistrationResponseContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
var response = context.Transaction.GetOwinRequest()?.Context.Response
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (response.StatusCode is not 204)
{
return ValueTask.CompletedTask;
}
context.Logger.LogInformation(6609, SR.GetResourceString(SR.ID6609));
context.HandleRequest();
return ValueTask.CompletedTask;
}
}
}
}

21
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs

@ -56,6 +56,7 @@ public static partial class OpenIddictServerOwinHandlers
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
.. Logout.DefaultHandlers,
.. Registration.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. Session.DefaultHandlers,
.. UserInfo.DefaultHandlers
@ -1088,6 +1089,16 @@ public static partial class OpenIddictServerOwinHandlers
// See https://datatracker.ietf.org/doc/html/rfc9126#section-2.2 for more information.
(OpenIddictServerEndpointType.PushedAuthorization, null or { Length: 0 }) => 201,
// Note: successful client registration responses MUST use the 201 status code and successful
// client deletion responses MUST use the 204 status code.
//
// See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1
// and https://datatracker.ietf.org/doc/html/rfc7592#section-2.3 for more information.
(OpenIddictServerEndpointType.Registration, null or { Length: 0 }) when string.Equals(
context.Transaction.RequestMethod, "POST", StringComparison.OrdinalIgnoreCase) => 201,
(OpenIddictServerEndpointType.Registration, null or { Length: 0 }) when string.Equals(
context.Transaction.RequestMethod, "DELETE", StringComparison.OrdinalIgnoreCase) => 204,
// Note: the default code may be replaced by another handler (e.g when doing redirects).
(_, null or { Length: 0 }) => 200,
@ -1099,6 +1110,11 @@ public static partial class OpenIddictServerOwinHandlers
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// Errors caused by missing or invalid initial access tokens or registration access tokens are
// returned as bearer token errors (RFC 7591, section 3 and RFC 7592, section 2).
(OpenIddictServerEndpointType.Registration, Errors.InvalidToken or Errors.MissingToken) => 401,
(OpenIddictServerEndpointType.Registration, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// When client authentication is made using basic authentication, the authorization server
// MUST return a 401 response with a valid WWW-Authenticate header containing the HTTP Basic
// authentication scheme. A similar error MAY be returned even when using client_secret_post.
@ -1320,6 +1336,11 @@ public static partial class OpenIddictServerOwinHandlers
context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) => Schemes.Bearer,
// Errors caused by missing or invalid initial access tokens or registration
// access tokens are returned as part of the WWW-Authenticate header.
(OpenIddictServerEndpointType.Registration, Errors.InvalidToken or Errors.MissingToken or
Errors.InsufficientAccess or Errors.InsufficientScope) => Schemes.Bearer,
// When client authentication is made using basic authentication, the authorization server
// MUST return a 401 response with a valid WWW-Authenticate header containing the HTTP Basic
// authentication scheme. A similar error MAY be returned even when using client_secret_post.

8
src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs

@ -35,6 +35,14 @@ public sealed class OpenIddictServerOwinOptions
/// </summary>
public bool EnableBackchannelAuthenticationEndpointPassthrough { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the pass-through mode is enabled for the registration endpoint.
/// When the pass-through mode is used, registration requests are initially validated by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that registration requests
/// can be approved or rejected at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
public bool EnableRegistrationEndpointPassthrough { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the pass-through mode is enabled for the end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

124
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -1364,6 +1364,49 @@ public sealed class OpenIddictServerBuilder
});
}
/// <summary>
/// Sets the relative or absolute URIs associated to the dynamic client registration endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
/// Note: only the first URI will be returned as part of the discovery document.
/// </summary>
/// <param name="uris">The URIs associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetRegistrationEndpointUris(
[StringSyntax(StringSyntaxAttribute.Uri)] params string[] uris)
{
ArgumentNullException.ThrowIfNull(uris);
return SetRegistrationEndpointUris([.. uris.Select(uri => new Uri(uri, UriKind.RelativeOrAbsolute))]);
}
/// <summary>
/// Sets the relative or absolute URIs associated to the dynamic client registration endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
/// Note: only the first URI will be returned as part of the discovery document.
/// </summary>
/// <param name="uris">The URIs associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetRegistrationEndpointUris(params Uri[] uris)
{
ArgumentNullException.ThrowIfNull(uris);
if (Array.Exists(uris, OpenIddictHelpers.IsImplicitFileUri))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0072), nameof(uris));
}
if (Array.Exists(uris, static uri => uri.OriginalString.StartsWith("~", StringComparison.OrdinalIgnoreCase)))
{
throw new ArgumentException(SR.FormatID0081("~"), nameof(uris));
}
return Configure(options =>
{
options.RegistrationEndpointUris.Clear();
options.RegistrationEndpointUris.AddRange(uris);
});
}
/// <summary>
/// Sets the relative or absolute URIs associated to the revocation endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
@ -2024,6 +2067,87 @@ public sealed class OpenIddictServerBuilder
public OpenIddictServerBuilder SetSessionLifetime(TimeSpan? lifetime)
=> Configure(options => options.SessionLifetime = lifetime);
/// <summary>
/// Enables OAuth 2.0 Dynamic Client Registration (RFC 7591) and Dynamic Client Registration Management
/// (RFC 7592). By default, registration requests must include an initial access token issued by this
/// server and containing one of the scopes configured using <see cref="SetInitialAccessTokenScopes(string[])"/>.
/// </summary>
/// <remarks>
/// Note: the registration endpoint URI must be set using <see cref="SetRegistrationEndpointUris(string[])"/>.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder EnableDynamicClientRegistration()
=> Configure(options => options.EnableDynamicClientRegistration = true);
/// <summary>
/// Allows client registration requests that don't include an initial access token (open registration).
/// </summary>
/// <remarks>
/// Enabling open registration is NOT recommended unless custom handlers are used to approve registrations.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowAnonymousClientRegistration()
=> Configure(options => options.AllowAnonymousClientRegistration = true);
/// <summary>
/// Sets the scopes initial access tokens must contain (at least one of them) to be accepted by the registration endpoint.
/// </summary>
/// <param name="scopes">The scopes.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetInitialAccessTokenScopes(params string[] scopes)
{
ArgumentNullException.ThrowIfNull(scopes);
if (Array.Exists(scopes, string.IsNullOrEmpty))
{
throw new ArgumentException(SR.FormatID0457(nameof(scopes)), nameof(scopes));
}
return Configure(options =>
{
options.InitialAccessTokenScopes.Clear();
options.InitialAccessTokenScopes.UnionWith(scopes);
});
}
/// <summary>
/// Sets the registration access token lifetime. By default, registration access tokens never expire.
/// </summary>
/// <param name="lifetime">The registration access token lifetime.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetRegistrationAccessTokenLifetime(TimeSpan? lifetime)
=> Configure(options => options.RegistrationAccessTokenLifetime = lifetime);
/// <summary>
/// Configures OpenIddict to require a software statement in client registration requests.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder RequireSoftwareStatement()
=> Configure(options => options.RequireSoftwareStatement = true);
/// <summary>
/// Adds a key trusted to sign the software statements sent to the registration endpoint.
/// </summary>
/// <param name="key">The security key.</param>
/// <param name="issuers">The issuers allowed to issue software statements, if applicable.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSoftwareStatementSigningKey(SecurityKey key, params string[] issuers)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(issuers);
if (Array.Exists(issuers, string.IsNullOrEmpty))
{
throw new ArgumentException(SR.FormatID0457(nameof(issuers)), nameof(issuers));
}
return Configure(options =>
{
options.SoftwareStatementSigningKeys.Add(key);
options.SoftwareStatementIssuers.UnionWith(issuers);
});
}
/// <summary>
/// Configures OpenIddict to require a valid DPoP proof for all token requests.
/// </summary>

35
src/OpenIddict.Server/OpenIddictServerConfiguration.cs

@ -229,6 +229,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
.Concat(options.IntrospectionEndpointUris.Distinct())
.Concat(options.EndSessionEndpointUris.Distinct())
.Concat(options.PushedAuthorizationEndpointUris.Distinct())
.Concat(options.RegistrationEndpointUris.Distinct())
.Concat(options.RevocationEndpointUris.Distinct())
.Concat(options.TokenEndpointUris.Distinct())
.Concat(options.UserInfoEndpointUris.Distinct())
@ -299,6 +300,40 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
builder.AddError(SR.GetResourceString(SR.ID0529));
}
// Ensure the registration endpoint and dynamic client registration are always enabled together.
if (options.EnableDynamicClientRegistration && options.RegistrationEndpointUris.Count is 0)
{
builder.AddError(SR.GetResourceString(SR.ID0800));
}
if (!options.EnableDynamicClientRegistration && options.RegistrationEndpointUris.Count is > 0)
{
builder.AddError(SR.GetResourceString(SR.ID0801));
}
if (options.EnableDynamicClientRegistration)
{
// Registered clients are persisted using the application manager and registration
// access tokens are stored as token entries: the degraded mode and disabling token
// storage are not supported.
if (options.EnableDegradedMode || options.DisableTokenStorage)
{
builder.AddError(SR.GetResourceString(SR.ID0802));
}
// Unless open registration is explicitly allowed, initial access tokens must contain a dedicated scope
// to prevent regular access tokens issued to any client from being usable to register new clients.
if (!options.AllowAnonymousClientRegistration && options.InitialAccessTokenScopes.Count is 0)
{
builder.AddError(SR.GetResourceString(SR.ID0803));
}
if (options.RequireSoftwareStatement && options.SoftwareStatementSigningKeys.Count is 0)
{
builder.AddError(SR.GetResourceString(SR.ID0804));
}
}
// Ensure the grant types/response types configuration is consistent.
foreach (var type in options.ResponseTypes)
{

6
src/OpenIddict.Server/OpenIddictServerEndpointType.cs

@ -76,6 +76,12 @@ public enum OpenIddictServerEndpointType
/// </summary>
BackchannelAuthentication = 12,
/// <summary>
/// Dynamic client registration endpoint (RFC 7591), also used as the
/// client configuration endpoint (RFC 7592) when a client_id is specified.
/// </summary>
Registration = 13,
/// <summary>
/// Check session iframe endpoint (OpenID Connect Session Management 1.0).
/// </summary>

5
src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs

@ -131,6 +131,11 @@ public static partial class OpenIddictServerEvents
/// </summary>
public Uri? PushedAuthorizationEndpoint { get; set; }
/// <summary>
/// Gets or sets the dynamic client registration endpoint URI.
/// </summary>
public Uri? RegistrationEndpoint { get; set; }
/// <summary>
/// Gets or sets the revocation endpoint URI.
/// </summary>

240
src/OpenIddict.Server/OpenIddictServerEvents.Registration.cs

@ -0,0 +1,240 @@
/*
* 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.Security.Claims;
using System.Text.Json;
namespace OpenIddict.Server;
public static partial class OpenIddictServerEvents
{
/// <summary>
/// Resolves the type of a registration operation from the HTTP method used by the client (RFC 7591 and RFC 7592).
/// </summary>
internal static OpenIddictServerRegistrationRequestType GetRegistrationRequestType(string? method) => method switch
{
_ when string.Equals(method, "POST", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Registration,
_ when string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Read,
_ when string.Equals(method, "PUT", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Update,
_ when string.Equals(method, "DELETE", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Deletion,
_ => OpenIddictServerRegistrationRequestType.Unknown
};
/// <summary>
/// Represents an event called for each request to the registration endpoint to give the user code
/// a chance to manually extract the registration request from the ambient HTTP context.
/// </summary>
public sealed class ExtractRegistrationRequestContext : BaseValidatingContext
{
/// <summary>
/// Creates a new instance of the <see cref="ExtractRegistrationRequestContext"/> class.
/// </summary>
public ExtractRegistrationRequestContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request, or <see langword="null"/> if it wasn't extracted yet.
/// </summary>
public OpenIddictRequest? Request
{
get => Transaction.Request;
set => Transaction.Request = value;
}
/// <summary>
/// Gets the type of the registration operation, resolved from the HTTP method.
/// </summary>
public OpenIddictServerRegistrationRequestType RequestType
=> GetRegistrationRequestType(Transaction.RequestMethod);
}
/// <summary>
/// Represents an event called for each request to the registration endpoint to determine if the request
/// is valid and should continue to be processed. Custom handlers can be used to enforce additional
/// registration policies (e.g to approve or reject a registration based on the client metadata).
/// </summary>
public sealed class ValidateRegistrationRequestContext : BaseValidatingContext
{
/// <summary>
/// Creates a new instance of the <see cref="ValidateRegistrationRequestContext"/> class.
/// </summary>
public ValidateRegistrationRequestContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
/// <summary>
/// Gets the type of the registration operation, resolved from the HTTP method.
/// </summary>
public OpenIddictServerRegistrationRequestType RequestType
=> GetRegistrationRequestType(Transaction.RequestMethod);
/// <summary>
/// Gets the client identifier targeted by the client configuration endpoint (RFC 7592), if applicable.
/// </summary>
public string? ClientId => RequestType is OpenIddictServerRegistrationRequestType.Registration
? null : Transaction.Request?.ClientId;
/// <summary>
/// Gets or sets the security principal extracted from the initial access token, if applicable.
/// </summary>
/// <remarks>
/// Note: custom handlers executed before the built-in handlers can set this property
/// to accept initial access tokens that are not issued by this authorization server.
/// </remarks>
public ClaimsPrincipal? InitialAccessTokenPrincipal { get; set; }
/// <summary>
/// Gets or sets the token entry representing the registration access token, if applicable.
/// </summary>
public object? RegistrationAccessToken { get; set; }
/// <summary>
/// Gets or sets the security principal extracted from the software statement, if applicable.
/// </summary>
public ClaimsPrincipal? SoftwareStatementPrincipal { get; set; }
/// <summary>
/// Gets or sets the application managed using the client configuration endpoint, if applicable.
/// </summary>
public object? Application { get; set; }
/// <summary>
/// Gets or sets the client authentication method resolved from the client metadata.
/// </summary>
public string? TokenEndpointAuthenticationMethod { get; set; }
/// <summary>
/// Gets the grant types resolved from the client metadata.
/// </summary>
public HashSet<string> GrantTypes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets the response types resolved from the client metadata.
/// </summary>
public HashSet<string> ResponseTypes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets the scopes resolved from the client metadata.
/// </summary>
public HashSet<string> Scopes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets the client metadata accepted by the authorization server. Unrecognized
/// metadata are ignored, as required by RFC 7591, section 2, and not included.
/// </summary>
public Dictionary<string, JsonElement> Metadata { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the descriptor representing the client application that will be created or updated.
/// Custom handlers executed after the built-in handlers can inspect or amend it (e.g to restrict
/// the permissions granted to the client application) or reject the request.
/// </summary>
public OpenIddictApplicationDescriptor Descriptor { get; set; } = new();
}
/// <summary>
/// Represents an event called for each validated registration request
/// to allow the user code to decide how the request should be handled.
/// </summary>
public sealed class HandleRegistrationRequestContext : BaseValidatingContext
{
/// <summary>
/// Creates a new instance of the <see cref="HandleRegistrationRequestContext"/> class.
/// </summary>
public HandleRegistrationRequestContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
/// <summary>
/// Gets the type of the registration operation, resolved from the HTTP method.
/// </summary>
public OpenIddictServerRegistrationRequestType RequestType
=> GetRegistrationRequestType(Transaction.RequestMethod);
/// <summary>
/// Gets or sets the application read, updated or deleted by this request, if applicable.
/// </summary>
public object? Application { get; set; }
/// <summary>
/// Gets or sets the descriptor representing the client application that will be created or updated.
/// </summary>
public OpenIddictApplicationDescriptor Descriptor { get; set; } = new();
/// <summary>
/// Gets the additional parameters returned to the client application.
/// </summary>
public Dictionary<string, OpenIddictParameter> Parameters { get; } = new(StringComparer.Ordinal);
}
/// <summary>
/// Represents an event called before the registration response is returned to the caller.
/// </summary>
public sealed class ApplyRegistrationResponseContext : BaseRequestContext
{
/// <summary>
/// Creates a new instance of the <see cref="ApplyRegistrationResponseContext"/> class.
/// </summary>
public ApplyRegistrationResponseContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request, or <see langword="null"/> if it couldn't be extracted.
/// </summary>
public OpenIddictRequest? Request
{
get => Transaction.Request;
set => Transaction.Request = value;
}
/// <summary>
/// Gets or sets the response.
/// </summary>
public OpenIddictResponse Response
{
get => Transaction.Response!;
set => Transaction.Response = value;
}
/// <summary>
/// Gets the type of the registration operation, resolved from the HTTP method.
/// </summary>
public OpenIddictServerRegistrationRequestType RequestType
=> GetRegistrationRequestType(Transaction.RequestMethod);
/// <summary>
/// Gets the error code returned to the client application.
/// When the response indicates a successful response,
/// this property returns <see langword="null"/>.
/// </summary>
public string? Error => Response.Error;
}
}

1
src/OpenIddict.Server/OpenIddictServerExtensions.cs

@ -58,6 +58,7 @@ public static class OpenIddictServerExtensions
builder.Services.TryAddSingleton<RequireAuthenticationRequestIdGenerated>();
builder.Services.TryAddSingleton<RequireAuthenticationRequestIdValidated>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationRequest>();
builder.Services.TryAddSingleton<RequireRegistrationRequest>();
builder.Services.TryAddSingleton<RequireDeviceAuthorizationRequest>();
builder.Services.TryAddSingleton<RequireDPoPSupportEnabled>();
builder.Services.TryAddSingleton<RequireJsonWebTokenIntrospectionResponseRequested>();

14
src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs

@ -291,6 +291,20 @@ public static class OpenIddictServerHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the request is not a registration request.
/// </summary>
public sealed class RequireRegistrationRequest : IOpenIddictServerHandlerFilter<BaseContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(BaseContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.EndpointType is OpenIddictServerEndpointType.Registration);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the request is not a device request.
/// </summary>

5
src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs

@ -238,6 +238,7 @@ public static partial class OpenIddictServerHandlers
[Metadata.UserInfoEndpoint] = notification.UserInfoEndpoint?.AbsoluteUri,
[Metadata.DeviceAuthorizationEndpoint] = notification.DeviceAuthorizationEndpoint?.AbsoluteUri,
[Metadata.PushedAuthorizationRequestEndpoint] = notification.PushedAuthorizationEndpoint?.AbsoluteUri,
[Metadata.RegistrationEndpoint] = notification.RegistrationEndpoint?.AbsoluteUri,
[Metadata.BackchannelAuthenticationEndpoint] = notification.BackchannelAuthenticationEndpoint?.AbsoluteUri,
[Metadata.BackchannelTokenDeliveryModesSupported] = notification.BackchannelTokenDeliveryModes.ToImmutableArray<string?>(),
[Metadata.BackchannelUserCodeParameterSupported] = notification.BackchannelAuthenticationEndpoint is not null ? false : null,
@ -452,6 +453,10 @@ public static partial class OpenIddictServerHandlers
context.PushedAuthorizationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.PushedAuthorizationEndpointUris.FirstOrDefault());
// See https://datatracker.ietf.org/doc/html/rfc8414#section-2 for more information.
context.RegistrationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.RegistrationEndpointUris.FirstOrDefault());
context.RevocationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.RevocationEndpointUris.FirstOrDefault());

1679
src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs

File diff suppressed because it is too large

35
src/OpenIddict.Server/OpenIddictServerHandlers.cs

@ -141,6 +141,7 @@ public static partial class OpenIddictServerHandlers
.. Introspection.DefaultHandlers,
.. Logout.DefaultHandlers,
.. Protection.DefaultHandlers,
.. Registration.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. Session.DefaultHandlers,
.. UserInfo.DefaultHandlers
@ -182,6 +183,7 @@ public static partial class OpenIddictServerHandlers
Matches(context.Options.IntrospectionEndpointUris) ? OpenIddictServerEndpointType.Introspection :
Matches(context.Options.JsonWebKeySetEndpointUris) ? OpenIddictServerEndpointType.JsonWebKeySet :
Matches(context.Options.PushedAuthorizationEndpointUris) ? OpenIddictServerEndpointType.PushedAuthorization :
Matches(context.Options.RegistrationEndpointUris) ? OpenIddictServerEndpointType.Registration :
Matches(context.Options.RevocationEndpointUris) ? OpenIddictServerEndpointType.Revocation :
Matches(context.Options.TokenEndpointUris) ? OpenIddictServerEndpointType.Token :
Matches(context.Options.UserInfoEndpointUris) ? OpenIddictServerEndpointType.UserInfo :
@ -265,7 +267,8 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Revocation or OpenIddictServerEndpointType.Token or
OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.BackchannelAuthentication
OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.Registration
=> default,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0002)),
@ -301,6 +304,12 @@ public static partial class OpenIddictServerHandlers
// The userinfo endpoint requires sending a valid access token.
OpenIddictServerEndpointType.UserInfo => (true, true, true, true),
// Client registration requests (RFC 7591) can include an initial access token. When present, it
// is always validated but whether it is required is determined by the registration endpoint itself.
OpenIddictServerEndpointType.Registration when string.Equals(
context.Transaction.RequestMethod, "POST", StringComparison.OrdinalIgnoreCase)
=> (true, false, true, true),
_ => (false, false, false, false)
};
@ -477,7 +486,8 @@ public static partial class OpenIddictServerHandlers
context.AccessToken = context.EndpointType switch
{
OpenIddictServerEndpointType.UserInfo when context.ExtractAccessToken
OpenIddictServerEndpointType.UserInfo or
OpenIddictServerEndpointType.Registration when context.ExtractAccessToken
=> context.Request.AccessToken,
_ => null
@ -971,6 +981,7 @@ public static partial class OpenIddictServerHandlers
// Don't validate the client identifier on endpoints that don't support client identification.
if (context.EndpointType is OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Registration or
OpenIddictServerEndpointType.UserInfo)
{
return;
@ -1087,6 +1098,7 @@ public static partial class OpenIddictServerHandlers
if (context.EndpointType is OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Registration or
OpenIddictServerEndpointType.UserInfo)
{
return;
@ -1194,6 +1206,7 @@ public static partial class OpenIddictServerHandlers
if (context.EndpointType is OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Registration or
OpenIddictServerEndpointType.UserInfo)
{
return;
@ -1253,6 +1266,7 @@ public static partial class OpenIddictServerHandlers
if (context.EndpointType is OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Registration or
OpenIddictServerEndpointType.UserInfo)
{
return;
@ -1800,8 +1814,11 @@ public static partial class OpenIddictServerHandlers
{
// Audience validation is deliberately disabled for the userinfo endpoint to allow any access token to
// be used even if the authorization server isn't explicitly listed as a valid audience in the token.
DisableAudienceValidation = context.EndpointType is OpenIddictServerEndpointType.UserInfo,
DisablePresenterValidation = context.EndpointType is OpenIddictServerEndpointType.UserInfo,
// Similarly, initial access tokens sent to the registration endpoint are not bound to a specific audience.
DisableAudienceValidation = context.EndpointType is OpenIddictServerEndpointType.UserInfo or
OpenIddictServerEndpointType.Registration,
DisablePresenterValidation = context.EndpointType is OpenIddictServerEndpointType.UserInfo or
OpenIddictServerEndpointType.Registration,
Token = context.AccessToken,
ValidTokenTypes = { TokenTypeIdentifiers.AccessToken }
};
@ -2766,6 +2783,7 @@ public static partial class OpenIddictServerHandlers
if (context.EndpointType is not (OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Registration or
OpenIddictServerEndpointType.Token or
OpenIddictServerEndpointType.UserInfo))
{
@ -2801,7 +2819,8 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Registration
=> Errors.AccessDenied,
OpenIddictServerEndpointType.Token => Errors.InvalidGrant,
@ -2815,7 +2834,8 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Registration
=> SR.GetResourceString(SR.ID2015),
OpenIddictServerEndpointType.Token => SR.GetResourceString(SR.ID2024),
@ -2829,7 +2849,8 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Registration
=> SR.FormatID8000(SR.ID2015),
OpenIddictServerEndpointType.Token => SR.FormatID8000(SR.ID2024),

52
src/OpenIddict.Server/OpenIddictServerOptions.cs

@ -105,6 +105,11 @@ public sealed class OpenIddictServerOptions
/// </summary>
public List<Uri> PushedAuthorizationEndpointUris { get; } = [];
/// <summary>
/// Gets the absolute and relative URIs associated to the dynamic client registration endpoint.
/// </summary>
public List<Uri> RegistrationEndpointUris { get; } = [];
/// <summary>
/// Gets the absolute and relative URIs associated to the revocation endpoint.
/// </summary>
@ -736,6 +741,53 @@ public sealed class OpenIddictServerOptions
/// </remarks>
public bool RequireDPoPNonces { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether OAuth 2.0 Dynamic Client Registration (RFC 7591) and
/// Dynamic Client Registration Management (RFC 7592) are enabled. When enabled, the registration
/// endpoint creates, reads, updates and deletes client applications using the application manager.
/// </summary>
/// <remarks>
/// Note: this option requires setting at least one registration endpoint URI.
/// </remarks>
public bool EnableDynamicClientRegistration { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether client registration requests that don't include an initial
/// access token are accepted. Setting this property to <see langword="true"/> enables open registration
/// and is NOT recommended unless additional policy handlers are registered to approve registrations.
/// </summary>
public bool AllowAnonymousClientRegistration { get; set; }
/// <summary>
/// Gets the scopes that initial access tokens must contain (at least one of them) to be accepted
/// by the registration endpoint. Initial access tokens are access tokens issued by this server.
/// </summary>
public HashSet<string> InitialAccessTokenScopes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the period of time registration access tokens (RFC 7592) remain valid after being issued.
/// By default, registration access tokens don't expire and remain valid until the client is deleted.
/// </summary>
public TimeSpan? RegistrationAccessTokenLifetime { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether client registration requests must include a software statement.
/// </summary>
public bool RequireSoftwareStatement { get; set; }
/// <summary>
/// Gets the issuers whose software statements are accepted by the registration endpoint.
/// If no issuer is added, any issuer is accepted, as long as the software statement
/// is signed by one of the keys listed in <see cref="SoftwareStatementSigningKeys"/>.
/// </summary>
public HashSet<string> SoftwareStatementIssuers { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets the keys trusted to sign the software statements sent to the registration endpoint.
/// If no key is added, software statements are always rejected as unapproved.
/// </summary>
public List<SecurityKey> SoftwareStatementSigningKeys { get; } = [];
/// <summary>
/// Gets or sets the maximum difference allowed between the issuance date of a DPoP proof and the current date.
/// </summary>

38
src/OpenIddict.Server/OpenIddictServerRegistrationRequestType.cs

@ -0,0 +1,38 @@
/*
* 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.Server;
/// <summary>
/// Represents the type of an operation performed using the dynamic client registration endpoint.
/// </summary>
public enum OpenIddictServerRegistrationRequestType
{
/// <summary>
/// Unknown operation (e.g unsupported HTTP method).
/// </summary>
Unknown = 0,
/// <summary>
/// Client registration request (RFC 7591, HTTP POST).
/// </summary>
Registration = 1,
/// <summary>
/// Client read request (RFC 7592, HTTP GET).
/// </summary>
Read = 2,
/// <summary>
/// Client update request (RFC 7592, HTTP PUT).
/// </summary>
Update = 3,
/// <summary>
/// Client delete request (RFC 7592, HTTP DELETE).
/// </summary>
Deletion = 4
}

59
test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs

@ -192,11 +192,70 @@ public class OpenIddictServerIntegrationTestClient : IAsyncDisposable
}
ResponseMediaType = response.Content.Headers.ContentType?.MediaType;
ResponseStatusCode = response.StatusCode;
ResponseToken = null;
return await GetResponseAsync(response);
}
/// <summary>
/// Sends a request whose payload is represented as a JSON object (e.g a dynamic client registration request)
/// and converts the returned response to an OpenID Connect response.
/// </summary>
/// <param name="method">The HTTP method used to send the request.</param>
/// <param name="uri">The endpoint to which the request is sent.</param>
/// <param name="payload">The JSON payload, if applicable.</param>
/// <param name="token">The bearer token attached to the Authorization header, if applicable.</param>
/// <returns>The OpenID Connect response returned by the server.</returns>
public virtual async Task<OpenIddictResponse> SendJsonAsync(HttpMethod method, string uri, string? payload, string? token = null)
{
ArgumentNullException.ThrowIfNull(method);
ArgumentException.ThrowIfNullOrEmpty(uri);
var address = new Uri(uri, UriKind.RelativeOrAbsolute);
if (!address.IsAbsoluteUri)
{
address = new Uri(HttpClient.BaseAddress!, address);
}
using var message = new HttpRequestMessage(method, address);
if (payload is not null)
{
message.Content = new StringContent(payload, Encoding.UTF8, "application/json");
}
if (!string.IsNullOrEmpty(token))
{
message.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
}
foreach (var header in RequestHeaders)
{
message.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
using var response = await HttpClient.SendAsync(message);
ResponseHeaders.Clear();
foreach (var header in response.Headers)
{
ResponseHeaders[header.Key] = [.. header.Value];
}
ResponseMediaType = response.Content.Headers.ContentType?.MediaType;
ResponseStatusCode = response.StatusCode;
ResponseToken = null;
return await GetResponseAsync(response);
}
/// <summary>
/// Gets the HTTP status code of the last response received by this client, if available.
/// </summary>
public System.Net.HttpStatusCode? ResponseStatusCode { get; private set; }
/// <summary>
/// Gets the additional headers attached to all the requests sent by this client.
/// </summary>

197
test/OpenIddict.Server.Tests/OpenIddictServerRegistrationTests.cs

@ -0,0 +1,197 @@
/*
* 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.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Xunit;
namespace OpenIddict.Server.Tests;
public class OpenIddictServerRegistrationTests
{
[Fact]
public void SetRegistrationEndpointUris_AddsUris()
{
// Arrange
var services = new ServiceCollection().AddOptions();
var builder = new OpenIddictServerBuilder(services);
// Act
builder.SetRegistrationEndpointUris("http://localhost/connect/register");
// Assert
Assert.Contains(new Uri("http://localhost/connect/register"), GetOptions(services).RegistrationEndpointUris);
}
[Fact]
public void SetRegistrationEndpointUris_ThrowsAnExceptionForUriStartingWithTilde()
{
// Arrange
var builder = new OpenIddictServerBuilder(new ServiceCollection());
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => builder.SetRegistrationEndpointUris("~/connect/register"));
Assert.Equal("uris", exception.ParamName);
}
[Fact]
public void RegistrationMethods_UpdateTheOptions()
{
// Arrange
var services = new ServiceCollection().AddOptions();
var builder = new OpenIddictServerBuilder(services);
var key = new RsaSecurityKey(RSA.Create(2048));
// Act
builder.EnableDynamicClientRegistration()
.AllowAnonymousClientRegistration()
.SetInitialAccessTokenScopes("dcr")
.SetRegistrationAccessTokenLifetime(TimeSpan.FromDays(1))
.RequireSoftwareStatement()
.AddSoftwareStatementSigningKey(key, "https://issuer.example.com/");
var options = GetOptions(services);
// Assert
Assert.True(options.EnableDynamicClientRegistration);
Assert.True(options.AllowAnonymousClientRegistration);
Assert.Equal(["dcr"], options.InitialAccessTokenScopes);
Assert.Equal(TimeSpan.FromDays(1), options.RegistrationAccessTokenLifetime);
Assert.True(options.RequireSoftwareStatement);
Assert.Same(key, Assert.Single(options.SoftwareStatementSigningKeys));
Assert.Equal(["https://issuer.example.com/"], options.SoftwareStatementIssuers);
}
[Fact]
public void SetInitialAccessTokenScopes_ThrowsAnExceptionForEmptyScope()
{
// Arrange
var builder = new OpenIddictServerBuilder(new ServiceCollection());
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => builder.SetInitialAccessTokenScopes(string.Empty));
Assert.Equal("scopes", exception.ParamName);
}
[Fact]
public void AddSoftwareStatementSigningKey_ThrowsAnExceptionForNullKey()
{
// Arrange
var builder = new OpenIddictServerBuilder(new ServiceCollection());
// Act and assert
var exception = Assert.Throws<ArgumentNullException>(() => builder.AddSoftwareStatementSigningKey(null!));
Assert.Equal("key", exception.ParamName);
}
[Fact]
public void Validate_ReturnsAnErrorWhenRegistrationEndpointIsMissing()
{
// Arrange
var options = CreateBaseOptions();
options.EnableDynamicClientRegistration = true;
// Act
var result = Validate(options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0800), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenDynamicClientRegistrationIsDisabled()
{
// Arrange
var options = CreateBaseOptions();
options.RegistrationEndpointUris.Add(new Uri("connect/register", UriKind.Relative));
// Act
var result = Validate(options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0801), result.Failures!, StringComparer.Ordinal);
}
[Theory]
[InlineData(true, false)]
[InlineData(false, true)]
public void Validate_ReturnsAnErrorWhenIncompatibleSettingsAreUsed(bool degraded, bool storage)
{
// Arrange
var options = CreateRegistrationOptions();
options.EnableDegradedMode = degraded;
options.DisableTokenStorage = storage;
// Act
var result = Validate(options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0802), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenNoInitialAccessTokenScopeIsConfigured()
{
// Arrange
var options = CreateRegistrationOptions();
options.InitialAccessTokenScopes.Clear();
// Act
var result = Validate(options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0803), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_DoesNotRequireInitialAccessTokenScopesForAnonymousRegistration()
{
// Arrange
var options = CreateRegistrationOptions();
options.InitialAccessTokenScopes.Clear();
options.AllowAnonymousClientRegistration = true;
// Act
var result = Validate(options);
// Assert
Assert.DoesNotContain(SR.GetResourceString(SR.ID0803), result.Failures ?? [], StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenSoftwareStatementsAreRequiredWithoutSigningKeys()
{
// Arrange
var options = CreateRegistrationOptions();
options.RequireSoftwareStatement = true;
// Act
var result = Validate(options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0804), result.Failures!, StringComparer.Ordinal);
}
private static OpenIddictServerOptions CreateBaseOptions() => new() { TimeProvider = TimeProvider.System };
private static OpenIddictServerOptions CreateRegistrationOptions()
{
var options = CreateBaseOptions();
options.EnableDynamicClientRegistration = true;
options.RegistrationEndpointUris.Add(new Uri("connect/register", UriKind.Relative));
options.InitialAccessTokenScopes.Add("dcr");
return options;
}
private static ValidateOptionsResult Validate(OpenIddictServerOptions options)
=> new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()).Validate(name: null, options);
private static OpenIddictServerOptions GetOptions(IServiceCollection services)
=> services.BuildServiceProvider().GetRequiredService<IOptions<OpenIddictServerOptions>>().Value;
}
Loading…
Cancel
Save