diff --git a/src/OpenIddict.Abstractions/OpenIddictConstants.cs b/src/OpenIddict.Abstractions/OpenIddictConstants.cs index 47fd781e..17685af5 100644 --- a/src/OpenIddict.Abstractions/OpenIddictConstants.cs +++ b/src/OpenIddict.Abstractions/OpenIddictConstants.cs @@ -126,8 +126,10 @@ public static class OpenIddictConstants { public const string AccessTokenLifetime = "oi_act_lft"; public const string Audience = "oi_aud"; + public const string AuthenticationRequestIdLifetime = "oi_arid_lft"; public const string AuthorizationCodeLifetime = "oi_auc_lft"; public const string AuthorizationId = "oi_au_id"; + public const string BindingMessage = "oi_bdg_msg"; public const string ClaimDestinationsMap = "oi_cl_dstn"; public const string CodeChallenge = "oi_cd_chlg"; public const string CodeChallengeMethod = "oi_cd_chlg_meth"; @@ -165,6 +167,13 @@ public static class OpenIddictConstants } } + public static class BackchannelTokenDeliveryModes + { + public const string Ping = "ping"; + public const string Poll = "poll"; + public const string Push = "push"; + } + public static class ClaimRequestMembers { public const string Essential = "essential"; @@ -224,10 +233,12 @@ public static class OpenIddictConstants public const string AccountSelectionRequired = "account_selection_required"; public const string AuthorizationPending = "authorization_pending"; public const string ConsentRequired = "consent_required"; + public const string ExpiredLoginHintToken = "expired_login_hint_token"; public const string ExpiredToken = "expired_token"; public const string InsufficientAccess = "insufficient_access"; public const string InsufficientScope = "insufficient_scope"; public const string InteractionRequired = "interaction_required"; + public const string InvalidBindingMessage = "invalid_binding_message"; public const string InvalidClient = "invalid_client"; public const string InvalidGrant = "invalid_grant"; public const string InvalidRequest = "invalid_request"; @@ -236,8 +247,10 @@ public static class OpenIddictConstants public const string InvalidScope = "invalid_scope"; public const string InvalidTarget = "invalid_target"; public const string InvalidToken = "invalid_token"; + public const string InvalidUserCode = "invalid_user_code"; public const string LoginRequired = "login_required"; public const string MissingToken = "missing_token"; + public const string MissingUserCode = "missing_user_code"; public const string RegistrationNotSupported = "registration_not_supported"; public const string RequestNotSupported = "request_not_supported"; public const string RequestUriNotSupported = "request_uri_not_supported"; @@ -245,6 +258,7 @@ public static class OpenIddictConstants public const string SlowDown = "slow_down"; public const string TemporarilyUnavailable = "temporarily_unavailable"; public const string UnauthorizedClient = "unauthorized_client"; + public const string UnknownUserId = "unknown_user_id"; public const string UnmetAuthenticationRequirements = "unmet_authentication_requirements"; public const string UnsupportedGrantType = "unsupported_grant_type"; public const string UnsupportedResponseType = "unsupported_response_type"; @@ -254,6 +268,7 @@ public static class OpenIddictConstants public static class GrantTypes { public const string AuthorizationCode = "authorization_code"; + public const string Ciba = "urn:openid:params:grant-type:ciba"; public const string ClientCredentials = "client_credentials"; public const string DeviceCode = "urn:ietf:params:oauth:grant-type:device_code"; public const string Implicit = "implicit"; @@ -277,6 +292,7 @@ public static class OpenIddictConstants public static class Private { + public const string AuthenticationRequestId = "oi_arid+jwt"; public const string AuthorizationCode = "oi_auc+jwt"; public const string DeviceCode = "oi_dvc+jwt"; public const string RefreshToken = "oi_reft+jwt"; @@ -291,6 +307,10 @@ public static class OpenIddictConstants public const string AcrValuesSupported = "acr_values_supported"; public const string AuthorizationEndpoint = "authorization_endpoint"; public const string AuthorizationResponseIssParameterSupported = "authorization_response_iss_parameter_supported"; + public const string BackchannelAuthenticationEndpoint = "backchannel_authentication_endpoint"; + public const string BackchannelAuthenticationRequestSigningAlgValuesSupported = "backchannel_authentication_request_signing_alg_values_supported"; + public const string BackchannelTokenDeliveryModesSupported = "backchannel_token_delivery_modes_supported"; + public const string BackchannelUserCodeParameterSupported = "backchannel_user_code_parameter_supported"; public const string ClaimsLocalesSupported = "claims_locales_supported"; public const string ClaimsParameterSupported = "claims_parameter_supported"; public const string ClaimsSupported = "claims_supported"; @@ -365,11 +385,14 @@ public static class OpenIddictConstants public const string ActorTokenType = "actor_token_type"; public const string Assertion = "assertion"; public const string Audience = "audience"; + public const string AuthReqId = "auth_req_id"; + public const string BindingMessage = "binding_message"; public const string Claims = "claims"; public const string ClaimsLocales = "claims_locales"; public const string ClientAssertion = "client_assertion"; public const string ClientAssertionType = "client_assertion_type"; public const string ClientId = "client_id"; + public const string ClientNotificationToken = "client_notification_token"; public const string ClientSecret = "client_secret"; public const string Code = "code"; public const string CodeChallenge = "code_challenge"; @@ -389,6 +412,7 @@ public static class OpenIddictConstants public const string Iss = "iss"; public const string IssuedTokenType = "issued_token_type"; public const string LoginHint = "login_hint"; + public const string LoginHintToken = "login_hint_token"; public const string Keys = "keys"; public const string MaxAge = "max_age"; public const string Nonce = "nonce"; @@ -400,6 +424,7 @@ public static class OpenIddictConstants public const string RefreshToken = "refresh_token"; public const string Registration = "registration"; public const string Request = "request"; + public const string RequestedExpiry = "requested_expiry"; public const string RequestedTokenType = "requested_token_type"; public const string RequestUri = "request_uri"; public const string Resource = "resource"; @@ -424,6 +449,7 @@ public static class OpenIddictConstants public static class Endpoints { public const string Authorization = "ept:authorization"; + public const string BackchannelAuthentication = "ept:backchannel_authentication"; public const string DeviceAuthorization = "ept:device_authorization"; public const string EndSession = "ept:end_session"; public const string Introspection = "ept:introspection"; @@ -435,6 +461,7 @@ public static class OpenIddictConstants public static class GrantTypes { public const string AuthorizationCode = "gt:authorization_code"; + public const string Ciba = "gt:urn:openid:params:grant-type:ciba"; public const string ClientCredentials = "gt:client_credentials"; public const string DeviceCode = "gt:urn:ietf:params:oauth:grant-type:device_code"; public const string Implicit = "gt:implicit"; @@ -487,6 +514,7 @@ public static class OpenIddictConstants public static class Properties { public const string Destinations = ".destinations"; + public const string LastPollingDate = ".last_polling_date"; } public static class RequestTokenTypes @@ -579,6 +607,7 @@ public static class OpenIddictConstants public static class TokenLifetimes { public const string AccessToken = "tkn_lft:act"; + public const string AuthenticationRequestId = "tkn_lft:arid"; public const string AuthorizationCode = "tkn_lft:auc"; public const string DeviceCode = "tkn_lft:dvc"; public const string IdentityToken = "tkn_lft:idt"; @@ -647,6 +676,7 @@ public static class OpenIddictConstants public static class Private { + public const string AuthenticationRequestId = "urn:openiddict:params:oauth:token-type:auth_req_id"; public const string AuthorizationCode = "urn:openiddict:params:oauth:token-type:authorization_code"; public const string ClientAssertion = "urn:openiddict:params:oauth:token-type:client_assertion"; public const string DeviceCode = "urn:openiddict:params:oauth:token-type:device_code"; diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index fe631ae6..7f6c6360 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -1801,6 +1801,33 @@ To enable request object support, call 'services.AddOpenIddict().AddServer().Ena A signed request object must be sent but no asymmetric signing key was attached to the client registration. To use signed request objects, attach an asymmetric signing key or certificate to the client registration. + + + The backchannel authentication endpoint must be enabled to use the Client-Initiated Backchannel Authentication flow. + + + The Client-Initiated Backchannel Authentication flow must be enabled when the backchannel authentication endpoint is enabled. + + + The Client-Initiated Backchannel Authentication flow cannot be used when the degraded mode is enabled, when token storage is disabled or when no explicit issuer is configured. + + + A principal containing an authenticated identity and a subject claim must be attached to the backchannel authentication request context. +To attach it, enable the pass-through mode or register a custom event handler for the 'HandleBackchannelAuthenticationRequestContext' event. + + + The principal used to approve a backchannel authentication request must contain an authenticated identity and the same subject as the one attached to the request. + + + The authentication request identifier could not be generated: {0} ({1}). + + + The backchannel authentication request was not correctly extracted. +To extract backchannel authentication requests, create a class implementing 'IOpenIddictServerHandler<ExtractBackchannelAuthenticationRequestContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'. + + + The backchannel authentication response was not correctly applied. +To apply backchannel authentication responses, create a class implementing 'IOpenIddictServerHandler<ApplyBackchannelAuthenticationResponseContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'. The security token is missing. @@ -2440,6 +2467,24 @@ To use signed request objects, attach an asymmetric signing key or certificate t The '{0}' claim of the request object is missing or invalid. + + The client application is polling the token endpoint too frequently. + + + Exactly one of the 'login_hint', 'login_hint_token' or 'id_token_hint' parameters must be specified. + + + The mandatory 'openid' scope is missing. + + + The '{0}' parameter is required when using the Client-Initiated Backchannel Authentication grant. + + + This client application is not allowed to use the backchannel authentication endpoint. + + + The client application is not allowed to use the Client-Initiated Backchannel Authentication flow. + The '{0}' parameter shouldn't be null or empty at this point. @@ -3307,6 +3352,27 @@ This may indicate that the hashed entry is corrupted or malformed. The authorization request was rejected because the request object was invalid: {Error} ({Description}). + + The token request was rejected because the client application polled the token '{Identifier}' too frequently. + + + The backchannel authentication request was successfully extracted: {Request}. + + + The backchannel authentication request was successfully validated. + + + The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the backchannel authentication endpoint. + + + The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the Client-Initiated Backchannel Authentication flow. + + + The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the scope {Scope}. + + + The backchannel authentication request was rejected because invalid scopes were specified: {Scopes}. + https://documentation.openiddict.com/errors/{0} diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs index 6f9ab1a8..24927152 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs @@ -26,6 +26,22 @@ public sealed class OpenIddictConfiguration /// public bool? AuthorizationResponseIssParameterSupported { get; set; } + /// + /// Gets or sets the URI of the backchannel authentication endpoint. + /// + public Uri? BackchannelAuthenticationEndpoint { get; set; } + + /// + /// Gets the backchannel token delivery modes supported by the server. + /// + public HashSet BackchannelTokenDeliveryModesSupported { get; } = new(StringComparer.Ordinal); + + /// + /// Gets or sets a boolean indicating whether the "user_code" parameter + /// is supported by the backchannel authentication endpoint. + /// + public bool? BackchannelUserCodeParameterSupported { get; set; } + /// /// Gets the code challenge methods supported by the server. /// diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs index 94ee1b26..b49665ac 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs @@ -500,6 +500,19 @@ public static class OpenIddictExtensions return string.Equals(request.GrantType, GrantTypes.DeviceCode, StringComparison.Ordinal); } + /// + /// Determines whether the "grant_type" parameter corresponds to the Client-Initiated Backchannel Authentication grant. + /// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html for more information. + /// + /// The instance. + /// if the request is a CIBA grant request, otherwise. + public static bool IsCibaGrantType(this OpenIddictRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + return string.Equals(request.GrantType, GrantTypes.Ciba, StringComparison.Ordinal); + } + /// /// Determines whether the "grant_type" parameter corresponds to the password grant. /// See http://tools.ietf.org/html/rfc6749#section-4.3.2 for more information. @@ -2564,6 +2577,22 @@ public static class OpenIddictExtensions public static TimeSpan? GetAuthorizationCodeLifetime(this ClaimsPrincipal principal) => GetLifetime(principal, Claims.Private.AuthorizationCodeLifetime); + /// + /// Gets the authentication request identifier lifetime associated with the claims identity. + /// + /// The claims identity. + /// The authentication request identifier lifetime or if the claim cannot be found. + public static TimeSpan? GetAuthenticationRequestIdLifetime(this ClaimsIdentity identity) + => GetLifetime(identity, Claims.Private.AuthenticationRequestIdLifetime); + + /// + /// Gets the authentication request identifier lifetime associated with the claims principal. + /// + /// The claims principal. + /// The authentication request identifier lifetime or if the claim cannot be found. + public static TimeSpan? GetAuthenticationRequestIdLifetime(this ClaimsPrincipal principal) + => GetLifetime(principal, Claims.Private.AuthenticationRequestIdLifetime); + /// /// Gets the device code lifetime associated with the claims identity. /// @@ -3234,6 +3263,24 @@ public static class OpenIddictExtensions public static ClaimsPrincipal SetDeviceCodeLifetime(this ClaimsPrincipal principal, TimeSpan? lifetime) => principal.SetClaim(Claims.Private.DeviceCodeLifetime, (long?) lifetime?.TotalSeconds); + /// + /// Sets the authentication request identifier lifetime associated with the claims identity. + /// + /// The claims identity. + /// The authentication request identifier lifetime to store. + /// The claims identity. + public static ClaimsIdentity SetAuthenticationRequestIdLifetime(this ClaimsIdentity identity, TimeSpan? lifetime) + => identity.SetClaim(Claims.Private.AuthenticationRequestIdLifetime, (long?) lifetime?.TotalSeconds); + + /// + /// Sets the authentication request identifier lifetime associated with the claims principal. + /// + /// The claims principal. + /// The authentication request identifier lifetime to store. + /// The claims principal. + public static ClaimsPrincipal SetAuthenticationRequestIdLifetime(this ClaimsPrincipal principal, TimeSpan? lifetime) + => principal.SetClaim(Claims.Private.AuthenticationRequestIdLifetime, (long?) lifetime?.TotalSeconds); + /// /// Sets the identity token lifetime associated with the claims identity. /// diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs index 4a8e4169..294e5d2d 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs @@ -255,6 +255,51 @@ public class OpenIddictRequest : OpenIddictMessage set => SetParameter(OpenIddictConstants.Parameters.CodeVerifier, value); } + /// + /// Gets or sets the "auth_req_id" parameter. + /// + public string? AuthReqId + { + get => (string?) GetParameter(OpenIddictConstants.Parameters.AuthReqId); + set => SetParameter(OpenIddictConstants.Parameters.AuthReqId, value); + } + + /// + /// Gets or sets the "binding_message" parameter. + /// + public string? BindingMessage + { + get => (string?) GetParameter(OpenIddictConstants.Parameters.BindingMessage); + set => SetParameter(OpenIddictConstants.Parameters.BindingMessage, value); + } + + /// + /// Gets or sets the "client_notification_token" parameter. + /// + public string? ClientNotificationToken + { + get => (string?) GetParameter(OpenIddictConstants.Parameters.ClientNotificationToken); + set => SetParameter(OpenIddictConstants.Parameters.ClientNotificationToken, value); + } + + /// + /// Gets or sets the "login_hint_token" parameter. + /// + public string? LoginHintToken + { + get => (string?) GetParameter(OpenIddictConstants.Parameters.LoginHintToken); + set => SetParameter(OpenIddictConstants.Parameters.LoginHintToken, value); + } + + /// + /// Gets or sets the "requested_expiry" parameter. + /// + public long? RequestedExpiry + { + get => (long?) GetParameter(OpenIddictConstants.Parameters.RequestedExpiry); + set => SetParameter(OpenIddictConstants.Parameters.RequestedExpiry, value); + } + /// /// Gets or sets the "device_code" parameter. /// diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs index c943c818..50918dd2 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs @@ -122,6 +122,24 @@ public class OpenIddictResponse : OpenIddictMessage set => SetParameter(OpenIddictConstants.Parameters.Code, value); } + /// + /// Gets or sets the "auth_req_id" parameter. + /// + public string? AuthReqId + { + get => (string?) GetParameter(OpenIddictConstants.Parameters.AuthReqId); + set => SetParameter(OpenIddictConstants.Parameters.AuthReqId, value); + } + + /// + /// Gets or sets the "interval" parameter. + /// + public long? Interval + { + get => (long?) GetParameter(OpenIddictConstants.Parameters.Interval); + set => SetParameter(OpenIddictConstants.Parameters.Interval, value); + } + /// /// Gets or sets the "device_code" parameter. /// diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs index 8e2733ff..6e145930 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs @@ -74,6 +74,16 @@ public sealed class OpenIddictServerAspNetCoreBuilder public OpenIddictServerAspNetCoreBuilder EnableAuthorizationEndpointPassthrough() => Configure(options => options.EnableAuthorizationEndpointPassthrough = true); + /// + /// Enables the pass-through mode for the OpenID Connect backchannel authentication endpoint. + /// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict. + /// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests + /// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance). + /// + /// The instance. + public OpenIddictServerAspNetCoreBuilder EnableBackchannelAuthenticationEndpointPassthrough() + => Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = 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 74ea6787..2f07a38a 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs @@ -44,6 +44,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 410fa02b..60c29795 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs @@ -162,7 +162,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler context.IdentityTokenPrincipal, OpenIddictServerEndpointType.EndUserVerification => context.UserCodePrincipal, @@ -174,6 +175,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler context.AuthorizationCodePrincipal, OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType() => context.DeviceCodePrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType() + => context.AuthenticationRequestIdPrincipal, OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType() => context.RefreshTokenPrincipal, OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType() diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs index b22193cc..af3aa1a1 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs @@ -36,6 +36,26 @@ public static class OpenIddictServerAspNetCoreHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if the + /// pass-through mode was not enabled for the backchannel authentication endpoint. + /// + public sealed class RequireBackchannelAuthenticationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter + { + private readonly IOptionsMonitor _options; + + public RequireBackchannelAuthenticationEndpointPassthroughEnabled(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(_options.CurrentValue.EnableBackchannelAuthenticationEndpointPassthrough); + } + } + /// /// 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.Backchannel.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Backchannel.cs new file mode 100644 index 00000000..41e91b29 --- /dev/null +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Backchannel.cs @@ -0,0 +1,39 @@ +/* + * 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; + +namespace OpenIddict.Server.AspNetCore; + +public static partial class OpenIddictServerAspNetCoreHandlers +{ + public static class Backchannel + { + public static ImmutableArray DefaultHandlers { get; } = + [ + /* + * Backchannel authentication request extraction: + */ + ExtractPostRequest.Descriptor, + ValidateClientAuthenticationMethod.Descriptor, + ExtractClientCertificate.Descriptor, + ExtractBasicAuthenticationCredentials.Descriptor, + + /* + * Backchannel authentication request handling: + */ + EnablePassthroughMode.Descriptor, + + /* + * Backchannel authentication response processing: + */ + AttachHttpResponseCode.Descriptor, + AttachCacheControlHeader.Descriptor, + AttachWwwAuthenticateHeader.Descriptor, + ProcessJsonResponse.Descriptor + ]; + } +} diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs index 7bd5b361..1432a049 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs @@ -52,6 +52,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers ResolveHostSignOutProperties.Descriptor, .. Authentication.DefaultHandlers, + .. Backchannel.DefaultHandlers, .. Device.DefaultHandlers, .. Discovery.DefaultHandlers, .. Exchange.DefaultHandlers, diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs index aac6e238..49e5745a 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs @@ -27,6 +27,14 @@ public sealed class OpenIddictServerAspNetCoreOptions /// public bool EnableAuthorizationEndpointPassthrough { get; set; } + /// + /// Gets or sets a boolean indicating whether the pass-through mode is enabled for the backchannel authentication endpoint. + /// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict. + /// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests + /// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance). + /// + public bool EnableBackchannelAuthenticationEndpointPassthrough { 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 7350b326..69552493 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs @@ -74,6 +74,16 @@ public sealed class OpenIddictServerOwinBuilder public OpenIddictServerOwinBuilder EnableAuthorizationEndpointPassthrough() => Configure(options => options.EnableAuthorizationEndpointPassthrough = true); + /// + /// Enables the pass-through mode for the OpenID Connect backchannel authentication endpoint. + /// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict. + /// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests + /// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance). + /// + /// The instance. + public OpenIddictServerOwinBuilder EnableBackchannelAuthenticationEndpointPassthrough() + => Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = 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 e5c65cde..c989161f 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs @@ -46,6 +46,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 68b8d3c8..bc916484 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs @@ -175,7 +175,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler context.IdentityTokenPrincipal, OpenIddictServerEndpointType.EndUserVerification => context.UserCodePrincipal, @@ -187,6 +188,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler context.AuthorizationCodePrincipal, OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType() => context.DeviceCodePrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType() + => context.AuthenticationRequestIdPrincipal, OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType() => context.RefreshTokenPrincipal, OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType() diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs index 3b1193ea..ad3a0b7a 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs @@ -34,6 +34,26 @@ public static class OpenIddictServerOwinHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if the + /// pass-through mode was not enabled for the backchannel authentication endpoint. + /// + public sealed class RequireBackchannelAuthenticationEndpointPassthroughEnabled : IOpenIddictServerHandlerFilter + { + private readonly IOptionsMonitor _options; + + public RequireBackchannelAuthenticationEndpointPassthroughEnabled(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(_options.CurrentValue.EnableBackchannelAuthenticationEndpointPassthrough); + } + } + /// /// 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.Backchannel.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Backchannel.cs new file mode 100644 index 00000000..4b10aaee --- /dev/null +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Backchannel.cs @@ -0,0 +1,41 @@ +/* + * 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; + +namespace OpenIddict.Server.Owin; + +public static partial class OpenIddictServerOwinHandlers +{ + public static class Backchannel + { + public static ImmutableArray DefaultHandlers { get; } = + [ + /* + * Backchannel authentication request extraction: + */ + ExtractPostRequest.Descriptor, + ValidateClientAuthenticationMethod.Descriptor, + ExtractClientCertificate.Descriptor, + ExtractBasicAuthenticationCredentials.Descriptor, + + /* + * Backchannel authentication request handling: + */ + EnablePassthroughMode.Descriptor, + + /* + * Backchannel authentication response processing: + */ + AttachHttpResponseCode.Descriptor, + AttachOwinResponseChallenge.Descriptor, + SuppressFormsAuthenticationRedirect.Descriptor, + AttachCacheControlHeader.Descriptor, + AttachWwwAuthenticateHeader.Descriptor, + ProcessJsonResponse.Descriptor + ]; + } +} diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs index 02b7eddb..9032c461 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs @@ -50,6 +50,7 @@ public static partial class OpenIddictServerOwinHandlers ResolveHostSignOutProperties.Descriptor, .. Authentication.DefaultHandlers, + .. Backchannel.DefaultHandlers, .. Device.DefaultHandlers, .. Discovery.DefaultHandlers, .. Exchange.DefaultHandlers, diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs index acc1938f..bf62019f 100644 --- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs +++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs @@ -27,6 +27,14 @@ public sealed class OpenIddictServerOwinOptions /// public bool EnableAuthorizationEndpointPassthrough { get; set; } + /// + /// Gets or sets a boolean indicating whether the pass-through mode is enabled for the backchannel authentication endpoint. + /// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict. + /// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests + /// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance). + /// + public bool EnableBackchannelAuthenticationEndpointPassthrough { 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 5bb5d9fc..228ce98f 100644 --- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs +++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs @@ -914,7 +914,7 @@ public sealed class OpenIddictServerBuilder GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or GrantTypes.DeviceCode or GrantTypes.Implicit or GrantTypes.Password or GrantTypes.RefreshToken or - GrantTypes.TokenExchange + GrantTypes.TokenExchange or GrantTypes.Ciba => throw new ArgumentException(SR.FormatID0517(type), nameof(type)), _ => Configure(options => options.GrantTypes.Add(type)) @@ -929,6 +929,15 @@ public sealed class OpenIddictServerBuilder public OpenIddictServerBuilder AllowDeviceAuthorizationFlow() => Configure(options => options.GrantTypes.Add(GrantTypes.DeviceCode)); + /// + /// Enables OpenID Connect Client-Initiated Backchannel Authentication (CIBA) flow support (poll mode). + /// For more information about this specific flow, visit + /// https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html. + /// + /// The instance. + public OpenIddictServerBuilder AllowClientInitiatedBackchannelAuthenticationFlow() + => Configure(options => options.GrantTypes.Add(GrantTypes.Ciba)); + /// /// Enables hybrid flow support. For more information /// about this specific OpenID Connect flow, visit @@ -1054,6 +1063,49 @@ public sealed class OpenIddictServerBuilder }); } + /// + /// Sets the relative or absolute URIs associated to the backchannel authentication 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 SetBackchannelAuthenticationEndpointUris( + [StringSyntax(StringSyntaxAttribute.Uri)] params string[] uris) + { + ArgumentNullException.ThrowIfNull(uris); + + return SetBackchannelAuthenticationEndpointUris([.. uris.Select(uri => new Uri(uri, UriKind.RelativeOrAbsolute))]); + } + + /// + /// Sets the relative or absolute URIs associated to the backchannel authentication 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 SetBackchannelAuthenticationEndpointUris(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.BackchannelAuthenticationEndpointUris.Clear(); + options.BackchannelAuthenticationEndpointUris.AddRange(uris); + }); + } + /// /// Sets the relative or absolute URIs associated to the configuration endpoint. /// If an empty array is specified, the endpoint will be considered disabled. @@ -1792,6 +1844,25 @@ public sealed class OpenIddictServerBuilder public OpenIddictServerBuilder SetDeviceCodeLifetime(TimeSpan? lifetime) => Configure(options => options.DeviceCodeLifetime = lifetime); + /// + /// Sets the authentication request identifier lifetime, after which client applications + /// are unable to send a grant_type=urn:openid:params:grant-type:ciba token request. + /// While discouraged, can be specified to issue identifiers that never expire. + /// + /// The authentication request identifier lifetime. + /// The instance. + public OpenIddictServerBuilder SetAuthenticationRequestIdLifetime(TimeSpan? lifetime) + => Configure(options => options.AuthenticationRequestIdLifetime = lifetime); + + /// + /// Sets the minimum polling interval client applications must respect when using the device code + /// or CIBA grants. If is specified, the polling interval is not enforced. + /// + /// The polling interval. + /// The instance. + public OpenIddictServerBuilder SetPollingInterval(TimeSpan? interval) + => Configure(options => options.PollingInterval = interval); + /// /// Sets the identity token lifetime, after which client /// applications should refuse processing identity tokens. diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs index 9ffc11c0..539aee74 100644 --- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs +++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs @@ -222,6 +222,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions 0 && !options.GrantTypes.Contains(GrantTypes.Ciba)) + { + builder.AddError(SR.GetResourceString(SR.ID0528)); + } + + // Ensure the CIBA grant is not used with the degraded mode, with token storage disabled or without an explicit + // issuer, as authentication requests are persisted and completed outside the context of an HTTP request. + if (options.GrantTypes.Contains(GrantTypes.Ciba) && + (options.EnableDegradedMode || options.DisableTokenStorage || options.Issuer is null)) + { + builder.AddError(SR.GetResourceString(SR.ID0529)); + } + // Ensure the grant types/response types configuration is consistent. foreach (var type in options.ResponseTypes) { @@ -298,7 +319,8 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions /// Pushed authorization endpoint. /// - PushedAuthorization = 11 + PushedAuthorization = 11, + + /// + /// Backchannel authentication endpoint. + /// + BackchannelAuthentication = 12 } diff --git a/src/OpenIddict.Server/OpenIddictServerEvents.Backchannel.cs b/src/OpenIddict.Server/OpenIddictServerEvents.Backchannel.cs new file mode 100644 index 00000000..8e8193de --- /dev/null +++ b/src/OpenIddict.Server/OpenIddictServerEvents.Backchannel.cs @@ -0,0 +1,159 @@ +/* + * 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; + +namespace OpenIddict.Server; + +public static partial class OpenIddictServerEvents +{ + /// + /// Represents an event called for each request to the backchannel authentication endpoint to give + /// the user code a chance to manually extract the request from the ambient HTTP context. + /// + public sealed class ExtractBackchannelAuthenticationRequestContext : BaseValidatingContext + { + /// + /// Creates a new instance of the class. + /// + public ExtractBackchannelAuthenticationRequestContext(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; + } + } + + /// + /// Represents an event called for each request to the backchannel authentication endpoint + /// to determine if the request is valid and should continue to be processed. + /// + public sealed class ValidateBackchannelAuthenticationRequestContext : BaseValidatingClientContext + { + /// + /// Creates a new instance of the class. + /// + public ValidateBackchannelAuthenticationRequestContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request. + /// + public OpenIddictRequest Request + { + get => Transaction.Request!; + set => Transaction.Request = value; + } + + /// + /// Gets or sets the security principal extracted + /// from the identity token hint, if applicable. + /// + public ClaimsPrincipal? IdentityTokenHintPrincipal { get; set; } + } + + /// + /// Represents an event called for each validated backchannel authentication request to allow the user code + /// to identify the end user (using the login_hint, login_hint_token or id_token_hint parameters), notify + /// the end user out-of-band and attach a principal containing the identity of the end user. + /// + public sealed class HandleBackchannelAuthenticationRequestContext : BaseValidatingTicketContext + { + /// + /// Creates a new instance of the class. + /// + public HandleBackchannelAuthenticationRequestContext(OpenIddictServerTransaction transaction) + : base(transaction) + { + } + + /// + /// Gets or sets the request. + /// + public OpenIddictRequest Request + { + get => Transaction.Request!; + set => Transaction.Request = value; + } + + /// + /// Gets or sets the security principal extracted + /// from the identity token hint, if applicable. + /// + public ClaimsPrincipal? IdentityTokenHintPrincipal { get; set; } + + /// + /// Gets the additional parameters returned to the client application. + /// + public Dictionary Parameters { get; private set; } + = new(StringComparer.Ordinal); + + /// + /// Allows OpenIddict to return a sign-in response using the specified principal. + /// + /// The claims principal. + public void SignIn(ClaimsPrincipal principal) => Principal = principal; + + /// + /// Allows OpenIddict to return a sign-in response using the specified principal. + /// + /// The claims principal. + /// The additional parameters returned to the client application. + public void SignIn(ClaimsPrincipal principal, IDictionary parameters) + { + Principal = principal; + Parameters = new(parameters, StringComparer.Ordinal); + } + } + + /// + /// Represents an event called before the backchannel authentication response is returned to the caller. + /// + public sealed class ApplyBackchannelAuthenticationResponseContext : BaseRequestContext + { + /// + /// Creates a new instance of the class. + /// + public ApplyBackchannelAuthenticationResponseContext(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 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/OpenIddictServerEvents.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs index 74f9306f..2901fd5e 100644 --- a/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs +++ b/src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs @@ -96,6 +96,16 @@ public static partial class OpenIddictServerEvents /// public Uri? AuthorizationEndpoint { get; set; } + /// + /// Gets or sets the backchannel authentication endpoint URI. + /// + public Uri? BackchannelAuthenticationEndpoint { get; set; } + + /// + /// Gets the backchannel token delivery modes supported by the authorization server. + /// + public HashSet BackchannelTokenDeliveryModes { get; } = new(StringComparer.Ordinal); + /// /// Gets or sets the JSON Web Key Set endpoint URI. /// diff --git a/src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs b/src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs index 25b7d754..403b7256 100644 --- a/src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs +++ b/src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs @@ -72,6 +72,11 @@ public static partial class OpenIddictServerEvents /// public ClaimsPrincipal? DeviceCodePrincipal { get; set; } + /// + /// Gets or sets the security principal extracted from the authentication request identifier, if applicable. + /// + public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; } + /// /// Gets or sets the security principal extracted from the refresh token, if applicable. /// @@ -121,6 +126,11 @@ public static partial class OpenIddictServerEvents /// public ClaimsPrincipal? DeviceCodePrincipal { get; set; } + /// + /// Gets or sets the security principal extracted from the authentication request identifier, if applicable. + /// + public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; } + /// /// Gets or sets the security principal extracted from the refresh token, if applicable. /// diff --git a/src/OpenIddict.Server/OpenIddictServerEvents.cs b/src/OpenIddict.Server/OpenIddictServerEvents.cs index cf6c6b46..5920a49d 100644 --- a/src/OpenIddict.Server/OpenIddictServerEvents.cs +++ b/src/OpenIddict.Server/OpenIddictServerEvents.cs @@ -367,6 +367,15 @@ public static partial class OpenIddictServerEvents /// public bool ExtractDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether an authentication + /// request identifier should be extracted from the current context. + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool ExtractAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether a generic /// token should be extracted from the current context. @@ -466,6 +475,15 @@ public static partial class OpenIddictServerEvents /// public bool RequireDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether an authentication request identifier + /// must be resolved for the authentication to be considered valid. + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool RequireAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether a generic token /// must be resolved for the authentication to be considered valid. @@ -565,6 +583,15 @@ public static partial class OpenIddictServerEvents /// public bool ValidateDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether the authentication request + /// identifier extracted from the current request should be validated. + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool ValidateAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether the generic /// token extracted from the current request should be validated. @@ -664,6 +691,15 @@ public static partial class OpenIddictServerEvents /// public bool RejectDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether an invalid authentication request identifier + /// will cause the authentication demand to be rejected or will be ignored. + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool RejectAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether an invalid generic token /// will cause the authentication demand to be rejected or will be ignored. @@ -778,6 +814,16 @@ public static partial class OpenIddictServerEvents /// public ClaimsPrincipal? DeviceCodePrincipal { get; set; } + /// + /// Gets or sets the authentication request identifier to validate, if applicable. + /// + public string? AuthenticationRequestId { get; set; } + + /// + /// Gets or sets the principal extracted from the authentication request identifier, if applicable. + /// + public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; } + /// /// Gets or sets the generic token to validate, if applicable. /// @@ -959,6 +1005,15 @@ public static partial class OpenIddictServerEvents /// public bool GenerateDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether an authentication request + /// identifier should be generated (and optionally returned to the client). + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool GenerateAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether an issued token /// should be generated (and optionally returned to the client). @@ -1031,6 +1086,15 @@ public static partial class OpenIddictServerEvents /// public bool IncludeDeviceCode { get; set; } + /// + /// Gets or sets a boolean indicating whether the generated authentication request + /// identifier should be returned to the client application as part of the response. + /// + /// + /// Note: overriding the value of this property is generally not recommended. + /// + public bool IncludeAuthenticationRequestId { get; set; } + /// /// Gets or sets a boolean indicating whether the generated issued token /// should be returned to the client application as part of the response. @@ -1115,6 +1179,19 @@ public static partial class OpenIddictServerEvents /// public ClaimsPrincipal? DeviceCodePrincipal { get; set; } + /// + /// Gets or sets the generated authentication request identifier, if applicable. + /// The identifier will only be returned if + /// is set to . + /// + public string? AuthenticationRequestId { get; set; } + + /// + /// Gets or sets the principal containing the claims that will be + /// used to create the authentication request identifier, if applicable. + /// + public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; } + /// /// Gets or sets the generated issued token, if applicable. /// The issued token will only be returned if diff --git a/src/OpenIddict.Server/OpenIddictServerExtensions.cs b/src/OpenIddict.Server/OpenIddictServerExtensions.cs index ecf195ea..516c3ba4 100644 --- a/src/OpenIddict.Server/OpenIddictServerExtensions.cs +++ b/src/OpenIddict.Server/OpenIddictServerExtensions.cs @@ -30,6 +30,7 @@ public static class OpenIddictServerExtensions builder.Services.AddOptions(); builder.Services.TryAddSingleton(); + builder.Services.TryAddScoped(); // Register the built-in server event handlers used by the OpenIddict server components. // Note: the order used here is not important, as the actual order is set in the options. @@ -53,6 +54,9 @@ 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(); builder.Services.TryAddSingleton(); builder.Services.TryAddSingleton(); diff --git a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs index d13b5333..3d9559de 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs @@ -249,6 +249,48 @@ public static class OpenIddictServerHandlerFilters } } + /// + /// Represents a filter that excludes the associated handlers if no authentication request identifier is generated. + /// + public sealed class RequireAuthenticationRequestIdGenerated : IOpenIddictServerHandlerFilter + { + /// + public ValueTask IsActiveAsync(ProcessSignInContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(context.GenerateAuthenticationRequestId); + } + } + + /// + /// Represents a filter that excludes the associated handlers if no authentication request identifier is validated. + /// + public sealed class RequireAuthenticationRequestIdValidated : IOpenIddictServerHandlerFilter + { + /// + public ValueTask IsActiveAsync(ProcessAuthenticationContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(context.ValidateAuthenticationRequestId); + } + } + + /// + /// Represents a filter that excludes the associated handlers if the request is not a backchannel authentication request. + /// + public sealed class RequireBackchannelAuthenticationRequest : IOpenIddictServerHandlerFilter + { + /// + public ValueTask IsActiveAsync(BaseContext context) + { + ArgumentNullException.ThrowIfNull(context); + + return new(context.EndpointType is OpenIddictServerEndpointType.BackchannelAuthentication); + } + } + /// /// Represents a filter that excludes the associated handlers if the request is not a device request. /// diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs new file mode 100644 index 00000000..1667d563 --- /dev/null +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs @@ -0,0 +1,859 @@ +/* + * 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.Security.Claims; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace OpenIddict.Server; + +public static partial class OpenIddictServerHandlers +{ + public static class Backchannel + { + public static ImmutableArray DefaultHandlers { get; } = + [ + /* + * Backchannel authentication request top-level processing: + */ + ExtractBackchannelAuthenticationRequest.Descriptor, + ValidateBackchannelAuthenticationRequest.Descriptor, + HandleBackchannelAuthenticationRequest.Descriptor, + ApplyBackchannelAuthenticationResponse.Descriptor, + ApplyBackchannelAuthenticationResponse.Descriptor, + ApplyBackchannelAuthenticationResponse.Descriptor, + ApplyBackchannelAuthenticationResponse.Descriptor, + + /* + * Backchannel authentication request validation: + */ + ValidateRequestParameter.Descriptor, + ValidateScopeParameter.Descriptor, + ValidateHintParameters.Descriptor, + ValidateRequestedExpiryParameter.Descriptor, + ValidateClientCredentialsParameters.Descriptor, + ValidateScopes.Descriptor, + ValidateAuthentication.Descriptor, + ValidateEndpointPermissions.Descriptor, + ValidateGrantTypePermissions.Descriptor, + ValidateScopePermissions.Descriptor, + + /* + * Backchannel authentication request handling: + */ + AttachPrincipal.Descriptor + ]; + + /// + /// Contains the logic responsible for extracting backchannel authentication requests and invoking the corresponding event handlers. + /// + public sealed class ExtractBackchannelAuthenticationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ExtractBackchannelAuthenticationRequest(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 ExtractBackchannelAuthenticationRequestContext(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.ID0532)); + } + + context.Logger.LogInformation(6300, SR.GetResourceString(SR.ID6300), notification.Request); + } + } + + /// + /// Contains the logic responsible for validating backchannel authentication requests and invoking the corresponding event handlers. + /// + public sealed class ValidateBackchannelAuthenticationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ValidateBackchannelAuthenticationRequest(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(ExtractBackchannelAuthenticationRequest.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new ValidateBackchannelAuthenticationRequestContext(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 identity token hint principal without triggering a new validation. + context.Transaction.SetProperty(typeof(ValidateBackchannelAuthenticationRequestContext).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(6301, SR.GetResourceString(SR.ID6301)); + } + } + + /// + /// Contains the logic responsible for handling backchannel authentication requests and invoking the corresponding event handlers. + /// + public sealed class HandleBackchannelAuthenticationRequest : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public HandleBackchannelAuthenticationRequest(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(ValidateBackchannelAuthenticationRequest.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new HandleBackchannelAuthenticationRequestContext(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; + } + + // Unlike other endpoints, the backchannel authentication endpoint requires identifying the end user: + // since OpenIddict cannot resolve the user from the hints itself, a principal MUST be attached by + // the application (typically using the pass-through mode or a custom event handler). + if (notification.Principal is not { Identity.IsAuthenticated: true } principal || + string.IsNullOrEmpty(principal.GetClaim(Claims.Subject))) + { + throw new InvalidOperationException(SR.GetResourceString(SR.ID0531)); + } + + var @event = new ProcessSignInContext(context.Transaction) + { + Principal = principal, + Response = new OpenIddictResponse() + }; + + if (notification.Parameters.Count is > 0) + { + foreach (var parameter in notification.Parameters) + { + @event.Parameters.Add(parameter.Key, parameter.Value); + } + } + + 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.InvalidGrant, + description: @event.ErrorDescription, + uri: @event.ErrorUri); + return; + } + } + } + + /// + /// Contains the logic responsible for processing backchannel authentication responses and invoking the corresponding event handlers. + /// + public sealed class ApplyBackchannelAuthenticationResponse : IOpenIddictServerHandler where TContext : BaseRequestContext + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ApplyBackchannelAuthenticationResponse(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 ApplyBackchannelAuthenticationResponseContext(context.Transaction); + await _dispatcher.DispatchAsync(notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + throw new InvalidOperationException(SR.GetResourceString(SR.ID0533)); + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that specify the unsupported request parameter. + /// + public sealed class ValidateRequestParameter : 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(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // Note: signed authentication requests are not supported yet. + if (!string.IsNullOrEmpty(context.Request.Request)) + { + context.Reject( + error: Errors.RequestNotSupported, + description: SR.FormatID2028(Parameters.Request), + uri: SR.FormatID8000(SR.ID2028)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that don't specify a valid scope parameter. + /// + public sealed class ValidateScopeParameter : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateRequestParameter.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // Backchannel authentication requests MUST contain the "openid" scope. + // + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1. + if (!context.Request.HasScope(Scopes.OpenId)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2215), + uri: SR.FormatID8000(SR.ID2215)); + + return ValueTask.CompletedTask; + } + + // Reject requests that specify scope=offline_access if the refresh token flow is not enabled. + if (context.Request.HasScope(Scopes.OfflineAccess) && !context.Options.GrantTypes.Contains(GrantTypes.RefreshToken)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2035(Scopes.OfflineAccess), + uri: SR.FormatID8000(SR.ID2035)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that don't specify exactly one hint. + /// + public sealed class ValidateHintParameters : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateScopeParameter.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // Backchannel authentication requests MUST contain one and only one of the login_hint_token, + // id_token_hint or login_hint parameters, that are used to identify the end user. + // + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1. + var count = (string.IsNullOrEmpty(context.Request.LoginHint) ? 0 : 1) + + (string.IsNullOrEmpty(context.Request.LoginHintToken) ? 0 : 1) + + (string.IsNullOrEmpty(context.Request.IdTokenHint) ? 0 : 1); + + if (count is not 1) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2214), + uri: SR.FormatID8000(SR.ID2214)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that specify an invalid requested_expiry. + /// + public sealed class ValidateRequestedExpiryParameter : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateHintParameters.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.Request.HasParameter(Parameters.RequestedExpiry) && context.Request.RequestedExpiry is not > 0) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2052(Parameters.RequestedExpiry), + uri: SR.FormatID8000(SR.ID2052)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that specify invalid client credentials parameters. + /// + public sealed class ValidateClientCredentialsParameters : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(ValidateRequestedExpiryParameter.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // Ensure a client_assertion_type is specified when a client_assertion was attached. + if (!string.IsNullOrEmpty(context.Request.ClientAssertion) && + string.IsNullOrEmpty(context.Request.ClientAssertionType)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2037(Parameters.ClientAssertionType, Parameters.ClientAssertion), + uri: SR.FormatID8000(SR.ID2037)); + + return ValueTask.CompletedTask; + } + + // Ensure a client_assertion is specified when a client_assertion_type was attached. + if (string.IsNullOrEmpty(context.Request.ClientAssertion) && + !string.IsNullOrEmpty(context.Request.ClientAssertionType)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2037(Parameters.ClientAssertion, Parameters.ClientAssertionType), + uri: SR.FormatID8000(SR.ID2037)); + + return ValueTask.CompletedTask; + } + + // Reject requests that use multiple client authentication methods. + // + // See https://tools.ietf.org/html/rfc6749#section-2.3 for more information. + if (!string.IsNullOrEmpty(context.Request.ClientAssertion) && + !string.IsNullOrEmpty(context.Request.ClientSecret)) + { + context.Logger.LogInformation(6140, SR.GetResourceString(SR.ID6140)); + + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2087), + uri: SR.FormatID8000(SR.ID2087)); + + return ValueTask.CompletedTask; + } + + // Ensure the specified client_assertion_type is supported. + if (!string.IsNullOrEmpty(context.Request.ClientAssertionType) && + !context.Options.ClientAssertionTypes.Contains(context.Request.ClientAssertionType)) + { + context.Reject( + error: Errors.InvalidClient, + description: SR.FormatID2032(Parameters.ClientAssertionType), + uri: SR.FormatID8000(SR.ID2032)); + + return ValueTask.CompletedTask; + } + + return ValueTask.CompletedTask; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests that use unregistered scopes. + /// Note: this handler partially works with the degraded mode but 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(ValidateClientCredentialsParameters.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + // If all the specified scopes are registered in the options, avoid making a database lookup. + var scopes = context.Request.GetScopes().ToHashSet(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 at least one scope was not recognized, return an error. + if (scopes.Count is not 0) + { + context.Logger.LogInformation(6305, SR.GetResourceString(SR.ID6305), scopes); + + context.Reject( + error: Errors.InvalidScope, + description: SR.FormatID2052(Parameters.Scope), + uri: SR.FormatID8000(SR.ID2052)); + + return; + } + } + } + + /// + /// Contains the logic responsible for applying the authentication logic to backchannel authentication requests. + /// + public sealed class ValidateAuthentication : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ValidateAuthentication(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(ValidateScopes.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + 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.InvalidRequest, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + // Attach the security principal extracted from the identity token hint to the validation context. + context.IdentityTokenHintPrincipal = notification.IdentityTokenPrincipal; + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests made by applications + /// that haven't been granted the backchannel authentication endpoint permission. + /// Note: this handler is not used when the degraded mode is enabled. + /// + public sealed class ValidateEndpointPermissions : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .AddFilter() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ValidateAuthentication.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); + + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); + + if (!await manager.HasPermissionAsync(application, Permissions.Endpoints.BackchannelAuthentication, context.CancellationToken)) + { + context.Logger.LogInformation(6302, SR.GetResourceString(SR.ID6302), context.ClientId); + + context.Reject( + error: Errors.UnauthorizedClient, + description: SR.GetResourceString(SR.ID2217), + uri: SR.FormatID8000(SR.ID2217)); + + return; + } + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests made by unauthorized applications. + /// Note: this handler is not used when the degraded mode is enabled or when grant type permissions are disabled. + /// + public sealed class ValidateGrantTypePermissions : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .AddFilter() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ValidateEndpointPermissions.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); + + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); + + // Reject the request if the application is not allowed to use the CIBA grant. + if (!await manager.HasPermissionAsync(application, Permissions.GrantTypes.Ciba, context.CancellationToken)) + { + context.Logger.LogInformation(6303, SR.GetResourceString(SR.ID6303), context.ClientId); + + context.Reject( + error: Errors.UnauthorizedClient, + description: SR.GetResourceString(SR.ID2218), + uri: SR.FormatID8000(SR.ID2218)); + + return; + } + + // Reject the request if the offline_access scope was request and + // if the application is not allowed to use the refresh token grant. + if (context.Request.HasScope(Scopes.OfflineAccess) && + !await manager.HasPermissionAsync(application, Permissions.GrantTypes.RefreshToken, context.CancellationToken)) + { + context.Logger.LogInformation(6304, SR.GetResourceString(SR.ID6304), context.ClientId, Scopes.OfflineAccess); + + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2065(Scopes.OfflineAccess), + uri: SR.FormatID8000(SR.ID2065)); + + return; + } + } + } + + /// + /// Contains the logic responsible for rejecting backchannel authentication requests made by applications + /// that haven't been granted the appropriate scope permissions. + /// Note: this handler is not used when the degraded mode is enabled. + /// + public sealed class ValidateScopePermissions : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .AddFilter() + .AddFilter() + .UseSingletonHandler() + .SetOrder(ValidateGrantTypePermissions.Descriptor.Order + 1_000) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); + + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); + + foreach (var scope in context.Request.GetScopes()) + { + // Avoid validating the "openid" and "offline_access" scopes as they represent protocol scopes. + if (string.Equals(scope, Scopes.OfflineAccess, StringComparison.Ordinal) || + string.Equals(scope, Scopes.OpenId, StringComparison.Ordinal)) + { + continue; + } + + // Reject the request if the application is not allowed to use the iterated scope. + if (!await manager.HasPermissionAsync(application, Permissions.Prefixes.Scope + scope, context.CancellationToken)) + { + context.Logger.LogInformation(6304, SR.GetResourceString(SR.ID6304), context.ClientId, scope); + + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2051), + uri: SR.FormatID8000(SR.ID2051)); + + return; + } + } + } + } + + /// + /// Contains the logic responsible for attaching the principal + /// extracted from the identity token hint to the event context. + /// + public sealed class AttachPrincipal : 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(HandleBackchannelAuthenticationRequestContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = context.Transaction.GetProperty( + typeof(ValidateBackchannelAuthenticationRequestContext).FullName!) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); + + context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal; + + return ValueTask.CompletedTask; + } + } + } +} diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs index 666460d8..6a262973 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs @@ -238,6 +238,9 @@ public static partial class OpenIddictServerHandlers [Metadata.UserInfoEndpoint] = notification.UserInfoEndpoint?.AbsoluteUri, [Metadata.DeviceAuthorizationEndpoint] = notification.DeviceAuthorizationEndpoint?.AbsoluteUri, [Metadata.PushedAuthorizationRequestEndpoint] = notification.PushedAuthorizationEndpoint?.AbsoluteUri, + [Metadata.BackchannelAuthenticationEndpoint] = notification.BackchannelAuthenticationEndpoint?.AbsoluteUri, + [Metadata.BackchannelTokenDeliveryModesSupported] = notification.BackchannelTokenDeliveryModes.ToImmutableArray(), + [Metadata.BackchannelUserCodeParameterSupported] = notification.BackchannelAuthenticationEndpoint is not null ? false : null, [Metadata.MtlsEndpointAliases] = CreateMtlsEndpointAliases(notification), [Metadata.JwksUri] = notification.JsonWebKeySetEndpoint?.AbsoluteUri, [Metadata.GrantTypesSupported] = notification.GrantTypes.ToImmutableArray(), @@ -407,6 +410,15 @@ public static partial class OpenIddictServerHandlers context.AuthorizationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri( context.BaseUri, context.Options.AuthorizationEndpointUris.FirstOrDefault()); + context.BackchannelAuthenticationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri( + context.BaseUri, context.Options.BackchannelAuthenticationEndpointUris.FirstOrDefault()); + + // Note: OpenIddict only supports the poll delivery mode. + if (context.BackchannelAuthenticationEndpoint is not null) + { + context.BackchannelTokenDeliveryModes.Add(BackchannelTokenDeliveryModes.Poll); + } + context.DeviceAuthorizationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri( context.BaseUri, context.Options.DeviceAuthorizationEndpointUris.FirstOrDefault()); diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs index 845d9b15..aca1e669 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs @@ -413,6 +413,7 @@ public static partial class OpenIddictServerHandlers ArgumentNullException.ThrowIfNull(context); if (!context.Request.IsAuthorizationCodeGrantType() && + !context.Request.IsCibaGrantType() && !context.Request.IsClientCredentialsGrantType() && !context.Request.IsDeviceCodeGrantType()) { @@ -608,6 +609,18 @@ public static partial class OpenIddictServerHandlers return ValueTask.CompletedTask; } + // Reject grant_type=urn:openid:params:grant-type:ciba requests missing the authentication request identifier. + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.1. + if (context.Request.IsCibaGrantType() && string.IsNullOrEmpty(context.Request.AuthReqId)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2216(Parameters.AuthReqId), + uri: SR.FormatID8000(SR.ID2216)); + + return ValueTask.CompletedTask; + } + return ValueTask.CompletedTask; } } @@ -885,6 +898,7 @@ public static partial class OpenIddictServerHandlers // // For more information, see https://tools.ietf.org/html/rfc6749#section-6. if (!string.IsNullOrEmpty(context.Request.Scope) && (context.Request.IsAuthorizationCodeGrantType() || + context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType())) { context.Logger.LogInformation(6094, SR.GetResourceString(SR.ID6094), Parameters.Scope); @@ -929,6 +943,7 @@ public static partial class OpenIddictServerHandlers // Prevent audiences parameters from being attached to token requests that don't use the // OAuth 2.0 Token Exchange grant type, unless the specified grant type is a custom value. if (context.Request.IsAuthorizationCodeGrantType() || context.Request.IsClientCredentialsGrantType() || + context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType() || context.Request.IsImplicitFlow() || context.Request.IsPasswordGrantType() || context.Request.IsRefreshTokenGrantType()) { @@ -1214,6 +1229,7 @@ public static partial class OpenIddictServerHandlers context.ActorTokenPrincipal = notification.ActorTokenPrincipal; context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal; context.DeviceCodePrincipal = notification.DeviceCodePrincipal; + context.AuthenticationRequestIdPrincipal = notification.AuthenticationRequestIdPrincipal; context.RefreshTokenPrincipal = notification.RefreshTokenPrincipal; context.SubjectTokenPrincipal = notification.SubjectTokenPrincipal; } @@ -1570,12 +1586,14 @@ public static partial class OpenIddictServerHandlers ArgumentNullException.ThrowIfNull(context); if (context.Request.IsAuthorizationCodeGrantType() || + context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType() || context.Request.IsRefreshTokenGrantType()) { var principal = context.Request.GrantType switch { GrantTypes.AuthorizationCode => context.AuthorizationCodePrincipal, + GrantTypes.Ciba => context.AuthenticationRequestIdPrincipal, GrantTypes.DeviceCode => context.DeviceCodePrincipal, GrantTypes.RefreshToken => context.RefreshTokenPrincipal, @@ -1593,7 +1611,7 @@ public static partial class OpenIddictServerHandlers throw new InvalidOperationException(SR.GetResourceString(SR.ID0043)); } - if (context.Request.IsDeviceCodeGrantType()) + if (context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType()) { throw new InvalidOperationException(SR.GetResourceString(SR.ID0044)); } @@ -2082,6 +2100,7 @@ public static partial class OpenIddictServerHandlers ArgumentNullException.ThrowIfNull(context); if (!context.Request.IsAuthorizationCodeGrantType() && + !context.Request.IsCibaGrantType() && !context.Request.IsDeviceCodeGrantType() && !context.Request.IsRefreshTokenGrantType() && !context.Request.IsTokenExchangeGrantType()) @@ -2094,6 +2113,7 @@ public static partial class OpenIddictServerHandlers ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); context.ActorTokenPrincipal = notification.ActorTokenPrincipal; + context.AuthenticationRequestIdPrincipal = notification.AuthenticationRequestIdPrincipal; context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal; context.DeviceCodePrincipal = notification.DeviceCodePrincipal; context.RefreshTokenPrincipal = notification.RefreshTokenPrincipal; @@ -2104,6 +2124,7 @@ public static partial class OpenIddictServerHandlers context.Principal ??= context.Request.GrantType switch { GrantTypes.AuthorizationCode => notification.AuthorizationCodePrincipal, + GrantTypes.Ciba => notification.AuthenticationRequestIdPrincipal, GrantTypes.DeviceCode => notification.DeviceCodePrincipal, GrantTypes.RefreshToken => notification.RefreshTokenPrincipal, @@ -2150,6 +2171,7 @@ public static partial class OpenIddictServerHandlers // If the error indicates an invalid token, return a standard invalid_grant. if (context.Request is null || !(context.Request.IsAuthorizationCodeGrantType() || + context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType() || context.Request.IsRefreshTokenGrantType() || context.Request.IsTokenExchangeGrantType())) @@ -2162,6 +2184,9 @@ public static partial class OpenIddictServerHandlers // Keep "expired_token" errors as-is if the request is a device code token request. Errors.ExpiredToken when context.Request.IsDeviceCodeGrantType() => Errors.ExpiredToken, + // Similarly, keep "expired_token" errors as-is if the request is a CIBA token request. + Errors.ExpiredToken when context.Request.IsCibaGrantType() => Errors.ExpiredToken, + // Convert "invalid_token" errors to "invalid_grant". Errors.InvalidToken => Errors.InvalidGrant, diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs index 74973ba7..c0a28dda 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs @@ -13,6 +13,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; +using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -257,6 +258,9 @@ public static partial class OpenIddictServerHandlers // For device codes, only the short "oi_dvc+jwt" form is valid. TokenTypeIdentifiers.Private.DeviceCode => [JsonWebTokenTypes.Private.DeviceCode], + // For authentication request identifiers, only the short "oi_arid+jwt" form is valid. + TokenTypeIdentifiers.Private.AuthenticationRequestId => [JsonWebTokenTypes.Private.AuthenticationRequestId], + // For refresh tokens, only the short "oi_reft+jwt" form is valid. TokenTypeIdentifiers.RefreshToken => [JsonWebTokenTypes.Private.RefreshToken], @@ -585,6 +589,7 @@ public static partial class OpenIddictServerHandlers JsonWebTokenTypes.Private.AuthorizationCode => TokenTypeIdentifiers.Private.AuthorizationCode, JsonWebTokenTypes.Private.DeviceCode => TokenTypeIdentifiers.Private.DeviceCode, + JsonWebTokenTypes.Private.AuthenticationRequestId => TokenTypeIdentifiers.Private.AuthenticationRequestId, JsonWebTokenTypes.Private.RefreshToken => TokenTypeIdentifiers.RefreshToken, JsonWebTokenTypes.Private.RequestToken => TokenTypeIdentifiers.Private.RequestToken, JsonWebTokenTypes.Private.UserCode => TokenTypeIdentifiers.Private.UserCode, @@ -984,6 +989,7 @@ public static partial class OpenIddictServerHandlers { TokenTypeIdentifiers.Private.ClientAssertion => Errors.InvalidClient, TokenTypeIdentifiers.Private.DeviceCode => Errors.ExpiredToken, + TokenTypeIdentifiers.Private.AuthenticationRequestId => Errors.ExpiredToken, _ => Errors.InvalidToken }, description: context.Principal.GetTokenType() switch @@ -1298,6 +1304,24 @@ public static partial class OpenIddictServerHandlers // If the token is not marked as valid yet, return an authorization_pending error. if (await manager.HasStatusAsync(token, Statuses.Inactive, context.CancellationToken)) { + // If a polling interval was configured, return a slow_down error if the client + // application polls the token endpoint more frequently than what is allowed. + if (context.EndpointType is OpenIddictServerEndpointType.Token && + context.Options.PollingInterval is TimeSpan interval && + context.Principal.GetTokenType() is TokenTypeIdentifiers.Private.AuthenticationRequestId or + TokenTypeIdentifiers.Private.DeviceCode && + !await TryUpdatePollingDateAsync(token, interval)) + { + context.Logger.LogInformation(6299, SR.GetResourceString(SR.ID6299), context.TokenId); + + context.Reject( + error: Errors.SlowDown, + description: SR.GetResourceString(SR.ID2213), + uri: SR.FormatID8000(SR.ID2213)); + + return; + } + context.Logger.LogInformation(6003, SR.GetResourceString(SR.ID6003), context.TokenId); context.Reject( @@ -1352,6 +1376,40 @@ public static partial class OpenIddictServerHandlers return; } + async ValueTask TryUpdatePollingDateAsync(object token, TimeSpan interval) + { + var now = context.Options.TimeProvider.GetUtcNow(); + + var properties = await manager.GetPropertiesAsync(token, context.CancellationToken); + if (properties.TryGetValue(Properties.LastPollingDate, out JsonElement element) && + element.ValueKind is JsonValueKind.Number && element.TryGetInt64(out long value) && + now < DateTimeOffset.FromUnixTimeSeconds(value) + interval) + { + return false; + } + + var descriptor = new OpenIddictTokenDescriptor(); + await manager.PopulateAsync(descriptor, token, context.CancellationToken); + + using var document = JsonDocument.Parse(now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)); + descriptor.Properties[Properties.LastPollingDate] = document.RootElement.Clone(); + + try + { + await manager.UpdateAsync(token, descriptor, context.CancellationToken); + } + + // If the entry was concurrently updated (e.g because the client application sent concurrent polling + // requests or because the end user approved the demand at the same time), consider the request as + // too frequent: a subsequent polling request will be able to retrieve the updated token entry. + catch (OpenIddictExceptions.ConcurrencyException) + { + return false; + } + + return true; + } + async ValueTask IsReusableAsync(object token) { // If the reuse leeway was set to null, return false to indicate @@ -1568,6 +1626,10 @@ public static partial class OpenIddictServerHandlers // corresponding the user, which allows the client to redeem the device code. TokenTypeIdentifiers.Private.DeviceCode => Statuses.Inactive, + // Similarly, authentication request identifiers are marked as inactive until the end user + // approves the backchannel authentication request using the OpenIddict server service. + TokenTypeIdentifiers.Private.AuthenticationRequestId => Statuses.Inactive, + // For all other tokens, "valid" is the default status. _ => Statuses.Valid }; @@ -1737,6 +1799,7 @@ public static partial class OpenIddictServerHandlers // For authorization/device/user codes and refresh tokens, // attach claims destinations to the JWT claims collection. if (context.TokenType is TokenTypeIdentifiers.Private.AuthorizationCode or TokenTypeIdentifiers.Private.DeviceCode or + TokenTypeIdentifiers.Private.AuthenticationRequestId or TokenTypeIdentifiers.RefreshToken or TokenTypeIdentifiers.Private.UserCode or TokenTypeIdentifiers.Private.RequestToken) { @@ -1758,6 +1821,7 @@ public static partial class OpenIddictServerHandlers TokenTypeIdentifiers.AccessToken => JsonWebTokenTypes.AccessToken, TokenTypeIdentifiers.Private.AuthorizationCode => JsonWebTokenTypes.Private.AuthorizationCode, TokenTypeIdentifiers.Private.DeviceCode => JsonWebTokenTypes.Private.DeviceCode, + TokenTypeIdentifiers.Private.AuthenticationRequestId => JsonWebTokenTypes.Private.AuthenticationRequestId, TokenTypeIdentifiers.IdentityToken => JsonWebTokenTypes.GenericJsonWebToken, TokenTypeIdentifiers.RefreshToken => JsonWebTokenTypes.Private.RefreshToken, TokenTypeIdentifiers.Private.RequestToken => JsonWebTokenTypes.Private.RequestToken, diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs index da72dcb0..ca09c680 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.cs @@ -56,6 +56,7 @@ public static partial class OpenIddictServerHandlers ValidateAccessToken.Descriptor, ValidateAuthorizationCode.Descriptor, ValidateDeviceCode.Descriptor, + ValidateAuthenticationRequestId.Descriptor, ValidateGenericToken.Descriptor, ValidateIdentityToken.Descriptor, ValidateRefreshToken.Descriptor, @@ -91,6 +92,7 @@ public static partial class OpenIddictServerHandlers PrepareAccessTokenPrincipal.Descriptor, PrepareAuthorizationCodePrincipal.Descriptor, PrepareDeviceCodePrincipal.Descriptor, + PrepareAuthenticationRequestIdPrincipal.Descriptor, PrepareIssuedTokenPrincipal.Descriptor, PrepareRequestTokenPrincipal.Descriptor, PrepareRefreshTokenPrincipal.Descriptor, @@ -100,6 +102,7 @@ public static partial class OpenIddictServerHandlers GenerateAccessToken.Descriptor, GenerateAuthorizationCode.Descriptor, GenerateDeviceCode.Descriptor, + GenerateAuthenticationRequestId.Descriptor, GenerateIssuedToken.Descriptor, GenerateRequestToken.Descriptor, GenerateRefreshToken.Descriptor, @@ -130,6 +133,7 @@ public static partial class OpenIddictServerHandlers AttachCustomErrorParameters.Descriptor, .. Authentication.DefaultHandlers, + .. Backchannel.DefaultHandlers, .. Device.DefaultHandlers, .. Discovery.DefaultHandlers, .. Exchange.DefaultHandlers, @@ -168,6 +172,7 @@ public static partial class OpenIddictServerHandlers context.EndpointType = Matches(context.Options.AuthorizationEndpointUris) ? OpenIddictServerEndpointType.Authorization : + Matches(context.Options.BackchannelAuthenticationEndpointUris) ? OpenIddictServerEndpointType.BackchannelAuthentication : Matches(context.Options.ConfigurationEndpointUris) ? OpenIddictServerEndpointType.Configuration : Matches(context.Options.DeviceAuthorizationEndpointUris) ? OpenIddictServerEndpointType.DeviceAuthorization : Matches(context.Options.EndSessionEndpointUris) ? OpenIddictServerEndpointType.EndSession : @@ -258,7 +263,7 @@ 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 + OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.BackchannelAuthentication => default, _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0002)), @@ -309,6 +314,18 @@ public static partial class OpenIddictServerHandlers _ => (false, false, false, false) }; + (context.ExtractAuthenticationRequestId, + context.RequireAuthenticationRequestId, + context.ValidateAuthenticationRequestId, + context.RejectAuthenticationRequestId) = context.EndpointType switch + { + // The CIBA grant requires sending a valid authentication request identifier. + OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType() + => (true, true, true, true), + + _ => (false, false, false, false) + }; + (context.ExtractAuthorizationCode, context.RequireAuthorizationCode, context.ValidateAuthorizationCode, @@ -331,7 +348,7 @@ public static partial class OpenIddictServerHandlers // present and invalid client assertions are always automatically rejected by OpenIddict. OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or - OpenIddictServerEndpointType.Token + OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication => (true, false, true, true), _ => (false, false, false, false) @@ -377,6 +394,10 @@ public static partial class OpenIddictServerHandlers OpenIddictServerEndpointType.PushedAuthorization => (true, false, true, false), + // Identity token hints received by the backchannel authentication endpoint are used to + // identify the end user and invalid hints always cause the request to be rejected. + OpenIddictServerEndpointType.BackchannelAuthentication => (true, false, true, true), + _ => (false, false, false, false) }; @@ -468,6 +489,14 @@ public static partial class OpenIddictServerHandlers _ => (null, null) }; + context.AuthenticationRequestId = context.EndpointType switch + { + OpenIddictServerEndpointType.Token when context.ExtractAuthenticationRequestId + => context.Request.AuthReqId, + + _ => null + }; + context.AuthorizationCode = context.EndpointType switch { OpenIddictServerEndpointType.Token when context.ExtractAuthorizationCode @@ -480,7 +509,7 @@ public static partial class OpenIddictServerHandlers { OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or - OpenIddictServerEndpointType.Token + OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication when context.ExtractClientAssertion => (context.Request.ClientAssertion, context.Request.ClientAssertionType), @@ -506,8 +535,9 @@ public static partial class OpenIddictServerHandlers context.IdentityToken = context.EndpointType switch { - OpenIddictServerEndpointType.Authorization or - OpenIddictServerEndpointType.EndSession or + OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or + OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.PushedAuthorization when context.ExtractIdentityToken => context.Request.IdTokenHint, @@ -583,6 +613,7 @@ public static partial class OpenIddictServerHandlers if ((context.RequireAccessToken && string.IsNullOrEmpty(context.AccessToken)) || (context.RequireActorToken && string.IsNullOrEmpty(context.ActorToken)) || + (context.RequireAuthenticationRequestId && string.IsNullOrEmpty(context.AuthenticationRequestId)) || (context.RequireAuthorizationCode && string.IsNullOrEmpty(context.AuthorizationCode)) || (context.RequireClientAssertion && string.IsNullOrEmpty(context.ClientAssertion)) || (context.RequireDeviceCode && string.IsNullOrEmpty(context.DeviceCode)) || @@ -961,6 +992,7 @@ public static partial class OpenIddictServerHandlers // never allow anonymous clients, even if the corresponding option is enabled. case OpenIddictServerEndpointType.Token when context.Options.AcceptAnonymousClients && !context.Request.IsAuthorizationCodeGrantType() && + !context.Request.IsCibaGrantType() && !context.Request.IsClientCredentialsGrantType() && !context.Request.IsDeviceCodeGrantType(): return; @@ -1009,7 +1041,7 @@ public static partial class OpenIddictServerHandlers // For non-interactive endpoints, return "invalid_client" instead of "invalid_request". OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or - OpenIddictServerEndpointType.Token + OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication => Errors.InvalidClient, _ => Errors.InvalidRequest @@ -1773,6 +1805,81 @@ public static partial class OpenIddictServerHandlers } } + /// + /// Contains the logic responsible for validating the authentication request identifier resolved from the context. + /// + public sealed class ValidateAuthenticationRequestId : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public ValidateAuthenticationRequestId(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(ValidateDeviceCode.Descriptor.Order + 500) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessAuthenticationContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (string.IsNullOrEmpty(context.AuthenticationRequestId)) + { + return; + } + + var notification = new ValidateTokenContext(context.Transaction) + { + DisableAudienceValidation = true, + Token = context.AuthenticationRequestId, + ValidTokenTypes = { TokenTypeIdentifiers.Private.AuthenticationRequestId } + }; + + if (!string.IsNullOrEmpty(context.ClientId)) + { + notification.ValidPresenters.Add(context.ClientId); + } + + await _dispatcher.DispatchAsync(notification); + + if (notification.IsRequestHandled) + { + context.HandleRequest(); + return; + } + + if (notification.IsRequestSkipped) + { + context.SkipRequest(); + return; + } + + if (notification.IsRejected) + { + if (context.RejectAuthenticationRequestId) + { + context.Reject( + error: notification.Error ?? Errors.InvalidRequest, + description: notification.ErrorDescription, + uri: notification.ErrorUri); + return; + } + + return; + } + + context.AuthenticationRequestIdPrincipal = notification.Principal; + } + } + /// /// Contains the logic responsible for validating tokens of unknown types resolved from the context. /// @@ -1905,10 +2012,12 @@ public static partial class OpenIddictServerHandlers // Audience and presenter validation is disabled for the authorization and end session endpoints // as these endpoints implement specialized event handlers that use more complex rules. DisableAudienceValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.PushedAuthorization, // Don't validate the lifetime of identity token used as hints. DisableLifetimeValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.PushedAuthorization, DisablePresenterValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or @@ -2498,8 +2607,9 @@ public static partial class OpenIddictServerHandlers context.Response.Error ??= context.EndpointType switch { - OpenIddictServerEndpointType.Authorization or - OpenIddictServerEndpointType.EndUserVerification or + OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or + OpenIddictServerEndpointType.EndUserVerification or OpenIddictServerEndpointType.PushedAuthorization => Errors.AccessDenied, @@ -2511,8 +2621,9 @@ public static partial class OpenIddictServerHandlers context.Response.ErrorDescription ??= context.EndpointType switch { - OpenIddictServerEndpointType.Authorization or - OpenIddictServerEndpointType.EndUserVerification or + OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or + OpenIddictServerEndpointType.EndUserVerification or OpenIddictServerEndpointType.PushedAuthorization => SR.GetResourceString(SR.ID2015), @@ -2524,8 +2635,9 @@ public static partial class OpenIddictServerHandlers context.Response.ErrorUri ??= context.EndpointType switch { - OpenIddictServerEndpointType.Authorization or - OpenIddictServerEndpointType.EndUserVerification or + OpenIddictServerEndpointType.Authorization or + OpenIddictServerEndpointType.BackchannelAuthentication or + OpenIddictServerEndpointType.EndUserVerification or OpenIddictServerEndpointType.PushedAuthorization => SR.FormatID8000(SR.ID2015), @@ -2734,6 +2846,7 @@ public static partial class OpenIddictServerHandlers break; case OpenIddictServerEndpointType.Authorization: + case OpenIddictServerEndpointType.BackchannelAuthentication: case OpenIddictServerEndpointType.EndUserVerification: case OpenIddictServerEndpointType.Token: if (context.Principal is not { Identity: ClaimsIdentity }) @@ -2769,7 +2882,8 @@ public static partial class OpenIddictServerHandlers { // The following claims MUST be represented as unique strings. Claims.AuthenticationContextReference or Claims.Subject or - Claims.Private.AuthorizationId or Claims.Private.CreationDate or + Claims.Private.AuthorizationId or Claims.Private.BindingMessage or + Claims.Private.CreationDate or Claims.Private.DeviceCodeId or Claims.Private.ExpirationDate or Claims.Private.SessionId or Claims.Private.TokenId => values is [{ ValueType: ClaimValueTypes.String }], @@ -2798,6 +2912,7 @@ public static partial class OpenIddictServerHandlers // The following claims MUST be represented as unique integers. Claims.Private.AccessTokenLifetime or Claims.Private.AuthorizationCodeLifetime or + Claims.Private.AuthenticationRequestIdLifetime or Claims.Private.DeviceCodeLifetime or Claims.Private.IdentityTokenLifetime or Claims.Private.RefreshTokenLifetime or Claims.Private.RefreshTokenLifetime or Claims.Private.RequestTokenLifetime @@ -2854,6 +2969,7 @@ public static partial class OpenIddictServerHandlers case OpenIddictServerEndpointType.Authorization: case OpenIddictServerEndpointType.EndUserVerification: case OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType(): + case OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType(): case OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType(): case OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType() && !context.Options.DisableRollingRefreshTokens: @@ -2873,6 +2989,9 @@ public static partial class OpenIddictServerHandlers OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType() => notification.AuthorizationCodePrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType() + => notification.AuthenticationRequestIdPrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType() => notification.DeviceCodePrincipal, @@ -2965,6 +3084,7 @@ public static partial class OpenIddictServerHandlers { case OpenIddictServerEndpointType.EndUserVerification: case OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType(): + case OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType(): case OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType(): case OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType(): break; @@ -2985,6 +3105,9 @@ public static partial class OpenIddictServerHandlers OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType() => notification.AuthorizationCodePrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType() + => notification.AuthenticationRequestIdPrincipal, + OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType() => notification.DeviceCodePrincipal, @@ -3200,6 +3323,14 @@ public static partial class OpenIddictServerHandlers _ => (false, false) }; + (context.GenerateAuthenticationRequestId, context.IncludeAuthenticationRequestId) = context.EndpointType switch + { + // For backchannel authentication requests, always generate and return an authentication request identifier. + OpenIddictServerEndpointType.BackchannelAuthentication => (true, true), + + _ => (false, false) + }; + (context.GenerateAuthorizationCode, context.IncludeAuthorizationCode) = context.EndpointType switch { // Never generate an authorization code if request caching was enabled and the authorization @@ -3762,6 +3893,105 @@ public static partial class OpenIddictServerHandlers } } + /// + /// Contains the logic responsible for preparing and attaching the claims principal used + /// to generate the authentication request identifier, if one is going to be returned. + /// + public sealed class PrepareAuthenticationRequestIdPrincipal : IOpenIddictServerHandler + { + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictServerHandlerDescriptor Descriptor { get; } + = OpenIddictServerHandlerDescriptor.CreateBuilder() + .AddFilter() + .UseSingletonHandler() + .SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 500) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessSignInContext context) + { + ArgumentNullException.ThrowIfNull(context); + + Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); + + // Create a new principal containing only the filtered claims. + // Actors identities are also filtered (delegation scenarios). + var principal = context.Principal.Clone(claim => + { + // Never include the the following claims to ensure they are not inherited from the parent token: + if (string.Equals(claim.Type, Claims.JwtId, StringComparison.OrdinalIgnoreCase) || + string.Equals(claim.Type, Claims.Private.TokenId, StringComparison.OrdinalIgnoreCase) || + string.Equals(claim.Type, Claims.ExpiresAt, StringComparison.OrdinalIgnoreCase) || + string.Equals(claim.Type, Claims.IssuedAt, StringComparison.OrdinalIgnoreCase) || + string.Equals(claim.Type, Claims.NotBefore, StringComparison.OrdinalIgnoreCase) || + string.Equals(claim.Type, Claims.Confirmation, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // Other claims are always included in the authentication request identifier, even private claims. + return true; + }); + + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); + + // If a specific token lifetime was attached to the principal, prefer it over any other value. + var lifetime = context.Principal.GetAuthenticationRequestIdLifetime(); + + // If the client to which the token is returned is known, use the attached setting if available. + if (lifetime is null && !context.Options.EnableDegradedMode && !string.IsNullOrEmpty(context.ClientId)) + { + var manager = context.ServiceProvider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken) + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); + + var settings = await manager.GetSettingsAsync(application, context.CancellationToken); + if (settings.TryGetValue(Settings.TokenLifetimes.AuthenticationRequestId, out string? setting) && + TimeSpan.TryParse(setting, CultureInfo.InvariantCulture, out var value)) + { + lifetime = value; + } + } + + // Otherwise, fall back to the global value. + lifetime ??= context.Options.AuthenticationRequestIdLifetime; + + // If the client application requested a shorter expiration, honor it. + if (context.Request.RequestedExpiry is > 0 and long expiry && + (lifetime is null || TimeSpan.FromSeconds(expiry) < lifetime)) + { + lifetime = TimeSpan.FromSeconds(expiry); + } + + if (lifetime is not null) + { + principal.SetExpirationDate(principal.GetCreationDate() + lifetime.Value); + } + + // Use the server identity as the token issuer. + principal.SetClaim(Claims.Private.Issuer, (context.Options.Issuer ?? context.BaseUri) switch + { + { IsAbsoluteUri: true } uri => uri.AbsoluteUri, + + // Throw an exception if the issuer cannot be retrieved or is not valid. + _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0496)) + }); + + // Store the binding message so that it can be displayed to the end user when approving the request. + if (!string.IsNullOrEmpty(context.Request.BindingMessage)) + { + principal.SetClaim(Claims.Private.BindingMessage, context.Request.BindingMessage); + } + + context.AuthenticationRequestIdPrincipal = principal; + } + } + /// /// Contains the logic responsible for preparing and attaching the claims principal /// used to generate the issued token, if one is going to be returned. @@ -4733,6 +4963,72 @@ public static partial class OpenIddictServerHandlers } } + /// + /// Contains the logic responsible for generating an authentication request identifier for the current sign-in operation. + /// + public sealed class GenerateAuthenticationRequestId : IOpenIddictServerHandler + { + private readonly IOpenIddictServerDispatcher _dispatcher; + + public GenerateAuthenticationRequestId(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(GenerateDeviceCode.Descriptor.Order + 500) + .SetType(OpenIddictServerHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessSignInContext context) + { + ArgumentNullException.ThrowIfNull(context); + + var notification = new GenerateTokenContext(context.Transaction) + { + ClientId = context.ClientId, + CreateTokenEntry = !context.Options.DisableTokenStorage, + // Note: authentication request identifiers are always reference tokens so that + // their payload can be replaced when the end user approves the authentication request. + IsReferenceToken = !context.Options.DisableTokenStorage, + PersistTokenPayload = !context.Options.DisableTokenStorage, + Principal = context.AuthenticationRequestIdPrincipal!, + TokenFormat = TokenFormats.Private.JsonWebToken, + TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId + }; + + 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; + } + + context.AuthenticationRequestId = notification.Token; + } + } + /// /// Contains the logic responsible for generating an issued token for the current sign-in operation. /// @@ -5388,6 +5684,11 @@ public static partial class OpenIddictServerHandlers } } + if (context.IncludeAuthenticationRequestId) + { + context.Response.AuthReqId = context.AuthenticationRequestId; + } + if (context.IncludeAuthorizationCode) { context.Response.Code = context.AuthorizationCode; @@ -5482,6 +5783,33 @@ public static partial class OpenIddictServerHandlers // parameter is required in device authorization responses. _ => 5 * 60 // 5 minutes, in seconds. }; + + // If a polling interval was configured, return it to the client application. + if (context.Options.PollingInterval is TimeSpan interval) + { + context.Response.Interval = (long) Math.Ceiling(interval.TotalSeconds); + } + } + + else if (context.EndpointType is OpenIddictServerEndpointType.BackchannelAuthentication) + { + context.Response.ExpiresIn = context.AuthenticationRequestIdPrincipal?.GetExpirationDate() switch + { + // If an expiration date was set on the authentication request + // identifier principal, return it to the client application. + DateTimeOffset date when date > context.Options.TimeProvider.GetUtcNow() + => (long) ((date - context.Options.TimeProvider.GetUtcNow()).TotalSeconds + .5), + + // Otherwise, return an arbitrary value, as the "expires_in" + // parameter is required in backchannel authentication responses. + _ => 5 * 60 // 5 minutes, in seconds. + }; + + // If a polling interval was configured, return it to the client application. + if (context.Options.PollingInterval is TimeSpan interval) + { + context.Response.Interval = (long) Math.Ceiling(interval.TotalSeconds); + } } else if (context.EndpointType is OpenIddictServerEndpointType.PushedAuthorization) diff --git a/src/OpenIddict.Server/OpenIddictServerOptions.cs b/src/OpenIddict.Server/OpenIddictServerOptions.cs index b717ff88..3b111c02 100644 --- a/src/OpenIddict.Server/OpenIddictServerOptions.cs +++ b/src/OpenIddict.Server/OpenIddictServerOptions.cs @@ -63,6 +63,11 @@ public sealed class OpenIddictServerOptions /// public List AuthorizationEndpointUris { get; } = []; + /// + /// Gets the absolute and relative URIs associated to the backchannel authentication endpoint. + /// + public List BackchannelAuthenticationEndpointUris { get; } = []; + /// /// Gets the absolute and relative URIs associated to the configuration endpoint. /// @@ -251,6 +256,21 @@ public sealed class OpenIddictServerOptions /// public TimeSpan? AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1); + /// + /// Gets or sets the period of time authentication request identifiers (auth_req_id) returned by the backchannel + /// authentication endpoint remain valid after being issued. The default value is 5 minutes. While not recommended, + /// this property can be set to to issue authentication request identifiers that never expire. + /// + public TimeSpan? AuthenticationRequestIdLifetime { get; set; } = TimeSpan.FromMinutes(5); + + /// + /// Gets or sets the minimum period of time client applications must wait between two polling token requests made + /// using the device code or the Client-Initiated Backchannel Authentication grants. The default value is 5 seconds. + /// Token requests sent before this period has elapsed are rejected with a "slow_down" error. If this property is + /// set to , the polling interval is neither returned to the client nor enforced. + /// + public TimeSpan? PollingInterval { get; set; } = TimeSpan.FromSeconds(5); + /// /// Gets or sets the period of time device codes remain valid after being issued. The default value is 10 minutes. /// The client application is expected to start a whole new authentication flow after the device code has expired. diff --git a/src/OpenIddict.Server/OpenIddictServerService.cs b/src/OpenIddict.Server/OpenIddictServerService.cs new file mode 100644 index 00000000..b258eb2f --- /dev/null +++ b/src/OpenIddict.Server/OpenIddictServerService.cs @@ -0,0 +1,329 @@ +/* + * 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.Runtime.CompilerServices; +using System.Security.Claims; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; +using static OpenIddict.Abstractions.OpenIddictExceptions; + +namespace OpenIddict.Server; + +/// +/// Provides high-level APIs for performing server-side operations that are not tied to an HTTP request, +/// like completing Client-Initiated Backchannel Authentication (CIBA) requests once approved by the end user. +/// +public class OpenIddictServerService +{ + private readonly IServiceProvider _provider; + + /// + /// Creates a new instance of the class. + /// + /// The service provider. + public OpenIddictServerService(IServiceProvider provider) + => _provider = provider ?? throw new ArgumentNullException(nameof(provider)); + + /// + /// Lists the pending backchannel authentication requests associated with the specified subject. + /// + /// The subject (typically, the user identifier). + /// The that can be used to abort the operation. + /// The pending backchannel authentication requests. + public virtual IAsyncEnumerable ListPendingBackchannelAuthenticationRequestsAsync( + string subject, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(subject); + + var options = _provider.GetRequiredService>().CurrentValue; + var manager = _provider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + return ExecuteAsync(cancellationToken); + + async IAsyncEnumerable ExecuteAsync( + [EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var token in manager.FindBySubjectAsync(subject, cancellationToken)) + { + var request = await GetPendingRequestAsync(options, manager, token, cancellationToken); + if (request is not null) + { + yield return request; + } + } + } + } + + /// + /// Retrieves the pending backchannel authentication request corresponding to the specified identifier. + /// + /// The identifier of the backchannel authentication request. + /// The that can be used to abort the operation. + /// The pending request or if no pending request corresponds to the identifier. + public virtual async ValueTask GetPendingBackchannelAuthenticationRequestAsync( + string identifier, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(identifier); + + var options = _provider.GetRequiredService>().CurrentValue; + var manager = _provider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + return await manager.FindByIdAsync(identifier, cancellationToken) switch + { + object token => await GetPendingRequestAsync(options, manager, token, cancellationToken), + null => null + }; + } + + /// + /// Approves the specified backchannel authentication request, which allows the client application + /// to redeem the authentication request identifier using the CIBA grant. + /// + /// The identifier of the backchannel authentication request. + /// + /// The principal used to create the tokens returned to the client application. If this parameter + /// is , the principal attached to the backchannel authentication request is used. + /// The principal must contain the same subject as the one attached to the backchannel authentication request. + /// + /// The that can be used to abort the operation. + /// + /// if the request was approved, if it was not found, + /// is no longer pending or was concurrently updated (in which case, the operation can be retried). + /// + public virtual async ValueTask ApproveBackchannelAuthenticationRequestAsync( + string identifier, ClaimsPrincipal? principal = null, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(identifier); + + var options = _provider.GetRequiredService>().CurrentValue; + var manager = _provider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var token = await manager.FindByIdAsync(identifier, cancellationToken); + if (token is null || await GetPendingRequestAsync(options, manager, token, cancellationToken) is not { } request) + { + return false; + } + + principal ??= request.Principal; + + if (principal is not { Identity.IsAuthenticated: true } || + !string.Equals(principal.GetClaim(Claims.Subject), request.Subject, StringComparison.Ordinal)) + { + throw new InvalidOperationException(SR.GetResourceString(SR.ID0534)); + } + + // Create a new principal containing only the filtered claims. + var result = principal.Clone(static claim => + !string.Equals(claim.Type, Claims.JwtId, StringComparison.OrdinalIgnoreCase) && + !string.Equals(claim.Type, Claims.Private.TokenId, StringComparison.OrdinalIgnoreCase) && + !string.Equals(claim.Type, Claims.ExpiresAt, StringComparison.OrdinalIgnoreCase) && + !string.Equals(claim.Type, Claims.IssuedAt, StringComparison.OrdinalIgnoreCase) && + !string.Equals(claim.Type, Claims.NotBefore, StringComparison.OrdinalIgnoreCase) && + !string.Equals(claim.Type, Claims.Confirmation, StringComparison.OrdinalIgnoreCase)); + + // Restore the internal claims (e.g presenters or scopes) attached to the initial request, unless overridden. + foreach (var claims in request.Principal.Claims + .Where(static claim => claim.Type.StartsWith(Claims.Prefixes.Private, StringComparison.Ordinal)) + .GroupBy(static claim => claim.Type, StringComparer.Ordinal)) + { + if (!result.HasClaim(claims.Key) && result.Identity is ClaimsIdentity identity) + { + identity.AddClaims(claims); + } + } + + result.SetCreationDate(request.CreationDate ?? options.TimeProvider.GetUtcNow()) + .SetExpirationDate(request.ExpirationDate) + .SetTokenId(identifier) + .SetClaim(Claims.Private.Issuer, (options.Issuer ?? throw new InvalidOperationException( + SR.GetResourceString(SR.ID0529))).AbsoluteUri); + + var transaction = new OpenIddictServerTransaction + { + CancellationToken = cancellationToken, + Options = options, + ServiceProvider = _provider + }; + + var context = new OpenIddictServerEvents.GenerateTokenContext(transaction) + { + ClientId = request.ClientId, + CreateTokenEntry = false, + IsReferenceToken = false, + PersistTokenPayload = false, + Principal = result, + TokenFormat = TokenFormats.Private.JsonWebToken, + TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId + }; + + await _provider.GetRequiredService().DispatchAsync(context); + + if (context.IsRejected || string.IsNullOrEmpty(context.Token)) + { + throw new InvalidOperationException(SR.FormatID0535(context.Error, context.ErrorDescription)); + } + + var descriptor = new OpenIddictTokenDescriptor(); + await manager.PopulateAsync(descriptor, token, cancellationToken); + + descriptor.Payload = context.Token; + descriptor.Principal = result; + descriptor.Status = Statuses.Valid; + descriptor.Subject = request.Subject; + + try + { + await manager.UpdateAsync(token, descriptor, cancellationToken); + } + + catch (ConcurrencyException) + { + return false; + } + + return true; + } + + /// + /// Rejects the specified backchannel authentication request, which causes the + /// token requests sent by the client application to be rejected with an access_denied error. + /// + /// The identifier of the backchannel authentication request. + /// The that can be used to abort the operation. + /// if the request was rejected, otherwise. + public virtual async ValueTask RejectBackchannelAuthenticationRequestAsync( + string identifier, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(identifier); + + var options = _provider.GetRequiredService>().CurrentValue; + var manager = _provider.GetService() + ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); + + var token = await manager.FindByIdAsync(identifier, cancellationToken); + if (token is null || await GetPendingRequestAsync(options, manager, token, cancellationToken) is null) + { + return false; + } + + return await manager.TryRejectAsync(token, cancellationToken); + } + + private static async ValueTask GetPendingRequestAsync( + OpenIddictServerOptions options, IOpenIddictTokenManager manager, object token, CancellationToken cancellationToken) + { + if (!await manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, cancellationToken) || + !await manager.HasStatusAsync(token, Statuses.Inactive, cancellationToken)) + { + return null; + } + + var date = await manager.GetExpirationDateAsync(token, cancellationToken); + if (date is not null && date < options.TimeProvider.GetUtcNow()) + { + return null; + } + + var payload = await manager.GetPayloadAsync(token, cancellationToken); + if (string.IsNullOrEmpty(payload)) + { + return null; + } + + // Note: the payload is validated using the server token validation parameters (and not using the generic + // token validation pipeline) to avoid rejecting the token because its status is still marked as inactive. + var parameters = options.TokenValidationParameters.Clone(); + parameters.ValidateLifetime = false; + parameters.ValidIssuer = options.Issuer?.AbsoluteUri; + parameters.ValidateIssuer = parameters.ValidIssuer is not null; + parameters.ValidTypes = [JsonWebTokenTypes.Private.AuthenticationRequestId]; + + var result = await options.JsonWebTokenHandler.ValidateTokenAsync(payload, parameters); + if (!result.IsValid) + { + return null; + } + + var principal = new ClaimsPrincipal(result.ClaimsIdentity); + + // Restore the claim destinations from the special oi_cl_dstn claim (represented as a dictionary/JSON object). + var jwt = (JsonWebToken) result.SecurityToken; + if ((jwt.InnerToken ?? jwt).TryGetPayloadValue(Claims.Private.ClaimDestinationsMap, out Dictionary destinations)) + { + var builder = ImmutableDictionary.CreateBuilder>(StringComparer.Ordinal); + + foreach (var destination in destinations) + { + builder.Add(destination.Key, [.. destination.Value]); + } + + principal.SetDestinations(builder.ToImmutable()); + } + + return new OpenIddictServerBackchannelAuthenticationRequest + { + BindingMessage = principal.GetClaim(Claims.Private.BindingMessage), + ClientId = principal.GetPresenters().FirstOrDefault(), + CreationDate = await manager.GetCreationDateAsync(token, cancellationToken), + ExpirationDate = date, + Identifier = (await manager.GetIdAsync(token, cancellationToken))!, + Principal = principal, + Scopes = principal.GetScopes(), + Subject = principal.GetClaim(Claims.Subject) + }; + } +} + +/// +/// Represents a pending backchannel authentication request. +/// +public sealed class OpenIddictServerBackchannelAuthenticationRequest +{ + /// + /// Gets the binding message specified by the client application, if applicable. + /// + public string? BindingMessage { get; init; } + + /// + /// Gets the identifier of the client application that initiated the request. + /// + public string? ClientId { get; init; } + + /// + /// Gets the creation date of the request. + /// + public DateTimeOffset? CreationDate { get; init; } + + /// + /// Gets the expiration date of the request. + /// + public DateTimeOffset? ExpirationDate { get; init; } + + /// + /// Gets the identifier of the request. + /// + public required string Identifier { get; init; } + + /// + /// Gets the principal attached to the request. + /// + public required ClaimsPrincipal Principal { get; init; } + + /// + /// Gets the scopes requested by the client application. + /// + public ImmutableArray Scopes { get; init; } = []; + + /// + /// Gets the subject of the end user. + /// + public string? Subject { get; init; } +} diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs new file mode 100644 index 00000000..bbac58ff --- /dev/null +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs @@ -0,0 +1,521 @@ +/* + * 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.Net.Http; +using System.Security.Claims; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using OpenIddict.Core; +using Xunit; +using static OpenIddict.Server.OpenIddictServerEvents; +using static OpenIddict.Server.OpenIddictServerHandlers.Protection; + +namespace OpenIddict.Server.IntegrationTests; + +public abstract partial class OpenIddictServerIntegrationTests +{ + [Theory] + [InlineData(nameof(HttpMethod.Delete))] + [InlineData(nameof(HttpMethod.Get))] + [InlineData(nameof(HttpMethod.Head))] + [InlineData(nameof(HttpMethod.Options))] + [InlineData(nameof(HttpMethod.Put))] + [InlineData(nameof(HttpMethod.Trace))] + public async Task ExtractBackchannelAuthenticationRequest_UnexpectedMethodReturnsAnError(string method) + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.SendAsync(method, "/connect/ciba", new OpenIddictRequest()); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2084), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2084), response.ErrorUri); + } + + [Fact] + public async Task ValidateBackchannelAuthenticationRequest_MissingOpenIdScopeCausesAnError() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + LoginHint = "bob@fabrikam.com", + Scope = Scopes.Profile + }); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2215), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2215), response.ErrorUri); + } + + [Theory] + [InlineData(null, null, null)] + [InlineData("bob@fabrikam.com", "token", null)] + [InlineData("bob@fabrikam.com", null, "id_token")] + [InlineData(null, "token", "id_token")] + public async Task ValidateBackchannelAuthenticationRequest_InvalidHintsCauseAnError(string? hint, string? token, string? identity) + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + IdTokenHint = identity, + LoginHint = hint, + LoginHintToken = token, + Scope = Scopes.OpenId + }); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2214), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2214), response.ErrorUri); + } + + [Theory] + [InlineData("0")] + [InlineData("-10")] + [InlineData("value")] + public async Task ValidateBackchannelAuthenticationRequest_InvalidRequestedExpiryCausesAnError(string expiry) + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + LoginHint = "bob@fabrikam.com", + Scope = Scopes.OpenId, + [Parameters.RequestedExpiry] = expiry + }); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.FormatID2052(Parameters.RequestedExpiry), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2052), response.ErrorUri); + } + + [Fact] + public async Task ValidateBackchannelAuthenticationRequest_RequestParameterCausesAnError() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + Request = "eyJhbGciOiJub25lIn0.e30.", + Scope = Scopes.OpenId + }); + + // Assert + Assert.Equal(Errors.RequestNotSupported, response.Error); + Assert.Equal(SR.FormatID2028(Parameters.Request), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2028), response.ErrorUri); + } + + [Fact] + public async Task ValidateBackchannelAuthenticationRequest_MissingClientIdCausesAnError() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + LoginHint = "bob@fabrikam.com", + Scope = Scopes.OpenId + }); + + // Assert + Assert.Equal(Errors.InvalidClient, response.Error); + Assert.Equal(SR.FormatID2029(Parameters.ClientId), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2029), response.ErrorUri); + } + + [Fact] + public async Task HandleBackchannelAuthenticationRequest_ThrowsAnExceptionWhenNoPrincipalIsAttached() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act and assert + var exception = await Assert.ThrowsAsync(async () => + { + await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + LoginHint = "bob@fabrikam.com", + Scope = Scopes.OpenId + }); + }); + + Assert.Equal(SR.GetResourceString(SR.ID0531), exception.Message); + } + + [Fact] + public async Task HandleBackchannelAuthenticationRequest_AllowsRejectingRequest() + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureBackchannelAuthentication(options); + + options.AddEventHandler(builder => + builder.UseInlineHandler(context => + { + context.Reject(Errors.UnknownUserId, "The user is unknown."); + + return ValueTask.CompletedTask; + })); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + LoginHint = "bob@fabrikam.com", + Scope = Scopes.OpenId + }); + + // Assert + Assert.Equal(Errors.UnknownUserId, response.Error); + Assert.Equal("The user is unknown.", response.ErrorDescription); + } + + [Fact] + public async Task HandleBackchannelAuthenticationRequest_ReturnsAuthenticationRequestIdentifier() + { + // Arrange + var token = new OpenIddictToken(); + OpenIddictTokenDescriptor? created = null; + + await using var server = await CreateServerAsync(options => + { + ConfigureBackchannelAuthentication(options); + + options.Services.AddSingleton(CreateTokenManager(mock => + { + mock.Setup(manager => manager.CreateAsync(It.IsAny(), It.IsAny())) + .Callback((OpenIddictTokenDescriptor descriptor, CancellationToken _) => created = descriptor) + .ReturnsAsync(token); + + mock.Setup(manager => manager.GetIdAsync(token, It.IsAny())) + .ReturnsAsync("3E228451-1555-46F7-A471-951EFBA23A56"); + + mock.Setup(manager => manager.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny())) + .ReturnsAsync(token); + })); + + options.AddEventHandler(builder => + builder.UseInlineHandler(context => + { + Assert.Equal("bob@fabrikam.com", context.Request.LoginHint); + + context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob le Magnifique"); + + return ValueTask.CompletedTask; + })); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + BindingMessage = "W4SCT", + ClientId = "Fabrikam", + LoginHint = "bob@fabrikam.com", + RequestedExpiry = 120, + Scope = Scopes.OpenId + }); + + // Assert + Assert.Null(response.Error); + Assert.NotNull(response.AuthReqId); + Assert.InRange(response.ExpiresIn ?? 0, 115, 120); + Assert.Equal(5, response.Interval); + + Assert.NotNull(created); + Assert.Equal(Statuses.Inactive, created.Status); + Assert.Equal("Bob le Magnifique", created.Subject); + Assert.Equal(TokenTypeIdentifiers.Private.AuthenticationRequestId, created.Type); + Assert.Equal("W4SCT", created.Principal?.GetClaim(Claims.Private.BindingMessage)); + } + + [Fact] + public async Task ValidateTokenRequest_MissingAuthenticationRequestIdCausesAnError() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + ClientId = "Fabrikam", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.FormatID2216(Parameters.AuthReqId), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2216), response.ErrorUri); + } + + [Fact] + public async Task ValidateTokenRequest_MissingClientIdCausesAnErrorForCibaRequests() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.FormatID2029(Parameters.ClientId), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2029), response.ErrorUri); + } + + [Theory] + [InlineData(null, Errors.AuthorizationPending)] + [InlineData(-60, Errors.AuthorizationPending)] + [InlineData(-2, Errors.SlowDown)] + public async Task ValidateTokenRequest_PendingAuthenticationRequestCausesAnError(int? lastPolling, string error) + { + // Arrange + var token = new OpenIddictToken(); + var properties = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal); + + if (lastPolling is not null) + { + properties.Add(Properties.LastPollingDate, JsonSerializer.SerializeToElement( + (TimeProvider.System.GetUtcNow() + TimeSpan.FromSeconds(lastPolling.Value)).ToUnixTimeSeconds())); + } + + var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive, properties.ToImmutable()); + + await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager)); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", + ClientId = "Fabrikam", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(error, response.Error); + + Mock.Get(manager).Verify(manager => manager.UpdateAsync(token, It.IsAny(), It.IsAny()), + error is Errors.SlowDown ? Times.Never() : Times.Once()); + } + + [Fact] + public async Task ValidateTokenRequest_PollingIntervalIsNotEnforcedWhenDisabled() + { + // Arrange + var token = new OpenIddictToken(); + var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive, + ImmutableDictionary.Create(StringComparer.Ordinal)); + + await using var server = await CreateServerAsync(options => + { + ConfigureAuthenticationRequestValidation(options, manager); + options.SetPollingInterval(null); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", + ClientId = "Fabrikam", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(Errors.AuthorizationPending, response.Error); + + Mock.Get(manager).Verify(manager => manager.GetPropertiesAsync(token, It.IsAny()), Times.Never()); + } + + [Fact] + public async Task ValidateTokenRequest_RejectedAuthenticationRequestCausesAnAccessDeniedError() + { + // Arrange + var token = new OpenIddictToken(); + var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Rejected, + ImmutableDictionary.Create(StringComparer.Ordinal)); + + await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager)); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", + ClientId = "Fabrikam", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(Errors.AccessDenied, response.Error); + } + + [Fact] + public async Task ValidateTokenRequest_ExpiredAuthenticationRequestCausesAnExpiredTokenError() + { + // Arrange + var token = new OpenIddictToken(); + var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive, + ImmutableDictionary.Create(StringComparer.Ordinal), + expiration: TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)); + + await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager)); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", + ClientId = "Fabrikam", + GrantType = GrantTypes.Ciba + }); + + // Assert + Assert.Equal(Errors.ExpiredToken, response.Error); + } + + [Fact] + public async Task HandleConfigurationRequest_BackchannelAuthenticationMetadataIsReturned() + { + // Arrange + await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication); + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.GetAsync("/.well-known/openid-configuration"); + + // Assert + Assert.Equal("http://localhost/connect/ciba", (string?) response[Metadata.BackchannelAuthenticationEndpoint]); + Assert.Equal([BackchannelTokenDeliveryModes.Poll], (ImmutableArray?) response[Metadata.BackchannelTokenDeliveryModesSupported]); + Assert.False((bool) response[Metadata.BackchannelUserCodeParameterSupported]); + Assert.Contains(GrantTypes.Ciba, (ImmutableArray?) response[Metadata.GrantTypesSupported] ?? [], StringComparer.Ordinal); + } + + private void ConfigureBackchannelAuthentication(OpenIddictServerBuilder options) + { + options.SetBackchannelAuthenticationEndpointUris("/connect/ciba") + .AllowClientInitiatedBackchannelAuthenticationFlow() + .SetIssuer(new Uri("https://www.contoso.com/", UriKind.Absolute)); + + options.DisableAuthorizationStorage(); + + options.Services.AddSingleton(CreateApplicationManager(mock => + { + var application = new OpenIddictApplication(); + + mock.Setup(manager => manager.FindByClientIdAsync("Fabrikam", It.IsAny())) + .ReturnsAsync(application); + + mock.Setup(manager => manager.HasClientTypeAsync(application, ClientTypes.Public, It.IsAny())) + .ReturnsAsync(true); + + mock.Setup(manager => manager.GetSettingsAsync(application, It.IsAny())) + .ReturnsAsync(ImmutableDictionary.Create(StringComparer.Ordinal)); + })); + } + + private void ConfigureAuthenticationRequestValidation(OpenIddictServerBuilder options, OpenIddictTokenManager manager) + { + ConfigureBackchannelAuthentication(options); + + options.AddEventHandler(builder => + { + builder.UseInlineHandler(context => + { + Assert.Equal([TokenTypeIdentifiers.Private.AuthenticationRequestId], context.ValidTokenTypes); + + context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob le Magnifique") + .SetPresenters("Fabrikam") + .SetTokenId("60FFF7EA-F98E-437B-937E-5073CC313103") + .SetTokenType(TokenTypeIdentifiers.Private.AuthenticationRequestId); + + return ValueTask.CompletedTask; + }); + + builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500); + }); + + options.Services.AddSingleton(manager); + } + + private OpenIddictTokenManager CreateAuthenticationRequestTokenManager( + OpenIddictToken token, string status, ImmutableDictionary properties, DateTimeOffset? expiration = null) + => CreateTokenManager(mock => + { + mock.Setup(manager => manager.FindByReferenceIdAsync("8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", It.IsAny())) + .ReturnsAsync(token); + + mock.Setup(manager => manager.GetTypeAsync(token, It.IsAny())) + .ReturnsAsync(TokenTypeIdentifiers.Private.AuthenticationRequestId); + + mock.Setup(manager => manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, It.IsAny())) + .ReturnsAsync(true); + + mock.Setup(manager => manager.GetIdAsync(token, It.IsAny())) + .ReturnsAsync("60FFF7EA-F98E-437B-937E-5073CC313103"); + + mock.Setup(manager => manager.GetPayloadAsync(token, It.IsAny())) + .ReturnsAsync("payload"); + + mock.Setup(manager => manager.FindByIdAsync("60FFF7EA-F98E-437B-937E-5073CC313103", It.IsAny())) + .ReturnsAsync(token); + + mock.Setup(manager => manager.GetExpirationDateAsync(token, It.IsAny())) + .ReturnsAsync(expiration ?? TimeProvider.System.GetUtcNow() + TimeSpan.FromMinutes(5)); + + mock.Setup(manager => manager.HasStatusAsync(token, It.IsAny(), It.IsAny())) + .ReturnsAsync((object _, string value, CancellationToken _) => string.Equals(value, status, StringComparison.Ordinal)); + + mock.Setup(manager => manager.GetPropertiesAsync(token, It.IsAny())) + .ReturnsAsync(properties); + }); +} diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs index beec36ed..18955e2c 100644 --- a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs +++ b/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs @@ -1870,6 +1870,82 @@ public class OpenIddictServerBuilderTests Assert.True(options.RequireSignedRequestObjects); } + [Fact] + public void AllowClientInitiatedBackchannelAuthenticationFlow_CibaGrantIsAdded() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.AllowClientInitiatedBackchannelAuthenticationFlow(); + + var options = GetOptions(services); + + // Assert + Assert.Contains(GrantTypes.Ciba, options.GrantTypes); + } + + [Fact] + public void AllowCustomFlow_ThrowsAnExceptionForCibaGrant() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act and assert + var exception = Assert.Throws(() => builder.AllowCustomFlow(GrantTypes.Ciba)); + Assert.Equal("type", exception.ParamName); + } + + [Fact] + public void SetBackchannelAuthenticationEndpointUris_AddsUris() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.SetBackchannelAuthenticationEndpointUris("http://localhost/endpoint-path"); + + var options = GetOptions(services); + + // Assert + Assert.Contains(new Uri("http://localhost/endpoint-path"), options.BackchannelAuthenticationEndpointUris); + } + + [Fact] + public void SetAuthenticationRequestIdLifetime_LifetimeIsReplaced() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.SetAuthenticationRequestIdLifetime(TimeSpan.FromMinutes(42)); + + var options = GetOptions(services); + + // Assert + Assert.Equal(TimeSpan.FromMinutes(42), options.AuthenticationRequestIdLifetime); + } + + [Fact] + public void SetPollingInterval_IntervalIsReplaced() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.SetPollingInterval(null); + + var options = GetOptions(services); + + // Assert + Assert.Null(options.PollingInterval); + } + [Fact] public void EnableRequestObjectSupport_RequestObjectSupportIsEnabled() { diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs index 1c1b5377..1f2d4390 100644 --- a/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs +++ b/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs @@ -249,6 +249,58 @@ public class OpenIddictServerConfigurationTests Assert.Contains(SR.GetResourceString(SR.ID0079), result.Failures!, StringComparer.Ordinal); } + [Fact] + public void Validate_ReturnsAnErrorWhenBackchannelAuthenticationEndpointIsMissingForCibaGrant() + { + // Arrange + var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var options = CreateBaseOptions(); + options.GrantTypes.Add(GrantTypes.Ciba); + + // Act + var result = configuration.Validate(name: null, options); + + // Assert + Assert.Contains(SR.GetResourceString(SR.ID0527), result.Failures!, StringComparer.Ordinal); + } + + [Fact] + public void Validate_ReturnsAnErrorWhenCibaGrantIsMissingForBackchannelAuthenticationEndpoint() + { + // Arrange + var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var options = CreateBaseOptions(); + options.BackchannelAuthenticationEndpointUris.Add(new Uri("connect/ciba", UriKind.Relative)); + + // Act + var result = configuration.Validate(name: null, options); + + // Assert + Assert.Contains(SR.GetResourceString(SR.ID0528), result.Failures!, StringComparer.Ordinal); + } + + [Theory] + [InlineData(true, false, true)] + [InlineData(false, true, true)] + [InlineData(false, false, false)] + public void Validate_ReturnsAnErrorWhenCibaGrantIsUsedWithIncompatibleSettings(bool degraded, bool storage, bool issuer) + { + // Arrange + var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var options = CreateBaseOptions(); + options.GrantTypes.Add(GrantTypes.Ciba); + options.BackchannelAuthenticationEndpointUris.Add(new Uri("connect/ciba", UriKind.Relative)); + options.EnableDegradedMode = degraded; + options.DisableTokenStorage = storage; + options.Issuer = issuer ? new Uri("https://www.contoso.com/", UriKind.Absolute) : null; + + // Act + var result = configuration.Validate(name: null, options); + + // Assert + Assert.Contains(SR.GetResourceString(SR.ID0529), result.Failures!, StringComparer.Ordinal); + } + [Fact] public void Validate_ReturnsAnErrorWhenSignedRequestObjectsAreRequiredWithoutRequestObjectSupport() { diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerServiceTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerServiceTests.cs new file mode 100644 index 00000000..b1931283 --- /dev/null +++ b/test/OpenIddict.Server.Tests/OpenIddictServerServiceTests.cs @@ -0,0 +1,243 @@ +using System.Security.Claims; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; +using Moq; +using Xunit; +using static OpenIddict.Abstractions.OpenIddictExceptions; +using static OpenIddict.Server.OpenIddictServerEvents; + +namespace OpenIddict.Server.Tests; + +public class OpenIddictServerServiceTests +{ + private const string Identifier = "3E228451-1555-46F7-A471-951EFBA23A56"; + + [Fact] + public async Task ListPendingBackchannelAuthenticationRequestsAsync_ReturnsPendingRequests() + { + // Arrange + var token = new object(); + var (provider, _) = await CreateProviderAsync(token, Statuses.Inactive); + var service = provider.GetRequiredService(); + + // Act + var requests = new List(); + await foreach (var request in service.ListPendingBackchannelAuthenticationRequestsAsync("Bob")) + { + requests.Add(request); + } + + // Assert + var result = Assert.Single(requests); + Assert.Equal(Identifier, result.Identifier); + Assert.Equal("Fabrikam", result.ClientId); + Assert.Equal("W4SCT", result.BindingMessage); + Assert.Equal("Bob", result.Subject); + Assert.Equal([Scopes.OpenId, Scopes.Profile], result.Scopes.ToArray()); + } + + [Theory] + [InlineData(Statuses.Valid)] + [InlineData(Statuses.Rejected)] + [InlineData(Statuses.Redeemed)] + public async Task GetPendingBackchannelAuthenticationRequestAsync_ReturnsNullForNonPendingRequests(string status) + { + // Arrange + var token = new object(); + var (provider, _) = await CreateProviderAsync(token, status); + var service = provider.GetRequiredService(); + + // Act and assert + Assert.Null(await service.GetPendingBackchannelAuthenticationRequestAsync(Identifier)); + } + + [Fact] + public async Task ApproveBackchannelAuthenticationRequestAsync_UpdatesTokenEntry() + { + // Arrange + var token = new object(); + var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive); + var service = provider.GetRequiredService(); + + OpenIddictTokenDescriptor? descriptor = null; + manager.Setup(manager => manager.UpdateAsync(token, It.IsAny(), It.IsAny())) + .Callback((object _, OpenIddictTokenDescriptor value, CancellationToken _) => descriptor = value) + .Returns(ValueTask.CompletedTask); + + var principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob") + .SetClaim(Claims.Name, "Bob le Bricoleur"); + + // Act + var result = await service.ApproveBackchannelAuthenticationRequestAsync(Identifier, principal); + + // Assert + Assert.True(result); + Assert.NotNull(descriptor); + Assert.Equal(Statuses.Valid, descriptor.Status); + Assert.Equal("Bob", descriptor.Subject); + Assert.NotNull(descriptor.Payload); + + var options = provider.GetRequiredService>().CurrentValue; + var parameters = options.TokenValidationParameters.Clone(); + parameters.ValidIssuer = "https://www.contoso.com/"; + + var validation = await options.JsonWebTokenHandler.ValidateTokenAsync(descriptor.Payload, parameters); + Assert.True(validation.IsValid, validation.Exception?.Message); + + var approved = new ClaimsPrincipal(validation.ClaimsIdentity); + Assert.Equal("Bob le Bricoleur", approved.GetClaim(Claims.Name)); + Assert.Equal(Identifier, approved.GetTokenId()); + Assert.Equal("W4SCT", approved.GetClaim(Claims.Private.BindingMessage)); + Assert.True(approved.HasPresenter("Fabrikam")); + } + + [Fact] + public async Task ApproveBackchannelAuthenticationRequestAsync_ThrowsAnExceptionForDifferentSubject() + { + // Arrange + var token = new object(); + var (provider, _) = await CreateProviderAsync(token, Statuses.Inactive); + var service = provider.GetRequiredService(); + + var principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")).SetClaim(Claims.Subject, "Alice"); + + // Act and assert + var exception = await Assert.ThrowsAsync( + async () => await service.ApproveBackchannelAuthenticationRequestAsync(Identifier, principal)); + + Assert.Equal(SR.GetResourceString(SR.ID0534), exception.Message); + } + + [Fact] + public async Task ApproveBackchannelAuthenticationRequestAsync_ReturnsFalseForConcurrentUpdates() + { + // Arrange + var token = new object(); + var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive); + var service = provider.GetRequiredService(); + + manager.Setup(manager => manager.UpdateAsync(token, It.IsAny(), It.IsAny())) + .Returns(ValueTask.FromException(new ConcurrencyException("concurrency"))); + + // Act and assert + Assert.False(await service.ApproveBackchannelAuthenticationRequestAsync(Identifier)); + } + + [Fact] + public async Task ApproveBackchannelAuthenticationRequestAsync_ReturnsFalseForNonPendingRequests() + { + // Arrange + var token = new object(); + var (provider, manager) = await CreateProviderAsync(token, Statuses.Valid); + var service = provider.GetRequiredService(); + + // Act and assert + Assert.False(await service.ApproveBackchannelAuthenticationRequestAsync(Identifier)); + + manager.Verify(manager => manager.UpdateAsync(token, It.IsAny(), It.IsAny()), Times.Never()); + } + + [Fact] + public async Task RejectBackchannelAuthenticationRequestAsync_RejectsTokenEntry() + { + // Arrange + var token = new object(); + var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive); + var service = provider.GetRequiredService(); + + manager.Setup(manager => manager.TryRejectAsync(token, It.IsAny())) + .ReturnsAsync(true); + + // Act and assert + Assert.True(await service.RejectBackchannelAuthenticationRequestAsync(Identifier)); + + manager.Verify(manager => manager.TryRejectAsync(token, It.IsAny()), Times.Once()); + } + + private static async Task<(ServiceProvider Provider, Mock Manager)> CreateProviderAsync(object token, string status) + { + var manager = new Mock(); + + var services = new ServiceCollection(); + services.AddSingleton(manager.Object); + + services.AddOpenIddict() + .AddServer(options => + { + options.SetTokenEndpointUris("connect/token") + .SetBackchannelAuthenticationEndpointUris("connect/ciba") + .AllowClientInitiatedBackchannelAuthenticationFlow() + .SetIssuer(new Uri("https://www.contoso.com/", UriKind.Absolute)); + + options.AddEphemeralEncryptionKey() + .AddEphemeralSigningKey(); + + options.DisableAuthorizationStorage(); + }); + + var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().CurrentValue; + + // Generate the payload of the pending authentication request using the server token generation pipeline. + var context = new GenerateTokenContext(new OpenIddictServerTransaction + { + CancellationToken = CancellationToken.None, + Options = options, + ServiceProvider = provider + }) + { + ClientId = "Fabrikam", + CreateTokenEntry = false, + IsReferenceToken = false, + PersistTokenPayload = false, + Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob") + .SetClaim(Claims.Private.BindingMessage, "W4SCT") + .SetClaim(Claims.Private.Issuer, "https://www.contoso.com/") + .SetPresenters("Fabrikam") + .SetScopes(Scopes.OpenId, Scopes.Profile) + .SetTokenId(Identifier), + TokenFormat = TokenFormats.Private.JsonWebToken, + TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId + }; + + await provider.GetRequiredService().DispatchAsync(context); + Assert.False(string.IsNullOrEmpty(context.Token)); + Assert.True(new JsonWebTokenHandler().CanReadToken(context.Token)); + + manager.Setup(manager => manager.FindByIdAsync(Identifier, It.IsAny())) + .ReturnsAsync(token); + + manager.Setup(manager => manager.FindBySubjectAsync("Bob", It.IsAny())) + .Returns(ListAsync()); + + manager.Setup(manager => manager.GetIdAsync(token, It.IsAny())) + .ReturnsAsync(Identifier); + + manager.Setup(manager => manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, It.IsAny())) + .ReturnsAsync(true); + + manager.Setup(manager => manager.HasStatusAsync(token, It.IsAny(), It.IsAny())) + .ReturnsAsync((object _, string value, CancellationToken _) => string.Equals(value, status, StringComparison.Ordinal)); + + manager.Setup(manager => manager.GetExpirationDateAsync(token, It.IsAny())) + .ReturnsAsync(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(5)); + + manager.Setup(manager => manager.GetCreationDateAsync(token, It.IsAny())) + .ReturnsAsync(DateTimeOffset.UtcNow); + + manager.Setup(manager => manager.GetPayloadAsync(token, It.IsAny())) + .ReturnsAsync(context.Token); + + return (provider, manager); + + async IAsyncEnumerable ListAsync() + { + await Task.Yield(); + yield return token; + } + } +}