diff --git a/src/OpenIddict.Abstractions/OpenIddictConstants.cs b/src/OpenIddict.Abstractions/OpenIddictConstants.cs index 4ae598f2..65b60500 100644 --- a/src/OpenIddict.Abstractions/OpenIddictConstants.cs +++ b/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"; diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index af9847f0..dcf8ecf1 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/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()'. + + The registration endpoint must be enabled when dynamic client registration is enabled. +To enable it, use 'services.AddOpenIddict().AddServer().SetRegistrationEndpointUris()'. + + + Dynamic client registration must be enabled when the registration endpoint is enabled. +To enable it, use 'services.AddOpenIddict().AddServer().EnableDynamicClientRegistration()'. + + + Dynamic client registration cannot be used when the degraded mode is enabled or when token storage is disabled. + + + 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()'. + + + At least one software statement signing key must be registered when software statements are required. +To register one, use 'services.AddOpenIddict().AddServer().AddSoftwareStatementSigningKey()'. + + + The registration request was not correctly extracted. +To extract registration requests, create a class implementing 'IOpenIddictServerHandler<ExtractRegistrationRequestContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'. + + + The registration response was not correctly applied. +To apply registration responses, create a class implementing 'IOpenIddictServerHandler<ApplyRegistrationResponseContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'. + + + The registration operation cannot be processed because the client application couldn't be resolved. + The security token is missing. @@ -2886,6 +2916,66 @@ Alternatively, enable the pass-through mode using 'EnableFrontchannelLogoutEndpo The sessions targeted by the logout request couldn't be terminated. + + The specified registration access token is invalid. + + + An initial access token is required to register a client application. + + + The specified initial access token doesn't contain a scope allowing the registration of client applications. + + + The '{0}' client metadata is invalid. + + + The '{0}' client metadata value '{1}' is not supported by this authorization server. + + + The '{0}' client metadata must only contain absolute URIs that don't include a fragment. + + + The '{0}' client metadata is required when using the '{1}' grant type. + + + The '{0}' response type cannot be used without the '{1}' grant type. + + + The '{0}' and '{1}' client metadata cannot be used together. + + + The specified software statement is invalid. + + + The specified software statement was not issued or signed by a trusted party. + + + A software statement is required to register a client application. + + + The '{0}' client metadata cannot be specified when updating a client registration. + + + The '{0}' client metadata doesn't match the client identifier of the client configuration endpoint. + + + The client application is not allowed to manage its registration. + + + The specified client secret doesn't match the client secret of the client application. + + + The client metadata was rejected by the application manager. + + + The '{0}' client metadata is required when using the '{1}' client authentication method. + + + The JSON Web Key Set must only contain public asymmetric keys. + + + The request payload must be a valid JSON object. + The '{0}' parameter shouldn't be null or empty at this point. @@ -3924,6 +4014,36 @@ This may indicate that the hashed entry is corrupted or malformed. 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. + + The registration request was successfully extracted: {Request}. + + + The registration request was successfully validated. + + + The registration request was rejected because the '{Metadata}' client metadata was invalid. + + + The registration request was rejected because the registration access token was invalid. + + + The client application '{ClientId}' was successfully registered. + + + The client application '{ClientId}' was successfully updated. + + + The client application '{ClientId}' was successfully deleted. + + + The registration request was rejected because the software statement couldn't be validated. + + + The registration request was rejected by the application manager. + + + The response was successfully returned as an empty 204 response. + https://documentation.openiddict.com/errors/{0} diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs index b04544a9..544e7871 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs @@ -197,6 +197,11 @@ public sealed class OpenIddictConfiguration /// public HashSet ResponseTypesSupported { get; } = new(StringComparer.Ordinal); + /// + /// Gets or sets the URI of the dynamic client registration endpoint (RFC 7591). + /// + public Uri? RegistrationEndpoint { get; set; } + /// /// Gets or sets the URI of the revocation endpoint. /// diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs index 6e145930..c87d4496 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs @@ -84,6 +84,17 @@ public sealed class OpenIddictServerAspNetCoreBuilder public OpenIddictServerAspNetCoreBuilder EnableBackchannelAuthenticationEndpointPassthrough() => Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true); + /// + /// 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). + /// + /// The instance. + public OpenIddictServerAspNetCoreBuilder EnableRegistrationEndpointPassthrough() + => Configure(options => options.EnableRegistrationEndpointPassthrough = true); + /// /// 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. diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs index 2f07a38a..4a1f1961 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs @@ -45,6 +45,7 @@ public static class OpenIddictServerAspNetCoreExtensions builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); + builder.Services.TryAddSingleton(); // 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. diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs index 60c29795..4b4a17b6 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs @@ -182,7 +182,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler context.SubjectTokenPrincipal, - OpenIddictServerEndpointType.UserInfo => context.AccessTokenPrincipal, + OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.Registration + => context.AccessTokenPrincipal, _ => null }; diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs index af3aa1a1..2986beab 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs @@ -56,6 +56,26 @@ public static class OpenIddictServerAspNetCoreHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if the + /// pass-through mode was not enabled for the registration endpoint. + /// + public sealed class RequireRegistrationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter + { + private readonly IOptionsMonitor _options; + + public RequireRegistrationEndpointPassthroughEnabled(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(_options.CurrentValue.EnableRegistrationEndpointPassthrough); + } + } + /// /// Represents a filter that excludes the associated handlers if the /// pass-through mode was not enabled for the end session endpoint. diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Registration.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Registration.cs new file mode 100644 index 00000000..505accad --- /dev/null +++ b/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 DefaultHandlers { get; } = + [ + /* + * Registration request extraction: + */ + ExtractRegistrationRequest.Descriptor, + ExtractAccessToken.Descriptor, + + /* + * Registration request handling: + */ + EnablePassthroughMode.Descriptor, + + /* + * Registration response processing: + */ + AttachHttpResponseCode.Descriptor, + AttachCacheControlHeader.Descriptor, + AttachWwwAuthenticateHeader.Descriptor, + ProcessChallengeErrorResponse.Descriptor, + ProcessNoContentResponse.Descriptor, + ProcessJsonResponse.Descriptor + ]; + + /// + /// 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. + /// + public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ExtractPostRequest.Descriptor.Order) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + 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; + } + } + + /// + /// 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. + /// + public sealed class ProcessNoContentResponse : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ProcessJsonResponse.Descriptor.Order - 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + 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; + } + } + + /// + /// Merges the query string parameters with the parameters extracted from the JSON payload. + /// + 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; + } + } +} diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs index e0517932..6367c642 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs +++ b/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. diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs index 49e5745a..e9407a72 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs @@ -35,6 +35,14 @@ public sealed class OpenIddictServerAspNetCoreOptions /// public bool EnableBackchannelAuthenticationEndpointPassthrough { get; set; } + /// + /// 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). + /// + public bool EnableRegistrationEndpointPassthrough { get; set; } + /// /// 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. diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs index 69552493..f9f28cee 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs @@ -84,6 +84,17 @@ public sealed class OpenIddictServerOwinBuilder public OpenIddictServerOwinBuilder EnableBackchannelAuthenticationEndpointPassthrough() => Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true); + /// + /// 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). + /// + /// The instance. + public OpenIddictServerOwinBuilder EnableRegistrationEndpointPassthrough() + => Configure(options => options.EnableRegistrationEndpointPassthrough = true); + /// /// 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. diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs index c989161f..8a73cb6d 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs @@ -47,6 +47,7 @@ public static class OpenIddictServerOwinExtensions builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); + builder.Services.TryAddSingleton(); // 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. diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs index bc916484..8681ecdb 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs @@ -195,7 +195,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler context.SubjectTokenPrincipal, - OpenIddictServerEndpointType.UserInfo => context.AccessTokenPrincipal, + OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.Registration + => context.AccessTokenPrincipal, _ => null }; diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs index ad3a0b7a..f4f45bf7 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs @@ -54,6 +54,26 @@ public static class OpenIddictServerOwinHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if the + /// pass-through mode was not enabled for the registration endpoint. + /// + public sealed class RequireRegistrationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter + { + private readonly IOptionsMonitor _options; + + public RequireRegistrationEndpointPassthroughEnabled(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(_options.CurrentValue.EnableRegistrationEndpointPassthrough); + } + } + /// /// Represents a filter that excludes the associated handlers if the /// pass-through mode was not enabled for the end session endpoint. diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Registration.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Registration.cs new file mode 100644 index 00000000..e62b6e7c --- /dev/null +++ b/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 DefaultHandlers { get; } = + [ + /* + * Registration request extraction: + */ + ExtractRegistrationRequest.Descriptor, + ExtractAccessToken.Descriptor, + + /* + * Registration request handling: + */ + EnablePassthroughMode.Descriptor, + + /* + * Registration response processing: + */ + AttachHttpResponseCode.Descriptor, + AttachOwinResponseChallenge.Descriptor, + SuppressFormsAuthenticationRedirect.Descriptor, + AttachCacheControlHeader.Descriptor, + AttachWwwAuthenticateHeader.Descriptor, + ProcessChallengeErrorResponse.Descriptor, + ProcessNoContentResponse.Descriptor, + ProcessJsonResponse.Descriptor + ]; + + /// + /// 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. + /// + public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ExtractPostRequest.Descriptor.Order) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + 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; + } + } + + /// + /// 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. + /// + public sealed class ProcessNoContentResponse : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ProcessJsonResponse.Descriptor.Order - 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + 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; + } + } + } +} diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs index e095a2cd..2620e8fe 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs +++ b/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. diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs index bf62019f..0761743f 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs @@ -35,6 +35,14 @@ public sealed class OpenIddictServerOwinOptions /// public bool EnableBackchannelAuthenticationEndpointPassthrough { get; set; } + /// + /// 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). + /// + public bool EnableRegistrationEndpointPassthrough { get; set; } + /// /// 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. diff --git a/src/OpenIddict.Server/OpenIddictServerBuilder.cs b/src/OpenIddict.Server/OpenIddictServerBuilder.cs index efe82173..61abd26e 100644 --- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs +++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs @@ -1364,6 +1364,49 @@ public sealed class OpenIddictServerBuilder }); } + /// + /// 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. + /// + /// The URIs associated to the endpoint. + /// The instance. + public OpenIddictServerBuilder SetRegistrationEndpointUris( + [StringSyntax(StringSyntaxAttribute.Uri)] params string[] uris) + { + ArgumentNullException.ThrowIfNull(uris); + + return SetRegistrationEndpointUris([.. uris.Select(uri => new Uri(uri, UriKind.RelativeOrAbsolute))]); + } + + /// + /// 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. + /// + /// The URIs associated to the endpoint. + /// The instance. + 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); + }); + } + /// /// 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); + /// + /// 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 . + /// + /// + /// Note: the registration endpoint URI must be set using . + /// + /// The instance. + public OpenIddictServerBuilder EnableDynamicClientRegistration() + => Configure(options => options.EnableDynamicClientRegistration = true); + + /// + /// Allows client registration requests that don't include an initial access token (open registration). + /// + /// + /// Enabling open registration is NOT recommended unless custom handlers are used to approve registrations. + /// + /// The instance. + public OpenIddictServerBuilder AllowAnonymousClientRegistration() + => Configure(options => options.AllowAnonymousClientRegistration = true); + + /// + /// Sets the scopes initial access tokens must contain (at least one of them) to be accepted by the registration endpoint. + /// + /// The scopes. + /// The instance. + 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); + }); + } + + /// + /// Sets the registration access token lifetime. By default, registration access tokens never expire. + /// + /// The registration access token lifetime. + /// The instance. + public OpenIddictServerBuilder SetRegistrationAccessTokenLifetime(TimeSpan? lifetime) + => Configure(options => options.RegistrationAccessTokenLifetime = lifetime); + + /// + /// Configures OpenIddict to require a software statement in client registration requests. + /// + /// The instance. + public OpenIddictServerBuilder RequireSoftwareStatement() + => Configure(options => options.RequireSoftwareStatement = true); + + /// + /// Adds a key trusted to sign the software statements sent to the registration endpoint. + /// + /// The security key. + /// The issuers allowed to issue software statements, if applicable. + /// The instance. + 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); + }); + } + /// /// Configures OpenIddict to require a valid DPoP proof for all token requests. /// diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs index fb5c67dd..920465b2 100644 --- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs +++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs @@ -229,6 +229,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions 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) { diff --git a/src/OpenIddict.Server/OpenIddictServerEndpointType.cs b/src/OpenIddict.Server/OpenIddictServerEndpointType.cs index 24ded7d2..00349201 100644 --- a/src/OpenIddict.Server/OpenIddictServerEndpointType.cs +++ b/src/OpenIddict.Server/OpenIddictServerEndpointType.cs @@ -76,6 +76,12 @@ public enum OpenIddictServerEndpointType /// BackchannelAuthentication = 12, + /// + /// Dynamic client registration endpoint (RFC 7591), also used as the + /// client configuration endpoint (RFC 7592) when a client_id is specified. + /// + Registration = 13, + /// /// Check session iframe endpoint (OpenID Connect Session Management 1.0). /// diff --git a/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs index 2901fd5e..b7b8e73e 100644 --- a/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs +++ b/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs @@ -131,6 +131,11 @@ public static partial class OpenIddictServerEvents /// public Uri? PushedAuthorizationEndpoint { get; set; } + /// + /// Gets or sets the dynamic client registration endpoint URI. + /// + public Uri? RegistrationEndpoint { get; set; } + /// /// Gets or sets the revocation endpoint URI. /// diff --git a/src/OpenIddict.Server/OpenIddictServerEvents.Registration.cs b/src/OpenIddict.Server/OpenIddictServerEvents.Registration.cs new file mode 100644 index 00000000..8380fac0 --- /dev/null +++ b/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 +{ + /// + /// Resolves the type of a registration operation from the HTTP method used by the client (RFC 7591 and RFC 7592). + /// + 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 + }; + + /// + /// 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. + /// + public sealed class ExtractRegistrationRequestContext : BaseValidatingContext + { + /// + /// Creates a new instance of the class. + /// + public ExtractRegistrationRequestContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request, or if it wasn't extracted yet. + /// + public OpenIddictRequest? Request + { + get => Transaction.Request; + set => Transaction.Request = value; + } + + /// + /// Gets the type of the registration operation, resolved from the HTTP method. + /// + public OpenIddictServerRegistrationRequestType RequestType + => GetRegistrationRequestType(Transaction.RequestMethod); + } + + /// + /// 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). + /// + public sealed class ValidateRegistrationRequestContext : BaseValidatingContext + { + /// + /// Creates a new instance of the class. + /// + public ValidateRegistrationRequestContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request. + /// + public OpenIddictRequest Request + { + get => Transaction.Request!; + set => Transaction.Request = value; + } + + /// + /// Gets the type of the registration operation, resolved from the HTTP method. + /// + public OpenIddictServerRegistrationRequestType RequestType + => GetRegistrationRequestType(Transaction.RequestMethod); + + /// + /// Gets the client identifier targeted by the client configuration endpoint (RFC 7592), if applicable. + /// + public string? ClientId => RequestType is OpenIddictServerRegistrationRequestType.Registration + ? null : Transaction.Request?.ClientId; + + /// + /// Gets or sets the security principal extracted from the initial access token, if applicable. + /// + /// + /// 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. + /// + public ClaimsPrincipal? InitialAccessTokenPrincipal { get; set; } + + /// + /// Gets or sets the token entry representing the registration access token, if applicable. + /// + public object? RegistrationAccessToken { get; set; } + + /// + /// Gets or sets the security principal extracted from the software statement, if applicable. + /// + public ClaimsPrincipal? SoftwareStatementPrincipal { get; set; } + + /// + /// Gets or sets the application managed using the client configuration endpoint, if applicable. + /// + public object? Application { get; set; } + + /// + /// Gets or sets the client authentication method resolved from the client metadata. + /// + public string? TokenEndpointAuthenticationMethod { get; set; } + + /// + /// Gets the grant types resolved from the client metadata. + /// + public HashSet GrantTypes { get; } = new(StringComparer.Ordinal); + + /// + /// Gets the response types resolved from the client metadata. + /// + public HashSet ResponseTypes { get; } = new(StringComparer.Ordinal); + + /// + /// Gets the scopes resolved from the client metadata. + /// + public HashSet Scopes { get; } = new(StringComparer.Ordinal); + + /// + /// Gets the client metadata accepted by the authorization server. Unrecognized + /// metadata are ignored, as required by RFC 7591, section 2, and not included. + /// + public Dictionary Metadata { get; } = new(StringComparer.Ordinal); + + /// + /// 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. + /// + public OpenIddictApplicationDescriptor Descriptor { get; set; } = new(); + } + + /// + /// Represents an event called for each validated registration request + /// to allow the user code to decide how the request should be handled. + /// + public sealed class HandleRegistrationRequestContext : BaseValidatingContext + { + /// + /// Creates a new instance of the class. + /// + public HandleRegistrationRequestContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request. + /// + public OpenIddictRequest Request + { + get => Transaction.Request!; + set => Transaction.Request = value; + } + + /// + /// Gets the type of the registration operation, resolved from the HTTP method. + /// + public OpenIddictServerRegistrationRequestType RequestType + => GetRegistrationRequestType(Transaction.RequestMethod); + + /// + /// Gets or sets the application read, updated or deleted by this request, if applicable. + /// + public object? Application { get; set; } + + /// + /// Gets or sets the descriptor representing the client application that will be created or updated. + /// + public OpenIddictApplicationDescriptor Descriptor { get; set; } = new(); + + /// + /// Gets the additional parameters returned to the client application. + /// + public Dictionary Parameters { get; } = new(StringComparer.Ordinal); + } + + /// + /// Represents an event called before the registration response is returned to the caller. + /// + public sealed class ApplyRegistrationResponseContext : BaseRequestContext + { + /// + /// Creates a new instance of the class. + /// + public ApplyRegistrationResponseContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request, or if it couldn't be extracted. + /// + public OpenIddictRequest? Request + { + get => Transaction.Request; + set => Transaction.Request = value; + } + + /// + /// Gets or sets the response. + /// + public OpenIddictResponse Response + { + get => Transaction.Response!; + set => Transaction.Response = value; + } + + /// + /// Gets the type of the registration operation, resolved from the HTTP method. + /// + public OpenIddictServerRegistrationRequestType RequestType + => GetRegistrationRequestType(Transaction.RequestMethod); + + /// + /// Gets the error code returned to the client application. + /// When the response indicates a successful response, + /// this property returns . + /// + public string? Error => Response.Error; + } +} diff --git a/src/OpenIddict.Server/OpenIddictServerExtensions.cs b/src/OpenIddict.Server/OpenIddictServerExtensions.cs index 4f84430e..be9b11d0 100644 --- a/src/OpenIddict.Server/OpenIddictServerExtensions.cs +++ b/src/OpenIddict.Server/OpenIddictServerExtensions.cs @@ -58,6 +58,7 @@ public static class OpenIddictServerExtensions builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); + builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); diff --git a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs index 8049c436..6f34ae45 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs @@ -291,6 +291,20 @@ public static class OpenIddictServerHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if the request is not a registration request. + /// + public sealed class RequireRegistrationRequest : IOpenIddictServerHandlerFilter + { + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(context.EndpointType is OpenIddictServerEndpointType.Registration); + } + } + /// /// Represents a filter that excludes the associated handlers if the request is not a device request. /// diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs index 38ee4e59..700a018a 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs +++ b/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(), [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()); diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs new file mode 100644 index 00000000..4aca6299 --- /dev/null +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Registration.cs @@ -0,0 +1,1679 @@ +/* + * 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.Buffers.Text; +using System.Collections.Immutable; +using System.Globalization; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace OpenIddict.Server; + +public static partial class OpenIddictServerHandlers +{ + public static class Registration + { + public static ImmutableArray DefaultHandlers { get; } = + [ + /* + * Registration request top-level processing: + */ + ExtractRegistrationRequest.Descriptor, + ValidateRegistrationRequest.Descriptor, + HandleRegistrationRequest.Descriptor, + ApplyRegistrationResponse.Descriptor, + ApplyRegistrationResponse.Descriptor, + ApplyRegistrationResponse.Descriptor, + + /* + * Registration request validation: + */ + ValidateRequestType.Descriptor, + ValidateInitialAccessToken.Descriptor, + ValidateRegistrationAccessToken.Descriptor, + ValidateSoftwareStatement.Descriptor, + ValidateUpdatedMetadata.Descriptor, + ValidateClientMetadata.Descriptor, + ValidateScopes.Descriptor, + AttachApplicationDescriptor.Descriptor, + + /* + * Registration request handling: + */ + AttachApplication.Descriptor, + + /* + * Sign-in processing: + */ + ProcessRegistrationOperation.Descriptor + ]; + + /// + /// Contains the logic responsible for extracting registration requests and invoking the corresponding event handlers. + /// + public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ExtractRegistrationRequest(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(100_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new ExtractRegistrationRequestContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (notification.IsRejected) + { + context.Reject( + error: notification.Error ?? Errors.InvalidRequest, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + if (notification.Request is null) + { + throw new InvalidOperationException(SR.GetResourceString(SR.ID0805)); + } + + context.Logger.LogInformation(6600, SR.GetResourceString(SR.ID6600), notification.Request); + } + } + + /// + /// Contains the logic responsible for validating registration requests and invoking the corresponding event handlers. + /// + public sealed class ValidateRegistrationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ValidateRegistrationRequest(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ExtractRegistrationRequest.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new ValidateRegistrationRequestContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + // Store the context object in the transaction so it can be later retrieved by handlers + // that want to access the resolved descriptor without triggering a new validation. + context.Transaction.SetProperty(typeof(ValidateRegistrationRequestContext).FullName!, notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (notification.IsRejected) + { + context.Reject( + error: notification.Error ?? Errors.InvalidRequest, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + context.Logger.LogInformation(6601, SR.GetResourceString(SR.ID6601)); + } + } + + /// + /// Contains the logic responsible for handling registration requests and invoking the corresponding event handlers. + /// + public sealed class HandleRegistrationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public HandleRegistrationRequest(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ValidateRegistrationRequest.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new HandleRegistrationRequestContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + // Store the context object in the transaction so it can be later retrieved by the sign-in + // handlers (e.g when the pass-through mode is used and the request is approved later). + context.Transaction.SetProperty(typeof(HandleRegistrationRequestContext).FullName!, notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (notification.IsRejected) + { + context.Reject( + error: notification.Error ?? Errors.InvalidRequest, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + // Registration operations are persisted by a sign-in handler: this allows applications + // using the pass-through mode to approve registration requests by triggering a sign-in + // operation (with an empty principal) and reject them by triggering a challenge. + var @event = new ProcessSignInContext(context.Transaction) + { + Principal = new ClaimsPrincipal(new ClaimsIdentity()), + Response = new OpenIddictResponse() + }; + + await _dispatcher.DispatchAsync(@event); + + if (@event.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (@event.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (@event.IsRejected) + { + context.Reject( + error: @event.Error ?? Errors.InvalidClientMetadata, + description: @event.ErrorDescription, + uri: @event.ErrorUri); + return; + } + } + } + + /// + /// Contains the logic responsible for processing registration responses and invoking the corresponding event handlers. + /// + public sealed class ApplyRegistrationResponse : IOpenIddictServerHandler where TContext : BaseRequestContext + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ApplyRegistrationResponse(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler>() + .SetOrder(500_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(TContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new ApplyRegistrationResponseContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + throw new InvalidOperationException(SR.GetResourceString(SR.ID0806)); + } + } + + /// + /// Contains the logic responsible for rejecting registration requests using an unsupported + /// HTTP method or that don't specify the client identifier when required (RFC 7592). + /// + public sealed class ValidateRequestType : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(int.MinValue + 100_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is OpenIddictServerRegistrationRequestType.Unknown) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2084), + uri: SR.FormatID8000(SR.ID2084)); + + return ValueTask.CompletedTask; + } + + // Requests sent to the client configuration endpoint MUST identify the client. + // + // See https://datatracker.ietf.org/doc/html/rfc7592#section-2 for more information. + if (context.RequestType is not OpenIddictServerRegistrationRequestType.Registration && + string.IsNullOrEmpty(context.ClientId)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2029(Parameters.ClientId), + uri: SR.FormatID8000(SR.ID2029)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for validating the initial access token attached to registration requests. + /// + public sealed class ValidateInitialAccessToken : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ValidateInitialAccessToken(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateRequestType.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is not OpenIddictServerRegistrationRequestType.Registration) + { + return; + } + + // Note: custom handlers executed before this handler can attach a principal + // to accept initial access tokens that were not issued by this server. + if (context.InitialAccessTokenPrincipal is null && !string.IsNullOrEmpty(context.Request.AccessToken)) + { + var notification = new ProcessAuthenticationContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + // Store the context object in the transaction so it can be later retrieved by handlers + // that want to access the authentication result without triggering a new authentication flow. + context.Transaction.SetProperty(typeof(ProcessAuthenticationContext).FullName!, notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (notification.IsRejected) + { + context.Reject( + error: notification.Error ?? Errors.InvalidToken, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + context.InitialAccessTokenPrincipal = notification.AccessTokenPrincipal; + } + + // Unless open registration was explicitly enabled, an initial access token is required. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-3 for more information. + if (context.InitialAccessTokenPrincipal is null) + { + if (context.Options.AllowAnonymousClientRegistration) + { + return; + } + + context.Logger.LogInformation(6603, SR.GetResourceString(SR.ID6603)); + + context.Reject( + error: Errors.MissingToken, + description: SR.GetResourceString(SR.ID2401), + uri: SR.FormatID8000(SR.ID2401)); + + return; + } + + // Ensure the initial access token contains one of the dedicated scopes, if configured. + if (context.Options.InitialAccessTokenScopes.Count is > 0 && + !context.Options.InitialAccessTokenScopes.Any(context.InitialAccessTokenPrincipal.HasScope)) + { + context.Reject( + error: Errors.InsufficientScope, + description: SR.GetResourceString(SR.ID2402), + uri: SR.FormatID8000(SR.ID2402)); + + return; + } + } + } + + /// + /// Contains the logic responsible for validating the registration access token + /// attached to requests sent to the client configuration endpoint (RFC 7592). + /// + public sealed class ValidateRegistrationAccessToken : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateInitialAccessToken.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // Note: custom handlers executed before this handler can attach + // the application to use a different authentication mechanism. + if (context.RequestType is OpenIddictServerRegistrationRequestType.Registration || context.Application is not null) + { + return; + } + + if (string.IsNullOrEmpty(context.Request.AccessToken)) + { + context.Reject( + error: Errors.MissingToken, + description: SR.GetResourceString(SR.ID2000), + uri: SR.FormatID8000(SR.ID2000)); + + return; + } + + var tokens = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var applications = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + // Note: to prevent client identifiers from being enumerated, the same invalid_token error is + // returned whether the token is invalid or the client doesn't exist or was deleted. + // + // See https://datatracker.ietf.org/doc/html/rfc7592#section-2.1 for more information. + var token = await tokens.FindByReferenceIdAsync(context.Request.AccessToken, context.CancellationToken); + if (token is null || + !await tokens.HasTypeAsync(token, TokenTypeIdentifiers.Private.RegistrationAccessToken, context.CancellationToken) || + !await tokens.HasStatusAsync(token, Statuses.Valid, context.CancellationToken) || + await tokens.GetExpirationDateAsync(token, context.CancellationToken) is DateTimeOffset date && + date < context.Options.TimeProvider.GetUtcNow() || + await tokens.GetApplicationIdAsync(token, context.CancellationToken) is not { Length: > 0 } identifier || + await applications.FindByIdAsync(identifier, context.CancellationToken) is not object application || + !string.Equals(await applications.GetClientIdAsync(application, context.CancellationToken), context.ClientId, StringComparison.Ordinal)) + { + context.Logger.LogInformation(6603, SR.GetResourceString(SR.ID6603)); + + context.Reject( + error: Errors.InvalidToken, + description: SR.GetResourceString(SR.ID2400), + uri: SR.FormatID8000(SR.ID2400)); + + return; + } + + // Ensure the client application is still allowed to manage its registration. + if (!context.Options.IgnoreEndpointPermissions && + !await applications.HasPermissionAsync(application, Permissions.Endpoints.Registration, context.CancellationToken)) + { + context.Reject( + error: Errors.InsufficientAccess, + description: SR.GetResourceString(SR.ID2414), + uri: SR.FormatID8000(SR.ID2414)); + + return; + } + + context.Application = application; + context.RegistrationAccessToken = token; + } + } + + /// + /// Contains the logic responsible for validating the software statement attached to the client + /// metadata and merging the claims it contains with the other metadata (RFC 7591, section 2.3). + /// + public sealed class ValidateSoftwareStatement : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateRegistrationAccessToken.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is not (OpenIddictServerRegistrationRequestType.Registration or + OpenIddictServerRegistrationRequestType.Update)) + { + return; + } + + var statement = (string?) context.Request[ClientMetadata.SoftwareStatement]; + if (string.IsNullOrEmpty(statement)) + { + if (context.Options.RequireSoftwareStatement && context.SoftwareStatementPrincipal is null) + { + context.Reject( + error: Errors.InvalidSoftwareStatement, + description: SR.GetResourceString(SR.ID2411), + uri: SR.FormatID8000(SR.ID2411)); + } + + return; + } + + var handler = new JsonWebTokenHandler(); + if (!handler.CanReadToken(statement)) + { + Reject(Errors.InvalidSoftwareStatement, SR.ID2409); + return; + } + + // Note: custom handlers executed before this handler can attach a principal + // to accept software statements validated using a different mechanism. + if (context.SoftwareStatementPrincipal is null) + { + if (context.Options.SoftwareStatementSigningKeys.Count is 0) + { + Reject(Errors.UnapprovedSoftwareStatement, SR.ID2410); + return; + } + + var result = await handler.ValidateTokenAsync(statement, new TokenValidationParameters + { + IssuerSigningKeys = context.Options.SoftwareStatementSigningKeys, + RequireExpirationTime = false, + RequireSignedTokens = true, + TryAllIssuerSigningKeys = true, + ValidateAudience = false, + ValidateIssuer = context.Options.SoftwareStatementIssuers.Count is > 0, + ValidateIssuerSigningKey = false, + ValidateLifetime = true, + ValidIssuers = context.Options.SoftwareStatementIssuers + }); + + if (!result.IsValid) + { + context.Logger.LogInformation(6607, result.Exception, SR.GetResourceString(SR.ID6607)); + + // Software statements that are not signed by a trusted party or issued by a trusted issuer + // are rejected as unapproved. Other errors (e.g expired tokens) are reported as invalid. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2 for more information. + if (result.Exception is SecurityTokenSignatureKeyNotFoundException or + SecurityTokenInvalidSignatureException or + SecurityTokenInvalidIssuerException) + { + Reject(Errors.UnapprovedSoftwareStatement, SR.ID2410); + return; + } + + Reject(Errors.InvalidSoftwareStatement, SR.ID2409); + return; + } + + context.SoftwareStatementPrincipal = new ClaimsPrincipal(result.ClaimsIdentity); + } + + // Software statements MUST contain an issuer claim. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2.3 for more information. + var token = handler.ReadJsonWebToken(statement); + if (string.IsNullOrEmpty(token.Issuer)) + { + Reject(Errors.InvalidSoftwareStatement, SR.ID2409); + return; + } + + // Client metadata values conveyed in the software statement take precedence over the plain JSON values. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-3.1.1 for more information. + using var document = JsonDocument.Parse(Base64UrlEncoder.DecodeBytes(token.EncodedPayload)); + if (document.RootElement.ValueKind is not JsonValueKind.Object) + { + Reject(Errors.InvalidSoftwareStatement, SR.ID2409); + return; + } + + foreach (var property in document.RootElement.EnumerateObject()) + { + if (property.Name is Claims.Issuer or Claims.Audience or Claims.ExpiresAt or + Claims.IssuedAt or Claims.NotBefore or Claims.JwtId) + { + continue; + } + + context.Request.SetParameter(property.Name, new OpenIddictParameter(property.Value.Clone())); + } + + void Reject(string error, string identifier) => context.Reject( + error: error, + description: SR.GetResourceString(identifier), + uri: SR.FormatID8000(identifier)); + } + } + + /// + /// Contains the logic responsible for validating the metadata specific to client update requests (RFC 7592). + /// + public sealed class ValidateUpdatedMetadata : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateSoftwareStatement.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is not OpenIddictServerRegistrationRequestType.Update) + { + return; + } + + // The client MUST NOT include the registration_access_token, registration_client_uri, + // client_secret_expires_at or client_id_issued_at fields in update requests. + // + // See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information. + foreach (var name in (string[]) [ClientMetadata.RegistrationAccessToken, ClientMetadata.RegistrationClientUri, + ClientMetadata.ClientSecretExpiresAt, ClientMetadata.ClientIdIssuedAt]) + { + if (context.Request.HasParameter(name)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2412(name), + uri: SR.FormatID8000(SR.ID2412)); + + return; + } + } + + // If the client includes the client_secret field, it MUST match the currently issued client secret: + // clients MUST NOT be allowed to overwrite their existing client secret with their own chosen value. + if ((string?) context.Request[ClientMetadata.ClientSecret] is { Length: > 0 } secret && context.Application is not null) + { + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + if (!await manager.ValidateClientSecretAsync(context.Application, secret, context.CancellationToken)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2415), + uri: SR.FormatID8000(SR.ID2415)); + + return; + } + } + } + } + + /// + /// Contains the logic responsible for validating the client metadata sent by + /// the client application (RFC 7591, section 2 and OpenID Connect Dynamic Client + /// Registration 1.0, section 2) and resolving the metadata accepted by the server. + /// + public sealed class ValidateClientMetadata : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateUpdatedMetadata.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + private static readonly ImmutableHashSet BooleanMetadata = ImmutableHashSet.Create(StringComparer.Ordinal, + ClientMetadata.BackchannelLogoutSessionRequired, ClientMetadata.DPoPBoundAccessTokens, + ClientMetadata.FrontchannelLogoutSessionRequired, ClientMetadata.RequireAuthTime, + ClientMetadata.RequirePushedAuthorizationRequests, ClientMetadata.RequireSignedRequestObject, + ClientMetadata.TlsClientCertificateBoundAccessTokens); + + private static readonly ImmutableHashSet StringMetadata = ImmutableHashSet.Create(StringComparer.Ordinal, + ClientMetadata.IdTokenEncryptedResponseAlg, ClientMetadata.IdTokenEncryptedResponseEnc, + ClientMetadata.RequestObjectEncryptionAlg, ClientMetadata.RequestObjectEncryptionEnc, + ClientMetadata.RequestObjectSigningAlg, ClientMetadata.SoftwareId, ClientMetadata.SoftwareStatement, + ClientMetadata.SoftwareVersion, ClientMetadata.TlsClientAuthSanDns, ClientMetadata.TlsClientAuthSanEmail, + ClientMetadata.TlsClientAuthSanIp, ClientMetadata.TlsClientAuthSanUri, ClientMetadata.TlsClientAuthSubjectDn, + ClientMetadata.TokenEndpointAuthSigningAlg, ClientMetadata.UserinfoEncryptedResponseAlg, + ClientMetadata.UserinfoEncryptedResponseEnc, ClientMetadata.UserinfoSignedResponseAlg); + + private static readonly ImmutableHashSet WebUriMetadata = ImmutableHashSet.Create(StringComparer.Ordinal, + ClientMetadata.BackchannelLogoutUri, ClientMetadata.ClientUri, ClientMetadata.FrontchannelLogoutUri, + ClientMetadata.InitiateLoginUri, ClientMetadata.LogoUri, ClientMetadata.PolicyUri, + ClientMetadata.SectorIdentifierUri, ClientMetadata.TosUri); + + private static readonly ImmutableHashSet LocalizableMetadata = ImmutableHashSet.Create(StringComparer.Ordinal, + ClientMetadata.ClientName, ClientMetadata.ClientUri, ClientMetadata.LogoUri, + ClientMetadata.PolicyUri, ClientMetadata.TosUri); + + /// + public ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is not (OpenIddictServerRegistrationRequestType.Registration or + OpenIddictServerRegistrationRequestType.Update)) + { + return ValueTask.CompletedTask; + } + + foreach (var parameter in context.Request.GetParameters()) + { + // Note: the language tag of localized values (e.g client_name#fr) is ignored for validation purposes. + var index = parameter.Key.IndexOf('#'); + var name = index is > 0 ? parameter.Key[..index] : parameter.Key; + if (index is > 0 && !LocalizableMetadata.Contains(name)) + { + continue; + } + + var value = (JsonElement) parameter.Value; + + var valid = name switch + { + ClientMetadata.ClientName => value.ValueKind is JsonValueKind.String, + + ClientMetadata.Contacts or ClientMetadata.DefaultAcrValues => IsStringArray(value, static _ => true), + + ClientMetadata.RedirectUris or ClientMetadata.PostLogoutRedirectUris or ClientMetadata.RequestUris + => IsStringArray(value, IsCallbackUri), + + ClientMetadata.GrantTypes or ClientMetadata.ResponseTypes + => IsStringArray(value, static item => !string.IsNullOrEmpty(item)), + + ClientMetadata.Scope or ClientMetadata.TokenEndpointAuthMethod or ClientMetadata.ApplicationType or + ClientMetadata.SubjectType or ClientMetadata.IdTokenSignedResponseAlg + => value.ValueKind is JsonValueKind.String && !string.IsNullOrEmpty(value.GetString()), + + ClientMetadata.Jwks => value.ValueKind is JsonValueKind.Object, + ClientMetadata.JwksUri => value.ValueKind is JsonValueKind.String && IsWebUri(value.GetString()), + + ClientMetadata.DefaultMaxAge => value.ValueKind is JsonValueKind.Number && + value.TryGetInt64(out var age) && age >= 0, + + _ when BooleanMetadata.Contains(name) => value.ValueKind is JsonValueKind.True or JsonValueKind.False, + _ when StringMetadata.Contains(name) => value.ValueKind is JsonValueKind.String, + _ when WebUriMetadata.Contains(name) => value.ValueKind is JsonValueKind.String && IsWebUri(value.GetString()), + + // Unrecognized metadata MUST be ignored by the authorization server. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2 for more information. + _ => (bool?) null + }; + + if (valid is null) + { + continue; + } + + if (valid is false) + { + context.Logger.LogInformation(6602, SR.GetResourceString(SR.ID6602), parameter.Key); + + context.Reject( + error: name is ClientMetadata.RedirectUris ? Errors.InvalidRedirectUri : Errors.InvalidClientMetadata, + description: name is ClientMetadata.RedirectUris or ClientMetadata.PostLogoutRedirectUris or ClientMetadata.RequestUris + ? SR.FormatID2405(name) : SR.FormatID2403(parameter.Key), + uri: SR.FormatID8000(name is ClientMetadata.RedirectUris or ClientMetadata.PostLogoutRedirectUris or ClientMetadata.RequestUris + ? SR.ID2405 : SR.ID2403)); + + return ValueTask.CompletedTask; + } + + context.Metadata[parameter.Key] = value.Clone(); + } + + // Resolve the grant types, that default to authorization_code if not explicitly specified. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2 for more information. + context.GrantTypes.Clear(); + context.GrantTypes.UnionWith(context.Metadata.TryGetValue(ClientMetadata.GrantTypes, out var types) + ? types.EnumerateArray().Select(static type => type.GetString()!) + : [GrantTypes.AuthorizationCode]); + + foreach (var type in context.GrantTypes) + { + if (!context.Options.GrantTypes.Contains(type)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.GrantTypes, type), SR.ID2404); + return ValueTask.CompletedTask; + } + } + + // Resolve the response types, that default to code when the authorization code grant is used. + context.ResponseTypes.Clear(); + + if (context.Metadata.TryGetValue(ClientMetadata.ResponseTypes, out types)) + { + foreach (var type in types.EnumerateArray().Select(static type => type.GetString()!)) + { + // Note: response types are compared using their components and are + // normalized to use the representation used in the server options. + var components = type.Split(Separators.Space, StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.Ordinal); + var normalized = context.Options.ResponseTypes.FirstOrDefault(value => + value.Split(Separators.Space, StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.Ordinal).SetEquals(components)); + + if (string.IsNullOrEmpty(normalized)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.ResponseTypes, type), SR.ID2404); + return ValueTask.CompletedTask; + } + + // Ensure the response types are consistent with the grant types. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2.1 for more information. + if (components.Contains(ResponseTypes.Code) && !context.GrantTypes.Contains(GrantTypes.AuthorizationCode)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2407(type, GrantTypes.AuthorizationCode), SR.ID2407); + return ValueTask.CompletedTask; + } + + if ((components.Contains(ResponseTypes.Token) || components.Contains(ResponseTypes.IdToken)) && + !context.GrantTypes.Contains(GrantTypes.Implicit)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2407(type, GrantTypes.Implicit), SR.ID2407); + return ValueTask.CompletedTask; + } + + context.ResponseTypes.Add(normalized); + } + } + + else if (context.GrantTypes.Contains(GrantTypes.AuthorizationCode)) + { + if (!context.Options.ResponseTypes.Contains(ResponseTypes.Code)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.ResponseTypes, ResponseTypes.Code), SR.ID2404); + return ValueTask.CompletedTask; + } + + context.ResponseTypes.Add(ResponseTypes.Code); + } + + // Redirect URIs are required when using a redirect-based flow. + if ((context.GrantTypes.Contains(GrantTypes.AuthorizationCode) || context.GrantTypes.Contains(GrantTypes.Implicit)) && + (!context.Metadata.TryGetValue(ClientMetadata.RedirectUris, out var uris) || uris.GetArrayLength() is 0)) + { + Reject(Errors.InvalidRedirectUri, SR.FormatID2406(ClientMetadata.RedirectUris, + context.GrantTypes.Contains(GrantTypes.AuthorizationCode) ? GrantTypes.AuthorizationCode : GrantTypes.Implicit), SR.ID2406); + return ValueTask.CompletedTask; + } + + // Resolve the client authentication method, that defaults to client_secret_basic. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2 for more information. + context.TokenEndpointAuthenticationMethod = context.Metadata.TryGetValue(ClientMetadata.TokenEndpointAuthMethod, out var method) + ? method.GetString() + : ClientAuthenticationMethods.ClientSecretBasic; + + // Note: client_secret_jwt is not supported as client secrets are not stored in plain text. + if (context.TokenEndpointAuthenticationMethod is not ClientAuthenticationMethods.None && + (context.TokenEndpointAuthenticationMethod is ClientAuthenticationMethods.ClientSecretJwt || + !context.Options.ClientAuthenticationMethods.Contains(context.TokenEndpointAuthenticationMethod!))) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404( + ClientMetadata.TokenEndpointAuthMethod, context.TokenEndpointAuthenticationMethod), SR.ID2404); + return ValueTask.CompletedTask; + } + + // Public clients cannot use grants that require client authentication. + if (context.TokenEndpointAuthenticationMethod is ClientAuthenticationMethods.None && + context.GrantTypes.Contains(GrantTypes.ClientCredentials)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2408( + ClientMetadata.TokenEndpointAuthMethod, ClientMetadata.GrantTypes), SR.ID2408); + return ValueTask.CompletedTask; + } + + // JSON Web Key Sets can be sent by value or by reference, but not both. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-2 for more information. + if (context.Metadata.ContainsKey(ClientMetadata.Jwks) && context.Metadata.ContainsKey(ClientMetadata.JwksUri)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2408(ClientMetadata.Jwks, ClientMetadata.JwksUri), SR.ID2408); + return ValueTask.CompletedTask; + } + + // Note: remote JSON Web Key Sets are not supported, as the authorization server would have to retrieve + // them from an arbitrary location (which would expose it to server-side request forgery attacks). + if (context.Metadata.TryGetValue(ClientMetadata.JwksUri, out var location)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.JwksUri, location.GetString()), SR.ID2404); + return ValueTask.CompletedTask; + } + + if (context.Metadata.TryGetValue(ClientMetadata.Jwks, out var jwks)) + { + JsonWebKeySet set; + + try + { + set = new JsonWebKeySet(jwks.GetRawText()); + } + + catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2403(ClientMetadata.Jwks), SR.ID2403); + return ValueTask.CompletedTask; + } + + // Only public asymmetric keys can be registered: symmetric and private keys are always rejected. + if (set.Keys.Count is 0 || set.Keys.Any(static key => + string.Equals(key.Kty, JsonWebAlgorithmsKeyTypes.Octet, StringComparison.Ordinal) || + !string.IsNullOrEmpty(key.D) || !string.IsNullOrEmpty(key.K) || + !string.IsNullOrEmpty(key.P) || !string.IsNullOrEmpty(key.Q))) + { + Reject(Errors.InvalidClientMetadata, SR.GetResourceString(SR.ID2418), SR.ID2418); + return ValueTask.CompletedTask; + } + } + + // Client authentication methods based on asymmetric keys or certificates require a JSON Web Key Set. + if (context.TokenEndpointAuthenticationMethod is ClientAuthenticationMethods.PrivateKeyJwt or + ClientAuthenticationMethods.SelfSignedTlsClientAuth or + ClientAuthenticationMethods.TlsClientAuth && jwks.ValueKind is not JsonValueKind.Object) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2417( + ClientMetadata.Jwks, context.TokenEndpointAuthenticationMethod), SR.ID2417); + return ValueTask.CompletedTask; + } + + // Only the public subject type is supported. + if (context.Metadata.TryGetValue(ClientMetadata.SubjectType, out var subject) && + !string.Equals(subject.GetString(), SubjectTypes.Public, StringComparison.Ordinal)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.SubjectType, subject.GetString()), SR.ID2404); + return ValueTask.CompletedTask; + } + + if (context.Metadata.TryGetValue(ClientMetadata.ApplicationType, out var application) && + application.GetString() is not (ApplicationTypes.Native or ApplicationTypes.Web)) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.ApplicationType, application.GetString()), SR.ID2404); + return ValueTask.CompletedTask; + } + + // Ensure the identity token signing algorithm is supported by one of the registered signing credentials. + if (context.Metadata.TryGetValue(ClientMetadata.IdTokenSignedResponseAlg, out var algorithm) && + !context.Options.SigningCredentials.Any(credentials => + string.Equals(credentials.Algorithm, algorithm.GetString(), StringComparison.Ordinal))) + { + Reject(Errors.InvalidClientMetadata, SR.FormatID2404(ClientMetadata.IdTokenSignedResponseAlg, algorithm.GetString()), SR.ID2404); + return ValueTask.CompletedTask; + } + + // Resolve the scopes (the validation of the scopes themselves is performed by a separate handler). + context.Scopes.Clear(); + + if (context.Metadata.TryGetValue(ClientMetadata.Scope, out var scope)) + { + context.Scopes.UnionWith(scope.GetString()!.Split(Separators.Space, StringSplitOptions.RemoveEmptyEntries)); + } + + return ValueTask.CompletedTask; + + void Reject(string error, string description, string identifier) + { + context.Logger.LogInformation(6602, SR.GetResourceString(SR.ID6602), description); + + context.Reject(error: error, description: description, uri: SR.FormatID8000(identifier)); + } + + static bool IsStringArray(JsonElement element, Func predicate) + => element.ValueKind is JsonValueKind.Array && element.EnumerateArray().All(item => + item.ValueKind is JsonValueKind.String && predicate(item.GetString())); + + // Callback URIs MUST be absolute and MUST NOT include a fragment. + // + // See https://datatracker.ietf.org/doc/html/rfc6749#section-3.1.2 for more information. + static bool IsCallbackUri(string? value) + => Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) && + !OpenIddictHelpers.IsImplicitFileUri(uri) && string.IsNullOrEmpty(uri.Fragment); + + static bool IsWebUri(string? value) + => Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) && + (string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) || + string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)); + } + } + + /// + /// Contains the logic responsible for rejecting registration requests that specify unregistered scopes. + /// Note: this handler is not used when scope validation is disabled. + /// + public sealed class ValidateScopes : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ValidateClientMetadata.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.Scopes.Count is 0) + { + return; + } + + // If all the specified scopes are registered in the options, avoid making a database lookup. + var scopes = new HashSet(context.Scopes, StringComparer.Ordinal); + scopes.ExceptWith(context.Options.Scopes); + + if (scopes.Count is not 0 && !context.Options.EnableDegradedMode) + { + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + await foreach (var scope in manager.FindByNamesAsync([.. scopes], context.CancellationToken)) + { + var name = await manager.GetNameAsync(scope, context.CancellationToken); + if (!string.IsNullOrEmpty(name)) + { + scopes.Remove(name); + } + } + } + + if (scopes.Count is not 0) + { + context.Logger.LogInformation(6602, SR.GetResourceString(SR.ID6602), ClientMetadata.Scope); + + context.Reject( + error: Errors.InvalidClientMetadata, + description: SR.FormatID2404(ClientMetadata.Scope, string.Join(' ', scopes)), + uri: SR.FormatID8000(SR.ID2404)); + + return; + } + } + } + + /// + /// Contains the logic responsible for creating the application descriptor from the validated client metadata. + /// Custom handlers executed after this handler can amend the descriptor to enforce additional policies. + /// + public sealed class AttachApplicationDescriptor : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateScopes.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.RequestType is not (OpenIddictServerRegistrationRequestType.Registration or + OpenIddictServerRegistrationRequestType.Update)) + { + return ValueTask.CompletedTask; + } + + context.Descriptor = CreateDescriptor(context); + + return ValueTask.CompletedTask; + } + + internal static OpenIddictApplicationDescriptor CreateDescriptor(ValidateRegistrationRequestContext context) + { + var descriptor = new OpenIddictApplicationDescriptor + { + ClientType = context.TokenEndpointAuthenticationMethod is ClientAuthenticationMethods.None + ? ClientTypes.Public : ClientTypes.Confidential + }; + + var metadata = context.Metadata; + + if (metadata.TryGetValue(ClientMetadata.ApplicationType, out var kind)) + { + descriptor.ApplicationType = kind.GetString(); + } + + foreach (var (name, value) in metadata.Select(static item => (item.Key, item.Value))) + { + if (name is ClientMetadata.ClientName) + { + descriptor.DisplayName = value.GetString(); + } + + else if (name.StartsWith(ClientMetadata.ClientName + '#', StringComparison.Ordinal)) + { + try + { + descriptor.DisplayNames[CultureInfo.GetCultureInfo(name[(ClientMetadata.ClientName.Length + 1)..])] = value.GetString()!; + } + + catch (CultureNotFoundException) + { + // Ignore localized values whose language tag is not supported. + } + } + } + + if (metadata.TryGetValue(ClientMetadata.RedirectUris, out var uris)) + { + descriptor.RedirectUris.UnionWith(uris.EnumerateArray().Select(static uri => new Uri(uri.GetString()!, UriKind.Absolute))); + } + + if (metadata.TryGetValue(ClientMetadata.PostLogoutRedirectUris, out uris)) + { + descriptor.PostLogoutRedirectUris.UnionWith(uris.EnumerateArray().Select(static uri => new Uri(uri.GetString()!, UriKind.Absolute))); + } + + if (metadata.TryGetValue(ClientMetadata.Jwks, out var jwks)) + { + descriptor.JsonWebKeySet = new JsonWebKeySet(jwks.GetRawText()); + } + + // Generate a client secret for confidential clients using a secret-based authentication method. + if (context.TokenEndpointAuthenticationMethod is ClientAuthenticationMethods.ClientSecretBasic or + ClientAuthenticationMethods.ClientSecretPost) + { + descriptor.ClientSecret = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(count: 256 / 8)); + } + + // Derive the permissions from the grant types, response types and scopes. + descriptor.Permissions.Add(Permissions.Endpoints.Registration); + + foreach (var grant in context.GrantTypes) + { + descriptor.Permissions.Add(Permissions.Prefixes.GrantType + grant); + + switch (grant) + { + case GrantTypes.AuthorizationCode: + descriptor.Permissions.Add(Permissions.Endpoints.Authorization); + descriptor.Permissions.Add(Permissions.Endpoints.EndSession); + descriptor.Permissions.Add(Permissions.Endpoints.PushedAuthorization); + descriptor.Permissions.Add(Permissions.Endpoints.Token); + break; + + case GrantTypes.Implicit: + descriptor.Permissions.Add(Permissions.Endpoints.Authorization); + descriptor.Permissions.Add(Permissions.Endpoints.EndSession); + descriptor.Permissions.Add(Permissions.Endpoints.PushedAuthorization); + break; + + case GrantTypes.DeviceCode: + descriptor.Permissions.Add(Permissions.Endpoints.DeviceAuthorization); + descriptor.Permissions.Add(Permissions.Endpoints.Token); + break; + + case GrantTypes.Ciba: + descriptor.Permissions.Add(Permissions.Endpoints.BackchannelAuthentication); + descriptor.Permissions.Add(Permissions.Endpoints.Token); + break; + + default: + descriptor.Permissions.Add(Permissions.Endpoints.Token); + break; + } + } + + if (descriptor.Permissions.Contains(Permissions.Endpoints.Token)) + { + descriptor.Permissions.Add(Permissions.Endpoints.Revocation); + + if (descriptor.ClientType is ClientTypes.Confidential) + { + descriptor.Permissions.Add(Permissions.Endpoints.Introspection); + } + } + + foreach (var type in context.ResponseTypes) + { + descriptor.Permissions.Add(Permissions.Prefixes.ResponseType + type); + } + + foreach (var scope in context.Scopes) + { + // Note: the openid and offline_access scopes are protocol scopes that don't require permissions. + if (scope is not (Scopes.OpenId or Scopes.OfflineAccess)) + { + descriptor.Permissions.Add(Permissions.Prefixes.Scope + scope); + } + } + + // Map the features requested by the client application to requirements. + if (IsTrue(ClientMetadata.RequirePushedAuthorizationRequests)) + { + descriptor.Requirements.Add(Requirements.Features.PushedAuthorizationRequests); + } + + if (IsTrue(ClientMetadata.RequireSignedRequestObject)) + { + descriptor.Requirements.Add(Requirements.Features.SignedRequestObjects); + } + + if (IsTrue(ClientMetadata.DPoPBoundAccessTokens)) + { + descriptor.Requirements.Add(Requirements.Features.DPoP); + } + + // Store the logout and identity token settings. + if (metadata.TryGetValue(ClientMetadata.BackchannelLogoutUri, out var uri)) + { + descriptor.Settings[Settings.Logout.BackchannelLogoutUri] = uri.GetString()!; + descriptor.Settings[Settings.Logout.BackchannelLogoutSessionRequired] = + IsTrue(ClientMetadata.BackchannelLogoutSessionRequired) ? "true" : "false"; + } + + if (metadata.TryGetValue(ClientMetadata.FrontchannelLogoutUri, out uri)) + { + descriptor.Settings[Settings.Logout.FrontchannelLogoutUri] = uri.GetString()!; + descriptor.Settings[Settings.Logout.FrontchannelLogoutSessionRequired] = + IsTrue(ClientMetadata.FrontchannelLogoutSessionRequired) ? "true" : "false"; + } + + if (metadata.TryGetValue(ClientMetadata.IdTokenSignedResponseAlg, out var algorithm)) + { + descriptor.Settings[Settings.Registration.IdentityTokenSigningAlgorithm] = algorithm.GetString()!; + } + + // Store the accepted client metadata (including the default values applied by the server) so they can be + // returned by the client configuration endpoint. Note: the software statement itself is not stored, as its + // claims were merged with the other metadata. + // + // See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1 for more information. + var values = metadata + .Where(static item => item.Key is not ClientMetadata.SoftwareStatement) + .ToDictionary(static item => item.Key, static item => item.Value, StringComparer.Ordinal); + + values[ClientMetadata.GrantTypes] = CreateElement(writer => WriteStrings(writer, context.GrantTypes)); + values[ClientMetadata.ResponseTypes] = CreateElement(writer => WriteStrings(writer, context.ResponseTypes)); + values[ClientMetadata.TokenEndpointAuthMethod] = CreateElement(writer => + writer.WriteStringValue(context.TokenEndpointAuthenticationMethod)); + + descriptor.Properties[Properties.ClientMetadata] = SerializeMetadata(values); + + return descriptor; + + bool IsTrue(string name) => metadata.TryGetValue(name, out var value) && value.ValueKind is JsonValueKind.True; + } + } + + /// + /// Contains the logic responsible for attaching the application and descriptor resolved during the validation phase. + /// + public sealed class AttachApplication : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(int.MinValue + 100_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(HandleRegistrationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = context.Transaction.GetProperty( + typeof(ValidateRegistrationRequestContext).FullName!) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); + + context.Application ??= notification.Application; + context.Descriptor = notification.Descriptor; + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for creating, reading, updating or deleting the client application + /// and returning the corresponding client information response (RFC 7591, section 3.2.1 and RFC 7592, + /// section 3) when a sign-in operation is triggered for a registration request. + /// + public sealed class ProcessRegistrationOperation : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ProcessRegistrationOperation(IOpenIddictServerDispatcher dispatcher) + => _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + // Note: this handler is deliberately executed before the default sign-in handlers, + // that are not used for registration requests (as no token is issued in this case). + .SetOrder(int.MinValue + 50_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessSignInContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var validation = context.Transaction.GetProperty( + typeof(ValidateRegistrationRequestContext).FullName!) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); + + var notification = context.Transaction.GetProperty( + typeof(HandleRegistrationRequestContext).FullName!); + + var applications = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var tokens = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var application = notification?.Application ?? validation.Application; + var descriptor = notification?.Descriptor ?? validation.Descriptor; + + var response = new OpenIddictResponse(); + + try + { + switch (validation.RequestType) + { + case OpenIddictServerRegistrationRequestType.Registration: + { + var date = context.Options.TimeProvider.GetUtcNow(); + + // Generate a unique client identifier, unless one was explicitly set by a custom handler. + if (string.IsNullOrEmpty(descriptor.ClientId)) + { + descriptor.ClientId = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(count: 256 / 8)); + } + + var secret = descriptor.ClientSecret; + + descriptor.Properties[Properties.ClientMetadata] = AddIssuanceDate( + descriptor.Properties.TryGetValue(Properties.ClientMetadata, out var metadata) ? metadata : default, date); + + application = await applications.CreateAsync(descriptor, context.CancellationToken); + + await AttachResponseAsync(application, descriptor.ClientId, secret, descriptor.Properties[Properties.ClientMetadata]); + + context.Logger.LogInformation(6604, SR.GetResourceString(SR.ID6604), descriptor.ClientId); + break; + } + + case OpenIddictServerRegistrationRequestType.Read when application is not null: + { + var properties = await applications.GetPropertiesAsync(application, context.CancellationToken); + + await AttachResponseAsync(application, await applications.GetClientIdAsync(application, context.CancellationToken), + secret: null, properties is not null && properties.TryGetValue(Properties.ClientMetadata, out var metadata) ? metadata : default); + break; + } + + case OpenIddictServerRegistrationRequestType.Update when application is not null: + { + var existing = new OpenIddictApplicationDescriptor(); + await applications.PopulateAsync(existing, application, context.CancellationToken); + + // Note: the update operation uses full replace semantics, but the client identifier, + // the client issuance date and the consent type (not a client metadata) are preserved. + // + // See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information. + descriptor.ClientId = existing.ClientId; + descriptor.ConsentType ??= existing.ConsentType; + + descriptor.Properties[Properties.ClientMetadata] = AddIssuanceDate( + descriptor.Properties.TryGetValue(Properties.ClientMetadata, out var metadata) ? metadata : default, + GetIssuanceDate(existing) ?? context.Options.TimeProvider.GetUtcNow()); + + // Preserve the existing client secret (that is never returned, as it is not stored in plain + // text) when the client still uses a secret-based authentication method. A new secret is + // only generated (and returned) when the client didn't have a secret before the update. + string? secret = null; + + if (!string.IsNullOrEmpty(descriptor.ClientSecret)) + { + if (!string.IsNullOrEmpty(existing.ClientSecret)) + { + descriptor.ClientSecret = existing.ClientSecret; + } + + else + { + secret = descriptor.ClientSecret; + } + } + + await applications.UpdateAsync(application, descriptor, context.CancellationToken); + + await AttachResponseAsync(application, descriptor.ClientId, secret, descriptor.Properties[Properties.ClientMetadata]); + + context.Logger.LogInformation(6605, SR.GetResourceString(SR.ID6605), descriptor.ClientId); + break; + } + + case OpenIddictServerRegistrationRequestType.Deletion when application is not null: + { + var identifier = await applications.GetIdAsync(application, context.CancellationToken); + if (!string.IsNullOrEmpty(identifier)) + { + await tokens.RevokeByApplicationIdAsync(identifier, context.CancellationToken); + + if (context.ServiceProvider.GetService() is IOpenIddictAuthorizationManager authorizations) + { + await authorizations.RevokeByApplicationIdAsync(identifier, context.CancellationToken); + } + } + + var client = await applications.GetClientIdAsync(application, context.CancellationToken); + + await applications.DeleteAsync(application, context.CancellationToken); + + context.Logger.LogInformation(6606, SR.GetResourceString(SR.ID6606), client); + break; + } + + default: throw new InvalidOperationException(SR.GetResourceString(SR.ID0807)); + } + } + + catch (OpenIddictExceptions.ValidationException exception) + { + context.Logger.LogInformation(6608, exception, SR.GetResourceString(SR.ID6608)); + + // Map errors affecting the redirect URIs to the dedicated invalid_redirect_uri error. + var redirect = exception.Results.Any(static result => result.ErrorMessage is string message && + (string.Equals(message, SR.GetResourceString(SR.ID2061), StringComparison.Ordinal) || + string.Equals(message, SR.GetResourceString(SR.ID2062), StringComparison.Ordinal) || + string.Equals(message, SR.GetResourceString(SR.ID2115), StringComparison.Ordinal) || + string.Equals(message, SR.FormatID2134(Parameters.Iss), StringComparison.Ordinal))); + + context.Reject( + error: redirect ? Errors.InvalidRedirectUri : Errors.InvalidClientMetadata, + description: SR.GetResourceString(SR.ID2416), + uri: SR.FormatID8000(SR.ID2416)); + + return; + } + + context.Transaction.Response = response; + + var @event = new ApplyRegistrationResponseContext(context.Transaction); + await _dispatcher.DispatchAsync(@event); + + if (@event.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (@event.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + throw new InvalidOperationException(SR.GetResourceString(SR.ID0806)); + + async ValueTask AttachResponseAsync(object application, string? client, string? secret, JsonElement metadata) + { + var identifier = await applications.GetIdAsync(application, context.CancellationToken); + + if (metadata.ValueKind is JsonValueKind.Object) + { + foreach (var property in metadata.EnumerateObject()) + { + response.SetParameter(property.Name, new OpenIddictParameter(property.Value.Clone())); + } + } + + response[ClientMetadata.ClientId] = client; + + if (!string.IsNullOrEmpty(secret)) + { + response[ClientMetadata.ClientSecret] = secret; + } + + // Note: client secrets issued by the registration endpoint never expire. + if ((string?) response[ClientMetadata.TokenEndpointAuthMethod] is ClientAuthenticationMethods.ClientSecretBasic or + ClientAuthenticationMethods.ClientSecretPost) + { + response[ClientMetadata.ClientSecretExpiresAt] = 0; + } + + // Revoke the registration access token used to authenticate the request and issue a new one: since + // registration access tokens are not stored in plain text, they can't be returned as-is and a new + // token is issued for each read or update operation (as allowed by RFC 7592, section 3). + if (validation.RegistrationAccessToken is not null) + { + await tokens.TryRevokeAsync(validation.RegistrationAccessToken, context.CancellationToken); + } + + var token = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(count: 256 / 8)); + var date = context.Options.TimeProvider.GetUtcNow(); + + await tokens.CreateAsync(new OpenIddictTokenDescriptor + { + ApplicationId = identifier, + CreationDate = date, + ExpirationDate = context.Options.RegistrationAccessTokenLifetime is TimeSpan lifetime ? date + lifetime : null, + ReferenceId = token, + Status = Statuses.Valid, + Type = TokenTypeIdentifiers.Private.RegistrationAccessToken + }, context.CancellationToken); + + response[ClientMetadata.RegistrationAccessToken] = token; + + // Note: the registration endpoint is also used as the client configuration endpoint. + if (OpenIddictHelpers.CreateAbsoluteUri(context.BaseUri, context.Options.RegistrationEndpointUris.FirstOrDefault()) is Uri uri) + { + response[ClientMetadata.RegistrationClientUri] = OpenIddictHelpers.AddQueryStringParameter( + uri, Parameters.ClientId, client).AbsoluteUri; + } + } + + static DateTimeOffset? GetIssuanceDate(OpenIddictApplicationDescriptor descriptor) + => descriptor.Properties.TryGetValue(Properties.ClientMetadata, out var metadata) && + metadata.ValueKind is JsonValueKind.Object && + metadata.TryGetProperty(ClientMetadata.ClientIdIssuedAt, out var value) && + value.TryGetInt64(out var seconds) ? DateTimeOffset.FromUnixTimeSeconds(seconds) : null; + + static JsonElement AddIssuanceDate(JsonElement metadata, DateTimeOffset date) + { + var values = new Dictionary(StringComparer.Ordinal); + + if (metadata.ValueKind is JsonValueKind.Object) + { + foreach (var property in metadata.EnumerateObject()) + { + values[property.Name] = property.Value; + } + } + + values[ClientMetadata.ClientIdIssuedAt] = CreateElement(writer => writer.WriteNumberValue(date.ToUnixTimeSeconds())); + + return SerializeMetadata(values); + } + } + } + + private static JsonElement SerializeMetadata(IEnumerable> metadata) + => CreateElement(writer => + { + writer.WriteStartObject(); + + foreach (var item in metadata) + { + writer.WritePropertyName(item.Key); + item.Value.WriteTo(writer); + } + + writer.WriteEndObject(); + }); + + private static void WriteStrings(Utf8JsonWriter writer, IEnumerable values) + { + writer.WriteStartArray(); + + foreach (var value in values) + { + writer.WriteStringValue(value); + } + + writer.WriteEndArray(); + } + + private static JsonElement CreateElement(Action action) + { + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + action(writer); + } + + using var document = JsonDocument.Parse(stream.ToArray()); + return document.RootElement.Clone(); + } + } +} diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs index e7dce056..6858c1e4 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs +++ b/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), diff --git a/src/OpenIddict.Server/OpenIddictServerOptions.cs b/src/OpenIddict.Server/OpenIddictServerOptions.cs index a97c17ce..8d16cb28 100644 --- a/src/OpenIddict.Server/OpenIddictServerOptions.cs +++ b/src/OpenIddict.Server/OpenIddictServerOptions.cs @@ -105,6 +105,11 @@ public sealed class OpenIddictServerOptions /// public List PushedAuthorizationEndpointUris { get; } = []; + /// + /// Gets the absolute and relative URIs associated to the dynamic client registration endpoint. + /// + public List RegistrationEndpointUris { get; } = []; + /// /// Gets the absolute and relative URIs associated to the revocation endpoint. /// @@ -736,6 +741,53 @@ public sealed class OpenIddictServerOptions /// public bool RequireDPoPNonces { get; set; } + /// + /// 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. + /// + /// + /// Note: this option requires setting at least one registration endpoint URI. + /// + public bool EnableDynamicClientRegistration { get; set; } + + /// + /// Gets or sets a boolean indicating whether client registration requests that don't include an initial + /// access token are accepted. Setting this property to enables open registration + /// and is NOT recommended unless additional policy handlers are registered to approve registrations. + /// + public bool AllowAnonymousClientRegistration { get; set; } + + /// + /// 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. + /// + public HashSet InitialAccessTokenScopes { get; } = new(StringComparer.Ordinal); + + /// + /// 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. + /// + public TimeSpan? RegistrationAccessTokenLifetime { get; set; } + + /// + /// Gets or sets a boolean indicating whether client registration requests must include a software statement. + /// + public bool RequireSoftwareStatement { get; set; } + + /// + /// 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 . + /// + public HashSet SoftwareStatementIssuers { get; } = new(StringComparer.Ordinal); + + /// + /// 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. + /// + public List SoftwareStatementSigningKeys { get; } = []; + /// /// Gets or sets the maximum difference allowed between the issuance date of a DPoP proof and the current date. /// diff --git a/src/OpenIddict.Server/OpenIddictServerRegistrationRequestType.cs b/src/OpenIddict.Server/OpenIddictServerRegistrationRequestType.cs new file mode 100644 index 00000000..7f271876 --- /dev/null +++ b/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; + +/// +/// Represents the type of an operation performed using the dynamic client registration endpoint. +/// +public enum OpenIddictServerRegistrationRequestType +{ + /// + /// Unknown operation (e.g unsupported HTTP method). + /// + Unknown = 0, + + /// + /// Client registration request (RFC 7591, HTTP POST). + /// + Registration = 1, + + /// + /// Client read request (RFC 7592, HTTP GET). + /// + Read = 2, + + /// + /// Client update request (RFC 7592, HTTP PUT). + /// + Update = 3, + + /// + /// Client delete request (RFC 7592, HTTP DELETE). + /// + Deletion = 4 +} diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs index 35590ffa..7e7a3a4d 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs +++ b/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); } + /// + /// 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. + /// + /// The HTTP method used to send the request. + /// The endpoint to which the request is sent. + /// The JSON payload, if applicable. + /// The bearer token attached to the Authorization header, if applicable. + /// The OpenID Connect response returned by the server. + public virtual async Task 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); + } + + /// + /// Gets the HTTP status code of the last response received by this client, if available. + /// + public System.Net.HttpStatusCode? ResponseStatusCode { get; private set; } + /// /// Gets the additional headers attached to all the requests sent by this client. /// diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerRegistrationTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerRegistrationTests.cs new file mode 100644 index 00000000..178aa3c0 --- /dev/null +++ b/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(() => 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(() => 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(() => 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>().Value; +}