diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index 7f6c6360..54601b09 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -1821,6 +1821,36 @@ To attach it, enable the pass-through mode or register a custom event handler fo
The authentication request identifier could not be generated: {0} ({1}).
+
+ An authentication request identifier must be specified when using the Client-Initiated Backchannel Authentication grant.
+
+
+ An error occurred while preparing the backchannel authentication request.
+ Error: {0}
+ Error description: {1}
+ Error URI: {2}
+
+
+ An error occurred while sending the backchannel authentication request.
+ Error: {0}
+ Error description: {1}
+ Error URI: {2}
+
+
+ An error occurred while extracting the backchannel authentication response.
+ Error: {0}
+ Error description: {1}
+ Error URI: {2}
+
+
+ An error occurred while handling the backchannel authentication response.
+ Error: {0}
+ Error description: {1}
+ Error URI: {2}
+
+
+ Exactly one of the login hint, login hint token or identity token hint must be specified when using the Client-Initiated Backchannel Authentication grant.
+
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()'.
@@ -2485,6 +2515,9 @@ To apply backchannel authentication responses, create a class implementing 'IOpe
The client application is not allowed to use the Client-Initiated Backchannel Authentication flow.
+
+ The backchannel authentication request was rejected by the remote server.
+
The '{0}' parameter shouldn't be null or empty at this point.
@@ -3373,6 +3406,15 @@ This may indicate that the hashed entry is corrupted or malformed.
The backchannel authentication request was rejected because invalid scopes were specified: {Scopes}.
+
+ The backchannel authentication request was rejected by the remote authorization server: {Response}.
+
+
+ The backchannel authentication request was successfully sent to {Uri}: {Request}.
+
+
+ The backchannel authentication response returned by {Uri} was successfully extracted: {Response}.
+
https://documentation.openiddict.com/errors/{0}
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Backchannel.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Backchannel.cs
new file mode 100644
index 00000000..4b1192a7
--- /dev/null
+++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.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.Client.SystemNetHttp;
+
+public static partial class OpenIddictClientSystemNetHttpHandlers
+{
+ public static class Backchannel
+ {
+ public static ImmutableArray DefaultHandlers { get; } =
+ [
+ /*
+ * Backchannel authentication request processing:
+ */
+ CreateHttpClient.Descriptor,
+ PreparePostHttpRequest.Descriptor,
+ AttachHttpVersion.Descriptor,
+ AttachJsonAcceptHeaders.Descriptor,
+ AttachUserAgentHeader.Descriptor,
+ AttachFromHeader.Descriptor,
+ AttachBasicAuthenticationCredentials.Descriptor,
+ AttachHttpParameters.Descriptor,
+ SendHttpRequest.Descriptor,
+ DisposeHttpRequest.Descriptor,
+
+ /*
+ * Backchannel authentication response processing:
+ */
+ DecompressResponseContent.Descriptor,
+ ExtractJsonHttpResponse.Descriptor,
+ ExtractWwwAuthenticateHeader.Descriptor,
+ ValidateHttpResponse.Descriptor,
+ DisposeHttpResponse.Descriptor
+ ];
+ }
+}
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
index f47dc1b7..b39d9549 100644
--- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
+++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
@@ -24,6 +24,7 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
public static ImmutableArray DefaultHandlers { get; } =
[
.. Authorization.DefaultHandlers,
+ .. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
diff --git a/src/OpenIddict.Client/OpenIddictClientBuilder.cs b/src/OpenIddict.Client/OpenIddictClientBuilder.cs
index fca89337..2c9d4b36 100644
--- a/src/OpenIddict.Client/OpenIddictClientBuilder.cs
+++ b/src/OpenIddict.Client/OpenIddictClientBuilder.cs
@@ -945,6 +945,15 @@ public sealed class OpenIddictClientBuilder
public OpenIddictClientBuilder 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 OpenIddictClientBuilder AllowClientInitiatedBackchannelAuthenticationFlow()
+ => Configure(options => options.GrantTypes.Add(GrantTypes.Ciba));
+
///
/// Enables hybrid flow support. For more information
/// about this specific OpenID Connect flow, visit
diff --git a/src/OpenIddict.Client/OpenIddictClientEvents.Backchannel.cs b/src/OpenIddict.Client/OpenIddictClientEvents.Backchannel.cs
new file mode 100644
index 00000000..07adeac7
--- /dev/null
+++ b/src/OpenIddict.Client/OpenIddictClientEvents.Backchannel.cs
@@ -0,0 +1,123 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+namespace OpenIddict.Client;
+
+public static partial class OpenIddictClientEvents
+{
+ ///
+ /// Represents an event called for each request to the backchannel authentication endpoint
+ /// to give the user code a chance to add parameters to the backchannel authentication request.
+ ///
+ public sealed class PrepareBackchannelAuthenticationRequestContext : BaseExternalContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public PrepareBackchannelAuthenticationRequestContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the request.
+ ///
+ public OpenIddictRequest Request
+ {
+ get => Transaction.Request!;
+ set => Transaction.Request = value;
+ }
+ }
+
+ ///
+ /// Represents an event called for each request to the backchannel authentication endpoint
+ /// to send the backchannel authentication request to the remote authorization server.
+ ///
+ public sealed class ApplyBackchannelAuthenticationRequestContext : BaseExternalContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public ApplyBackchannelAuthenticationRequestContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the request.
+ ///
+ public OpenIddictRequest Request
+ {
+ get => Transaction.Request!;
+ set => Transaction.Request = value;
+ }
+ }
+
+ ///
+ /// Represents an event called for each backchannel authentication response
+ /// to extract the response parameters from the server response.
+ ///
+ public sealed class ExtractBackchannelAuthenticationResponseContext : BaseExternalContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public ExtractBackchannelAuthenticationResponseContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the request.
+ ///
+ public OpenIddictRequest Request
+ {
+ get => Transaction.Request!;
+ set => Transaction.Request = value;
+ }
+
+ ///
+ /// Gets or sets the response, or if it wasn't extracted yet.
+ ///
+ public OpenIddictResponse? Response
+ {
+ get => Transaction.Response;
+ set => Transaction.Response = value;
+ }
+ }
+
+ ///
+ /// Represents an event called for each backchannel authentication response.
+ ///
+ public sealed class HandleBackchannelAuthenticationResponseContext : BaseExternalContext
+ {
+ ///
+ /// Creates a new instance of the class.
+ ///
+ public HandleBackchannelAuthenticationResponseContext(OpenIddictClientTransaction transaction)
+ : base(transaction)
+ {
+ }
+
+ ///
+ /// Gets or sets the request.
+ ///
+ 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;
+ }
+ }
+}
diff --git a/src/OpenIddict.Client/OpenIddictClientEvents.cs b/src/OpenIddict.Client/OpenIddictClientEvents.cs
index a7d31ea9..014ba3a1 100644
--- a/src/OpenIddict.Client/OpenIddictClientEvents.cs
+++ b/src/OpenIddict.Client/OpenIddictClientEvents.cs
@@ -796,6 +796,12 @@ public static partial class OpenIddictClientEvents
///
public string? BackchannelIdentityToken { get; set; }
+ ///
+ /// Gets or sets the authentication request identifier (auth_req_id)
+ /// used with the CIBA grant, if applicable.
+ ///
+ public string? AuthenticationRequestId { get; set; }
+
///
/// Gets or sets the device code to validate, if applicable.
///
@@ -1174,6 +1180,60 @@ public static partial class OpenIddictClientEvents
///
public HashSet Scopes { get; } = new(StringComparer.Ordinal);
+ ///
+ /// Gets or sets the optional login hint token that will be sent to the authorization server, if applicable.
+ ///
+ public string? LoginHintToken { get; set; }
+
+ ///
+ /// Gets or sets the optional binding message that will be sent to
+ /// the backchannel authentication endpoint, if applicable.
+ ///
+ public string? BindingMessage { get; set; }
+
+ ///
+ /// Gets or sets the optional requested expiry that will be sent to
+ /// the backchannel authentication endpoint, if applicable.
+ ///
+ public TimeSpan? RequestedExpiry { get; set; }
+
+ ///
+ /// Gets or sets the URI of the backchannel authentication endpoint, if applicable.
+ ///
+ public Uri? BackchannelAuthenticationEndpoint { get; set; }
+
+ ///
+ /// Gets or sets the client authentication method used when communicating
+ /// with the backchannel authentication endpoint, if applicable.
+ ///
+ public string? BackchannelAuthenticationEndpointClientAuthenticationMethod { get; set; }
+
+ ///
+ /// Gets or sets the X.509 client certificate used when communicating
+ /// with the backchannel authentication endpoint, if applicable.
+ ///
+ public X509Certificate2? BackchannelAuthenticationEndpointClientCertificate { get; set; }
+
+ ///
+ /// Gets or sets a boolean indicating whether a backchannel authentication request should be sent.
+ ///
+ public bool SendBackchannelAuthenticationRequest { get; set; }
+
+ ///
+ /// Gets or sets the request sent to the backchannel authentication endpoint, if applicable.
+ ///
+ public OpenIddictRequest? BackchannelAuthenticationRequest { get; set; }
+
+ ///
+ /// Gets or sets the response returned by the backchannel authentication endpoint, if applicable.
+ ///
+ public OpenIddictResponse? BackchannelAuthenticationResponse { get; set; }
+
+ ///
+ /// Gets or sets the authentication request identifier returned by the backchannel authentication endpoint, if applicable.
+ ///
+ public string? AuthenticationRequestId { get; set; }
+
///
/// Gets or sets the URI of the device authorization endpoint, if applicable.
///
diff --git a/src/OpenIddict.Client/OpenIddictClientExtensions.cs b/src/OpenIddict.Client/OpenIddictClientExtensions.cs
index 4ff9a148..7b05a9a4 100644
--- a/src/OpenIddict.Client/OpenIddictClientExtensions.cs
+++ b/src/OpenIddict.Client/OpenIddictClientExtensions.cs
@@ -56,6 +56,7 @@ public static class OpenIddictClientExtensions
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.Client/OpenIddictClientHandlerFilters.cs b/src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs
index 65999b0d..e42ba6b1 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs
@@ -350,6 +350,20 @@ public static class OpenIddictClientHandlerFilters
}
}
+ ///
+ /// Represents a filter that excludes the associated handlers if no backchannel authentication request is expected to be sent.
+ ///
+ public sealed class RequireBackchannelAuthenticationRequest : IOpenIddictClientHandlerFilter
+ {
+ ///
+ public ValueTask IsActiveAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ return new(context.SendBackchannelAuthenticationRequest);
+ }
+ }
+
///
/// Represents a filter that excludes the associated handlers if no request object is expected to be sent.
///
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Backchannel.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Backchannel.cs
new file mode 100644
index 00000000..0078f73f
--- /dev/null
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Backchannel.cs
@@ -0,0 +1,203 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+using System.Collections.Immutable;
+using System.Text.Json;
+using Microsoft.Extensions.Logging;
+
+namespace OpenIddict.Client;
+
+public static partial class OpenIddictClientHandlers
+{
+ public static class Backchannel
+ {
+ public static ImmutableArray DefaultHandlers { get; } =
+ [
+ /*
+ * Backchannel authentication response handling:
+ */
+ ValidateWellKnownParameters.Descriptor,
+ HandleErrorResponse.Descriptor,
+ ValidateAuthenticationRequestId.Descriptor,
+ ValidateExpiration.Descriptor
+ ];
+
+ ///
+ /// Contains the logic responsible for validating the well-known parameters contained in the backchannel authentication response.
+ ///
+ public sealed class ValidateWellKnownParameters : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(int.MinValue + 100_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleBackchannelAuthenticationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ foreach (var parameter in context.Response.GetParameters())
+ {
+ if (!ValidateParameterType(parameter.Key, parameter.Value))
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2107(parameter.Key),
+ uri: SR.FormatID8000(SR.ID2107));
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ return ValueTask.CompletedTask;
+
+ static bool ValidateParameterType(string name, OpenIddictParameter value) => name switch
+ {
+ // The following parameters MUST be formatted as unique strings:
+ Parameters.AuthReqId or Parameters.Error or Parameters.ErrorDescription or Parameters.ErrorUri
+ => ((JsonElement) value).ValueKind is JsonValueKind.String,
+
+ // The following parameters MUST be formatted as positive numbers:
+ Parameters.ExpiresIn or Parameters.Interval
+ => (JsonElement) value is { ValueKind: JsonValueKind.Number } element &&
+ element.TryGetDecimal(out decimal result) && result is >= 0,
+
+ // Parameters that are not in the well-known list can be of any type.
+ _ => true
+ };
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for surfacing potential errors from the backchannel authentication response.
+ ///
+ public sealed class HandleErrorResponse : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ValidateWellKnownParameters.Descriptor.Order + 1_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleBackchannelAuthenticationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // For more information, see
+ // https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.13.
+ if (!string.IsNullOrEmpty(context.Response.Error))
+ {
+ context.Logger.LogInformation(6306, SR.GetResourceString(SR.ID6306), context.Response);
+
+ context.Reject(
+ error: context.Response.Error switch
+ {
+ Errors.AccessDenied => Errors.AccessDenied,
+ Errors.ExpiredLoginHintToken => Errors.ExpiredLoginHintToken,
+ Errors.InvalidBindingMessage => Errors.InvalidBindingMessage,
+ Errors.InvalidClient => Errors.InvalidRequest,
+ Errors.InvalidRequest => Errors.InvalidRequest,
+ Errors.InvalidScope => Errors.InvalidScope,
+ Errors.InvalidUserCode => Errors.InvalidUserCode,
+ Errors.MissingUserCode => Errors.MissingUserCode,
+ Errors.UnauthorizedClient => Errors.UnauthorizedClient,
+ Errors.UnknownUserId => Errors.UnknownUserId,
+ _ => Errors.ServerError
+ },
+ description: SR.GetResourceString(SR.ID2219),
+ uri: SR.FormatID8000(SR.ID2219));
+
+ return ValueTask.CompletedTask;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for validating the authentication
+ /// request identifier contained in the backchannel authentication response.
+ ///
+ public sealed class ValidateAuthenticationRequestId : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(HandleErrorResponse.Descriptor.Order + 1_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleBackchannelAuthenticationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // Return an error if the mandatory "auth_req_id" parameter is missing.
+ if (string.IsNullOrEmpty(context.Response.AuthReqId))
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2168(Parameters.AuthReqId),
+ uri: SR.FormatID8000(SR.ID2168));
+
+ return ValueTask.CompletedTask;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for validating the "expires_in"
+ /// parameter contained in the backchannel authentication response.
+ ///
+ public sealed class ValidateExpiration : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ValidateAuthenticationRequestId.Descriptor.Order + 1_000)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleBackchannelAuthenticationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // Return an error if the mandatory "expires_in" parameter is missing.
+ if (context.Response.ExpiresIn is null)
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2168(Parameters.ExpiresIn),
+ uri: SR.FormatID8000(SR.ID2168));
+
+ return ValueTask.CompletedTask;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+ }
+}
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
index ce577fbb..8692d3fb 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
@@ -26,6 +26,7 @@ public static partial class OpenIddictClientHandlers
ExtractAuthorizationEndpoint.Descriptor,
ExtractJsonWebKeySetEndpoint.Descriptor,
ExtractDeviceAuthorizationEndpoint.Descriptor,
+ ExtractBackchannelAuthenticationEndpoint.Descriptor,
ExtractIntrospectionEndpoint.Descriptor,
ExtractEndSessionEndpoint.Descriptor,
ExtractMtlsDeviceAuthorizationEndpoint.Descriptor,
@@ -111,6 +112,7 @@ public static partial class OpenIddictClientHandlers
// The following parameters MUST be formatted as unique strings:
Metadata.AuthorizationEndpoint or
+ Metadata.BackchannelAuthenticationEndpoint or
Metadata.DeviceAuthorizationEndpoint or
Metadata.EndSessionEndpoint or
Metadata.Issuer or
@@ -121,6 +123,7 @@ public static partial class OpenIddictClientHandlers
=> ((JsonElement) value).ValueKind is JsonValueKind.String,
// The following parameters MUST be formatted as arrays of strings:
+ Metadata.BackchannelTokenDeliveryModesSupported or
Metadata.CodeChallengeMethodsSupported or
Metadata.DeviceAuthorizationEndpointAuthMethodsSupported or
Metadata.GrantTypesSupported or
@@ -141,6 +144,7 @@ public static partial class OpenIddictClientHandlers
// The following parameters MUST be formatted as booleans:
Metadata.AuthorizationResponseIssParameterSupported or
+ Metadata.BackchannelUserCodeParameterSupported or
Metadata.RequestParameterSupported or
Metadata.RequirePushedAuthorizationRequests or
Metadata.RequireSignedRequestObject or
@@ -392,6 +396,58 @@ public static partial class OpenIddictClientHandlers
}
}
+ ///
+ /// Contains the logic responsible for extracting the backchannel authentication
+ /// endpoint URI and the associated metadata from the discovery document.
+ ///
+ public sealed class ExtractBackchannelAuthenticationEndpoint : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ExtractDeviceAuthorizationEndpoint.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(HandleConfigurationResponseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ var endpoint = (string?) context.Response[Metadata.BackchannelAuthenticationEndpoint];
+ if (!string.IsNullOrEmpty(endpoint))
+ {
+ if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) || OpenIddictHelpers.IsImplicitFileUri(uri))
+ {
+ context.Reject(
+ error: Errors.ServerError,
+ description: SR.FormatID2100(Metadata.BackchannelAuthenticationEndpoint),
+ uri: SR.FormatID8000(SR.ID2100));
+
+ return ValueTask.CompletedTask;
+ }
+
+ context.Configuration.BackchannelAuthenticationEndpoint = uri;
+ }
+
+ foreach (var mode in (ImmutableArray?) context.Response[Metadata.BackchannelTokenDeliveryModesSupported] ?? [])
+ {
+ if (!string.IsNullOrEmpty(mode))
+ {
+ context.Configuration.BackchannelTokenDeliveryModesSupported.Add(mode);
+ }
+ }
+
+ context.Configuration.BackchannelUserCodeParameterSupported = (bool?)
+ context.Response[Metadata.BackchannelUserCodeParameterSupported];
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
///
/// Contains the logic responsible for extracting the introspection endpoint URI from the discovery document.
///
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
index 9c516a3b..6b30ab31 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
@@ -143,6 +143,14 @@ public static partial class OpenIddictClientHandlers
ResolveDeviceAuthorizationEndpoint.Descriptor,
AttachDeviceAuthorizationRequestParameters.Descriptor,
+ EvaluateBackchannelAuthenticationRequest.Descriptor,
+ AttachBackchannelAuthenticationEndpointClientAuthenticationMethod.Descriptor,
+ AttachBackchannelAuthenticationEndpointClientCertificate.Descriptor,
+ ResolveBackchannelAuthenticationEndpoint.Descriptor,
+ AttachBackchannelAuthenticationRequestParameters.Descriptor,
+ AttachBackchannelAuthenticationRequestClientCredentials.Descriptor,
+ SendBackchannelAuthenticationRequest.Descriptor,
+
EvaluatePushedAuthorizationRequest.Descriptor,
AttachPushedAuthorizationEndpointClientAuthenticationMethod.Descriptor,
AttachPushedAuthorizationEndpointClientCertificate.Descriptor,
@@ -229,6 +237,7 @@ public static partial class OpenIddictClientHandlers
AttachCustomErrorParameters.Descriptor,
.. Authentication.DefaultHandlers,
+ .. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
@@ -377,6 +386,9 @@ public static partial class OpenIddictClientHandlers
case GrantTypes.DeviceCode when string.IsNullOrEmpty(context.DeviceCode):
throw new InvalidOperationException(SR.GetResourceString(SR.ID0396));
+ case GrantTypes.Ciba when string.IsNullOrEmpty(context.AuthenticationRequestId):
+ throw new InvalidOperationException(SR.GetResourceString(SR.ID0536));
+
case GrantTypes.Password:
if (string.IsNullOrEmpty(context.Username))
{
@@ -2283,12 +2295,14 @@ public static partial class OpenIddictClientHandlers
null when context.ResponseType is ResponseTypes.None => false,
// For the non-interactive grant types, always send a token request.
+ GrantTypes.Ciba or
GrantTypes.ClientCredentials or GrantTypes.DeviceCode or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange => true,
// By default, always send a token request for custom grant types.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange) => true,
@@ -2685,7 +2699,7 @@ public static partial class OpenIddictClientHandlers
string value => value
};
- if (context.TokenRequest.GrantType is not (GrantTypes.AuthorizationCode or GrantTypes.DeviceCode))
+ if (context.TokenRequest.GrantType is not (GrantTypes.AuthorizationCode or GrantTypes.Ciba or GrantTypes.DeviceCode))
{
if (context.Audiences.Count is > 0)
{
@@ -2726,6 +2740,14 @@ public static partial class OpenIddictClientHandlers
context.TokenRequest.DeviceCode = context.DeviceCode;
}
+ // If the token request uses the CIBA grant, attach the authentication request identifier to the request.
+ else if (context.TokenRequest.GrantType is GrantTypes.Ciba)
+ {
+ Debug.Assert(!string.IsNullOrEmpty(context.AuthenticationRequestId), SR.GetResourceString(SR.ID4010));
+
+ context.TokenRequest.AuthReqId = context.AuthenticationRequestId;
+ }
+
// If the token request uses a resource owner password credentials grant, attach the credentials to the request.
else if (context.TokenRequest.GrantType is GrantTypes.Password)
{
@@ -3103,8 +3125,9 @@ public static partial class OpenIddictClientHandlers
types.Contains(ResponseTypes.Code)
=> (true, true, false, false),
- // An access token is always returned as part of client credentials, device
+ // An access token is always returned as part of CIBA, client credentials, device
// code, resource owner password credentials and refresh token responses.
+ GrantTypes.Ciba or
GrantTypes.ClientCredentials or GrantTypes.DeviceCode or
GrantTypes.Password or GrantTypes.RefreshToken
=> (true, true, false, false),
@@ -3118,6 +3141,7 @@ public static partial class OpenIddictClientHandlers
// By default, always extract and require a backchannel
// access token for custom grant types, but don't validate it.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -3142,6 +3166,9 @@ public static partial class OpenIddictClientHandlers
context.StateTokenPrincipal is ClaimsPrincipal principal &&
principal.HasScope(Scopes.OpenId) => (true, true, true, true),
+ // CIBA is an OpenID Connect flow: an identity token is always returned as part of token responses.
+ GrantTypes.Ciba => (true, true, true, true),
+
// The client credentials, device code, resource owner password credentials and token
// exchange grants don't have an equivalent in OpenID Connect so an identity token is
// typically never returned when using them. However, certain server implementations
@@ -3161,6 +3188,7 @@ public static partial class OpenIddictClientHandlers
// By default, try to extract a backchannel identity token for custom grant
// types and validate it when present, but don't require that one be returned.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -3203,6 +3231,7 @@ public static partial class OpenIddictClientHandlers
// resource owner password credentials, refresh token and token exchange responses
// depending on the policy adopted by the remote authorization server. As such,
// a refresh token is never considered required for such token responses.
+ GrantTypes.Ciba or
GrantTypes.ClientCredentials or GrantTypes.DeviceCode or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange
@@ -3211,6 +3240,7 @@ public static partial class OpenIddictClientHandlers
// By default, always try to extract a refresh token for
// custom grant types, but don't require or validate it.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -4058,7 +4088,8 @@ public static partial class OpenIddictClientHandlers
// For the well-known grant types involving users, send a userinfo request if the
// userinfo endpoint is available and if a frontchannel or backchannel access token
// is available, unless userinfo retrieval was explicitly disabled by the user.
- GrantTypes.AuthorizationCode or GrantTypes.DeviceCode or GrantTypes.Implicit or
+ GrantTypes.AuthorizationCode or GrantTypes.Ciba or
+ GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken
when context.Configuration.UserInfoEndpoint is not null && !context.DisableUserInfoRetrieval &&
(!string.IsNullOrEmpty(context.BackchannelAccessToken) ||
@@ -4072,6 +4103,7 @@ public static partial class OpenIddictClientHandlers
// Apply the same logic for custom grant types.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -4098,6 +4130,9 @@ public static partial class OpenIddictClientHandlers
// userinfo validation, unless the "openid" scope was explicitly requested by the application.
GrantTypes.DeviceCode or GrantTypes.Password => !context.Scopes.Contains(Scopes.OpenId),
+ // CIBA is an OpenID Connect-only flow: always validate userinfo responses.
+ GrantTypes.Ciba => false,
+
// Note: when using grant_type=refresh_token, it is not possible to determine whether the refresh token
// was issued during an OAuth 2.0-only or OpenID Connect flow. In this case, only validate userinfo
// responses if the openid scope was explicitly added by the user to the list of requested scopes.
@@ -4110,6 +4145,7 @@ public static partial class OpenIddictClientHandlers
// For unknown grant types, disable userinfo validation unless the openid scope was explicitly added.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -4400,6 +4436,7 @@ public static partial class OpenIddictClientHandlers
// By default, OpenIddict doesn't require that userinfo tokens be used even for
// user flows but they are extracted and validated when a userinfo request was sent.
GrantTypes.AuthorizationCode or GrantTypes.Implicit or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Password or
GrantTypes.RefreshToken or GrantTypes.TokenExchange
when context.SendUserInfoRequest => (true, false, true, true),
@@ -4412,6 +4449,7 @@ public static partial class OpenIddictClientHandlers
// By default, don't require userinfo tokens for custom grants
// but extract and validate them when a userinfo request was sent.
not null and not (GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
+ GrantTypes.Ciba or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange)
@@ -4857,7 +4895,7 @@ public static partial class OpenIddictClientHandlers
if (!string.IsNullOrEmpty(context.GrantType))
{
if (context.GrantType is not (
- GrantTypes.AuthorizationCode or GrantTypes.DeviceCode or GrantTypes.Implicit))
+ GrantTypes.AuthorizationCode or GrantTypes.Ciba or GrantTypes.DeviceCode or GrantTypes.Implicit))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0296));
}
@@ -4883,7 +4921,7 @@ public static partial class OpenIddictClientHandlers
}
// Ensure signing/and encryption credentials are present as they are required to protect state tokens.
- if (context.GrantType is not GrantTypes.DeviceCode)
+ if (context.GrantType is not (GrantTypes.Ciba or GrantTypes.DeviceCode))
{
if (context.Options.EncryptionCredentials.Count is 0)
{
@@ -5369,7 +5407,8 @@ public static partial class OpenIddictClientHandlers
// Note: the client identifier is required for the authorization code/hybrid/implicit and device authorization flows.
// If no client identifier was attached to the registration, abort the challenge demand immediately.
- _ when context.GrantType is GrantTypes.AuthorizationCode or GrantTypes.DeviceCode or GrantTypes.Implicit
+ _ when context.GrantType is GrantTypes.AuthorizationCode or GrantTypes.Ciba or
+ GrantTypes.DeviceCode or GrantTypes.Implicit
=> throw new InvalidOperationException(SR.GetResourceString(SR.ID0418)),
// Note: the client identifier is also required for the special response_type=none flow.
@@ -6835,6 +6874,7 @@ public static partial class OpenIddictClientHandlers
// If the private_key_jwt client authentication method could be negotiated,
// generate a client assertion that will be used to authenticate the client.
{ DeviceAuthorizationEndpointClientAuthenticationMethod: ClientAuthenticationMethods.PrivateKeyJwt } => (true, true),
+ { BackchannelAuthenticationEndpointClientAuthenticationMethod: ClientAuthenticationMethods.PrivateKeyJwt } => (true, true),
{ PushedAuthorizationEndpointClientAuthenticationMethod: ClientAuthenticationMethods.PrivateKeyJwt } => (true, true),
_ => (false, false)
@@ -7207,6 +7247,375 @@ public static partial class OpenIddictClientHandlers
}
}
+ ///
+ /// Contains the logic responsible for determining whether a backchannel authentication request should be sent.
+ ///
+ public sealed class EvaluateBackchannelAuthenticationRequest : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(EvaluateDeviceAuthorizationRequest.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ context.SendBackchannelAuthenticationRequest = context.GrantType is GrantTypes.Ciba;
+
+ if (context.SendBackchannelAuthenticationRequest)
+ {
+ // Backchannel authentication requests MUST contain exactly one hint identifying the end user.
+ var count = (string.IsNullOrEmpty(context.LoginHint) ? 0 : 1) +
+ (string.IsNullOrEmpty(context.LoginHintToken) ? 0 : 1) +
+ (string.IsNullOrEmpty(context.IdentityTokenHint) ? 0 : 1);
+
+ if (count is not 1)
+ {
+ throw new InvalidOperationException(SR.GetResourceString(SR.ID0541));
+ }
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for negotiating the best backchannel authentication endpoint
+ /// client authentication method supported by both the client and the authorization server.
+ ///
+ public sealed class AttachBackchannelAuthenticationEndpointClientAuthenticationMethod : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachDeviceAuthorizationEndpointClientAuthenticationMethod.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // If an explicit client authentication method was attached, don't overwrite it.
+ if (!string.IsNullOrEmpty(context.BackchannelAuthenticationEndpointClientAuthenticationMethod))
+ {
+ return ValueTask.CompletedTask;
+ }
+
+ // If the client is a public application, do not negotiate a client authentication method.
+ if (context.Registration.ClientType is ClientTypes.Public)
+ {
+ context.BackchannelAuthenticationEndpointClientAuthenticationMethod = ClientAuthenticationMethods.None;
+
+ return ValueTask.CompletedTask;
+ }
+
+ // Note: the CIBA specification requires using the same client authentication
+ // methods as the token endpoint, whose supported methods are used here.
+ context.BackchannelAuthenticationEndpointClientAuthenticationMethod = (
+ Client: context.Registration.ClientAuthenticationMethods.Count switch
+ {
+ 0 => context.Options.ClientAuthenticationMethods as ICollection,
+ _ => context.Options.ClientAuthenticationMethods.Intersect(context.Registration.ClientAuthenticationMethods, StringComparer.Ordinal).ToList()
+ },
+ Server: context.Configuration.TokenEndpointAuthMethodsSupported) switch
+ {
+ // If a TLS client authentication certificate can be resolved and both
+ // the client and the server explicitly support tls_client_auth, prefer it.
+ ({ Count: > 0 } client, { Count: > 0 } server) when
+ client.Contains(ClientAuthenticationMethods.TlsClientAuth) &&
+ server.Contains(ClientAuthenticationMethods.TlsClientAuth) &&
+ context.Configuration.BackchannelAuthenticationEndpoint is Uri endpoint &&
+ string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) &&
+ context.Registration.SigningCredentials.Exists(static credentials =>
+ credentials.Key is X509SecurityKey { Certificate: X509Certificate2 certificate } &&
+ OpenIddictHelpers.IsClientAuthenticationCertificate(certificate) &&
+ !OpenIddictHelpers.IsSelfIssuedCertificate(certificate))
+ => ClientAuthenticationMethods.TlsClientAuth,
+
+ ({ Count: > 0 } client, { Count: > 0 } server) when
+ client.Contains(ClientAuthenticationMethods.SelfSignedTlsClientAuth) &&
+ server.Contains(ClientAuthenticationMethods.SelfSignedTlsClientAuth) &&
+ context.Configuration.BackchannelAuthenticationEndpoint is Uri endpoint &&
+ string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) &&
+ context.Registration.SigningCredentials.Exists(static credentials =>
+ credentials.Key is X509SecurityKey { Certificate: X509Certificate2 certificate } &&
+ OpenIddictHelpers.IsClientAuthenticationCertificate(certificate) &&
+ OpenIddictHelpers.IsSelfIssuedCertificate(certificate))
+ => ClientAuthenticationMethods.SelfSignedTlsClientAuth,
+
+ // If at least one asymmetric signing key was attached to the client registration
+ // and both the client and the server explicitly support private_key_jwt, use it.
+ ({ Count: > 0 } client, { Count: > 0 } server) when
+ client.Contains(ClientAuthenticationMethods.PrivateKeyJwt) &&
+ server.Contains(ClientAuthenticationMethods.PrivateKeyJwt) &&
+ context.Registration.SigningCredentials.Exists(static credentials => credentials.Key is AsymmetricSecurityKey)
+ => ClientAuthenticationMethods.PrivateKeyJwt,
+
+ ({ Count: > 0 } client, { Count: > 0 } server) when !string.IsNullOrEmpty(context.Registration.ClientSecret) &&
+ client.Contains(ClientAuthenticationMethods.ClientSecretPost) &&
+ server.Contains(ClientAuthenticationMethods.ClientSecretPost)
+ => ClientAuthenticationMethods.ClientSecretPost,
+
+ ({ Count: > 0 } client, { Count: > 0 } server) when !string.IsNullOrEmpty(context.Registration.ClientSecret) &&
+ client.Contains(ClientAuthenticationMethods.ClientSecretBasic) &&
+ server.Contains(ClientAuthenticationMethods.ClientSecretBasic)
+ => ClientAuthenticationMethods.ClientSecretBasic,
+
+ ({ Count: > 0 } client, { Count: 0 }) when !string.IsNullOrEmpty(context.Registration.ClientSecret) &&
+ client.Contains(ClientAuthenticationMethods.ClientSecretBasic)
+ => ClientAuthenticationMethods.ClientSecretBasic,
+
+ _ => null
+ };
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for attaching the client certificate used for
+ /// the backchannel authentication endpoint to the challenge context, if applicable.
+ ///
+ public sealed class AttachBackchannelAuthenticationEndpointClientCertificate : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachDeviceAuthorizationEndpointClientCertificate.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ context.BackchannelAuthenticationEndpointClientCertificate ??= context.BackchannelAuthenticationEndpointClientAuthenticationMethod switch
+ {
+ ClientAuthenticationMethods.TlsClientAuth => context.Registration.SigningCredentials
+ .Select(static credentials => (credentials.Key as X509SecurityKey)?.Certificate)
+ .FirstOrDefault(static certificate => certificate is not null &&
+ OpenIddictHelpers.IsClientAuthenticationCertificate(certificate) &&
+ !OpenIddictHelpers.IsSelfIssuedCertificate(certificate))
+ ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0512)),
+
+ ClientAuthenticationMethods.SelfSignedTlsClientAuth => context.Registration.SigningCredentials
+ .Select(static credentials => (credentials.Key as X509SecurityKey)?.Certificate)
+ .FirstOrDefault(static certificate => certificate is not null &&
+ OpenIddictHelpers.IsClientAuthenticationCertificate(certificate) &&
+ OpenIddictHelpers.IsSelfIssuedCertificate(certificate))
+ ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0512)),
+
+ _ => null
+ };
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for resolving the URI of the backchannel authentication endpoint.
+ ///
+ public sealed class ResolveBackchannelAuthenticationEndpoint : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(ResolveDeviceAuthorizationEndpoint.Descriptor.Order + 500)
+ .SetType(OpenIddictClientHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ context.BackchannelAuthenticationEndpoint ??= context.Configuration.BackchannelAuthenticationEndpoint is { IsAbsoluteUri: true } uri &&
+ !OpenIddictHelpers.IsImplicitFileUri(uri) ? uri : null;
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for attaching the parameters to the backchannel authentication request, if applicable.
+ ///
+ public sealed class AttachBackchannelAuthenticationRequestParameters : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachDeviceAuthorizationRequestParameters.Descriptor.Order + 500)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ // Attach a new request instance if necessary.
+ context.BackchannelAuthenticationRequest ??= new OpenIddictRequest();
+
+ // Note: backchannel authentication requests MUST include the "openid" scope.
+ var scopes = new HashSet(context.Scopes, StringComparer.Ordinal) { Scopes.OpenId };
+ context.BackchannelAuthenticationRequest.Scope = string.Join(Separators.Space[0],
+ scopes.OrderBy(static scope => scope is Scopes.OpenId ? 0 : 1).ThenBy(static scope => scope, StringComparer.Ordinal));
+
+ context.BackchannelAuthenticationRequest.IdTokenHint = context.IdentityTokenHint;
+ context.BackchannelAuthenticationRequest.LoginHint = context.LoginHint;
+ context.BackchannelAuthenticationRequest.LoginHintToken = context.LoginHintToken;
+ context.BackchannelAuthenticationRequest.BindingMessage = context.BindingMessage;
+
+ if (context.RequestedExpiry is TimeSpan expiry)
+ {
+ context.BackchannelAuthenticationRequest.RequestedExpiry = (long) Math.Ceiling(expiry.TotalSeconds);
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for attaching the client credentials to the backchannel authentication request, if applicable.
+ ///
+ public sealed class AttachBackchannelAuthenticationRequestClientCredentials : IOpenIddictClientHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(AttachDeviceAuthorizationRequestClientCredentials.Descriptor.Order + 500)
+ .Build();
+
+ ///
+ public ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ Debug.Assert(context.BackchannelAuthenticationRequest is not null, SR.GetResourceString(SR.ID4008));
+
+ // Always attach the client_id to the request, even if an assertion is sent or mTLS is used.
+ context.BackchannelAuthenticationRequest.ClientId = context.ClientId;
+
+ // Note: client authentication methods are mutually exclusive so the client_assertion
+ // and client_secret parameters MUST never be sent at the same time.
+ if (context.IncludeClientAssertion)
+ {
+ context.BackchannelAuthenticationRequest.ClientAssertion = context.ClientAssertion;
+ context.BackchannelAuthenticationRequest.ClientAssertionType = context.ClientAssertionType;
+ }
+
+ else if (context.BackchannelAuthenticationEndpointClientAuthenticationMethod is
+ ClientAuthenticationMethods.ClientSecretBasic or
+ ClientAuthenticationMethods.ClientSecretPost)
+ {
+ context.BackchannelAuthenticationRequest.ClientSecret = context.Registration.ClientSecret;
+ }
+
+ return ValueTask.CompletedTask;
+ }
+ }
+
+ ///
+ /// Contains the logic responsible for sending the backchannel authentication request, if applicable.
+ ///
+ public sealed class SendBackchannelAuthenticationRequest : IOpenIddictClientHandler
+ {
+ private readonly OpenIddictClientService _service;
+
+ public SendBackchannelAuthenticationRequest(OpenIddictClientService service)
+ => _service = service ?? throw new ArgumentNullException(nameof(service));
+
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictClientHandlerDescriptor Descriptor { get; }
+ = OpenIddictClientHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(SendDeviceAuthorizationRequest.Descriptor.Order + 500)
+ .Build();
+
+ ///
+ public async ValueTask HandleAsync(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ Debug.Assert(context.BackchannelAuthenticationRequest is not null, SR.GetResourceString(SR.ID4008));
+
+ // Ensure the backchannel authentication endpoint is present and is a valid absolute URI.
+ if (context.BackchannelAuthenticationEndpoint is not { IsAbsoluteUri: true } ||
+ OpenIddictHelpers.IsImplicitFileUri(context.BackchannelAuthenticationEndpoint))
+ {
+ throw new InvalidOperationException(SR.FormatID0301(Metadata.BackchannelAuthenticationEndpoint));
+ }
+
+ var certificate = context.BackchannelAuthenticationEndpointClientAuthenticationMethod switch
+ {
+ ClientAuthenticationMethods.TlsClientAuth when context.BackchannelAuthenticationEndpointClientCertificate is not null =>
+ OpenIddictHelpers.IsSelfIssuedCertificate(context.BackchannelAuthenticationEndpointClientCertificate)
+ ? throw new InvalidOperationException(SR.GetResourceString(SR.ID0513))
+ : context.BackchannelAuthenticationEndpointClientCertificate,
+
+ ClientAuthenticationMethods.SelfSignedTlsClientAuth when context.BackchannelAuthenticationEndpointClientCertificate is not null =>
+ OpenIddictHelpers.IsSelfIssuedCertificate(context.BackchannelAuthenticationEndpointClientCertificate)
+ ? context.BackchannelAuthenticationEndpointClientCertificate
+ : throw new InvalidOperationException(SR.GetResourceString(SR.ID0513)),
+
+ _ => null
+ };
+
+ try
+ {
+ context.BackchannelAuthenticationResponse = await _service.SendBackchannelAuthenticationRequestAsync(
+ context.Registration, context.Configuration,
+ context.BackchannelAuthenticationRequest, context.BackchannelAuthenticationEndpoint,
+ context.BackchannelAuthenticationEndpointClientAuthenticationMethod,
+ certificate, context.CancellationToken);
+ }
+
+ catch (ProtocolException exception)
+ {
+ context.Reject(
+ error: exception.Error,
+ description: exception.ErrorDescription,
+ uri: exception.ErrorUri);
+
+ return;
+ }
+
+ context.AuthenticationRequestId = context.BackchannelAuthenticationResponse.AuthReqId;
+ }
+ }
+
///
/// Contains the logic responsible for attaching the client credentials to the pushed authorization endpoint request, if applicable.
///
@@ -7263,6 +7672,8 @@ public static partial class OpenIddictClientHandlers
///
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder()
+ // Note: pushed authorization requests only apply to interactive flows (e.g device or CIBA flows are not affected).
+ .AddFilter()
.UseSingletonHandler()
.SetOrder(AttachPushedAuthorizationRequestClientCredentials.Descriptor.Order + 1_000)
.Build();
diff --git a/src/OpenIddict.Client/OpenIddictClientModels.cs b/src/OpenIddict.Client/OpenIddictClientModels.cs
index becdf12a..b2c2ada0 100644
--- a/src/OpenIddict.Client/OpenIddictClientModels.cs
+++ b/src/OpenIddict.Client/OpenIddictClientModels.cs
@@ -651,6 +651,229 @@ public static class OpenIddictClientModels
public required ClaimsPrincipal? UserInfoTokenPrincipal { get; init; }
}
+ ///
+ /// Represents a backchannel authentication request (CIBA token polling).
+ ///
+ public sealed record class BackchannelAuthenticationRequest
+ {
+ ///
+ /// Gets or sets the parameters that will be added to the token request.
+ ///
+ public Dictionary? AdditionalTokenRequestParameters { get; init; }
+
+ ///
+ /// Gets or sets the authentication request identifier returned during the challenge phase.
+ ///
+ public required string AuthenticationRequestId { get; init; }
+
+ ///
+ /// Gets or sets the cancellation token that will be
+ /// used to determine if the operation was aborted.
+ ///
+ public CancellationToken CancellationToken { get; init; }
+
+ ///
+ /// Gets or sets a boolean indicating whether userinfo should be disabled.
+ ///
+ public bool DisableUserInfo { get; init; }
+
+ ///
+ /// Gets or sets the interval at which token requests will be sent (typically, the same
+ /// value as the one returned by the authorization server during the challenge phase).
+ ///
+ public required TimeSpan Interval { get; init; }
+
+ ///
+ /// Gets or sets the issuer used to resolve the client registration.
+ ///
+ public Uri? Issuer { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that will be added to the context.
+ ///
+ public Dictionary? Properties { get; init; }
+
+ ///
+ /// Gets or sets the provider name used to resolve the client registration.
+ ///
+ public string? ProviderName { get; init; }
+
+ ///
+ /// Gets or sets the unique identifier of the client registration that will be used.
+ ///
+ public string? RegistrationId { get; init; }
+
+ ///
+ /// Gets or sets the maximum duration during which token requests will be sent (typically, the
+ /// same value as the "expires_in" parameter returned during the challenge phase or a lower value).
+ ///
+ public required TimeSpan Timeout { get; init; }
+
+ ///
+ /// Gets or sets the X.509 client certificate used to bind the access and/or
+ /// refresh tokens issued by the authorization server, if applicable.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Advanced)]
+ public X509Certificate2? TokenBindingCertificate { get; init; }
+ }
+
+ ///
+ /// Represents a backchannel authentication result.
+ ///
+ public sealed record class BackchannelAuthenticationResult
+ {
+ ///
+ /// Gets or sets the access token.
+ ///
+ public required string AccessToken { get; init; }
+
+ ///
+ /// Gets or sets the expiration date of the access token, if available.
+ ///
+ public required DateTimeOffset? AccessTokenExpirationDate { get; init; }
+
+ ///
+ /// Gets or sets the identity token, if available.
+ ///
+ public required string? IdentityToken { get; init; }
+
+ ///
+ /// Gets or sets the principal extracted from the identity token, if available.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Advanced)]
+ public required ClaimsPrincipal? IdentityTokenPrincipal { get; init; }
+
+ ///
+ /// Gets or sets a merged principal containing all the claims
+ /// extracted from the identity token and userinfo token principals.
+ ///
+ public required ClaimsPrincipal Principal { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that were present in the context.
+ ///
+ public required Dictionary Properties { get; init; }
+
+ ///
+ /// Gets or sets the refresh token, if available.
+ ///
+ public required string? RefreshToken { get; init; }
+
+ ///
+ /// Gets or sets the token response.
+ ///
+ public required OpenIddictResponse TokenResponse { get; init; }
+
+ ///
+ /// Gets or sets the userinfo token, if available.
+ ///
+ public required string? UserInfoToken { get; init; }
+
+ ///
+ /// Gets or sets the principal extracted from the userinfo token or response, if available.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Advanced)]
+ public required ClaimsPrincipal? UserInfoTokenPrincipal { get; init; }
+ }
+
+ ///
+ /// Represents a backchannel challenge request (CIBA authentication request).
+ ///
+ public sealed record class BackchannelChallengeRequest
+ {
+ ///
+ /// Gets or sets the parameters that will be added to the backchannel authentication request.
+ ///
+ public Dictionary? AdditionalBackchannelAuthenticationRequestParameters { get; init; }
+
+ ///
+ /// Gets or sets the binding message displayed to the end user, if applicable.
+ ///
+ public string? BindingMessage { get; init; }
+
+ ///
+ /// Gets or sets the cancellation token that will be
+ /// used to determine if the operation was aborted.
+ ///
+ public CancellationToken CancellationToken { get; init; }
+
+ ///
+ /// Gets or sets the identity token hint used to identify the end user, if applicable.
+ ///
+ public string? IdentityTokenHint { get; init; }
+
+ ///
+ /// Gets or sets the issuer used to resolve the client registration.
+ ///
+ public Uri? Issuer { get; init; }
+
+ ///
+ /// Gets or sets the login hint used to identify the end user, if applicable.
+ ///
+ public string? LoginHint { get; init; }
+
+ ///
+ /// Gets or sets the login hint token used to identify the end user, if applicable.
+ ///
+ public string? LoginHintToken { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that will be added to the context.
+ ///
+ public Dictionary? Properties { get; init; }
+
+ ///
+ /// Gets or sets the provider name used to resolve the client registration.
+ ///
+ public string? ProviderName { get; init; }
+
+ ///
+ /// Gets or sets the unique identifier of the client registration that will be used.
+ ///
+ public string? RegistrationId { get; init; }
+
+ ///
+ /// Gets or sets the requested lifetime of the authentication request identifier, if applicable.
+ ///
+ public TimeSpan? RequestedExpiry { get; init; }
+
+ ///
+ /// Gets the scopes that will be sent to the authorization server.
+ ///
+ public List? Scopes { get; init; }
+ }
+
+ ///
+ /// Represents a backchannel challenge result.
+ ///
+ public sealed record class BackchannelChallengeResult
+ {
+ ///
+ /// Gets or sets the authentication request identifier.
+ ///
+ public required string AuthenticationRequestId { get; init; }
+
+ ///
+ /// Gets or sets the backchannel authentication response.
+ ///
+ public required OpenIddictResponse BackchannelAuthenticationResponse { get; init; }
+
+ ///
+ /// Gets or sets the remaining lifetime of the authentication request identifier.
+ ///
+ public required TimeSpan ExpiresIn { get; init; }
+
+ ///
+ /// Gets or sets the interval at which token requests should be sent.
+ ///
+ public required TimeSpan Interval { get; init; }
+
+ ///
+ /// Gets or sets the application-specific properties that were present in the context.
+ ///
+ public required Dictionary Properties { get; init; }
+ }
+
///
/// Represents a device authentication request.
///
diff --git a/src/OpenIddict.Client/OpenIddictClientService.cs b/src/OpenIddict.Client/OpenIddictClientService.cs
index 3d30b5b9..a49377bf 100644
--- a/src/OpenIddict.Client/OpenIddictClientService.cs
+++ b/src/OpenIddict.Client/OpenIddictClientService.cs
@@ -582,6 +582,179 @@ public class OpenIddictClientService
};
}
+ ///
+ /// Authenticates using the specified authentication request identifier (CIBA poll mode).
+ ///
+ /// The backchannel authentication request.
+ /// The backchannel authentication result.
+ public async ValueTask AuthenticateWithBackchannelAsync(BackchannelAuthenticationRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ using var source = CancellationTokenSource.CreateLinkedTokenSource(request.CancellationToken);
+ source.CancelAfter(request.Timeout);
+
+ var interval = request.Interval;
+
+ while (true)
+ {
+ source.Token.ThrowIfCancellationRequested();
+
+ try
+ {
+ await using var scope = _provider.CreateAsyncScope();
+
+ var dispatcher = scope.ServiceProvider.GetRequiredService();
+ var options = scope.ServiceProvider.GetRequiredService>();
+
+ var transaction = new OpenIddictClientTransaction
+ {
+ CancellationToken = request.CancellationToken,
+ Options = options.CurrentValue,
+ ServiceProvider = scope.ServiceProvider
+ };
+
+ var context = new ProcessAuthenticationContext(transaction)
+ {
+ AuthenticationRequestId = request.AuthenticationRequestId,
+ DisableUserInfoRetrieval = request.DisableUserInfo,
+ DisableUserInfoValidation = request.DisableUserInfo,
+ GrantType = GrantTypes.Ciba,
+ Issuer = request.Issuer,
+ ProviderName = request.ProviderName,
+ RegistrationId = request.RegistrationId,
+ Request = new(),
+ TokenEndpointClientCertificate = request.TokenBindingCertificate,
+ TokenRequest = request.AdditionalTokenRequestParameters
+ is Dictionary parameters ? new(parameters) : new()
+ };
+
+ if (request.Properties is { Count: > 0 })
+ {
+ foreach (var property in request.Properties)
+ {
+ context.Properties[property.Key] = property.Value;
+ }
+ }
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0374(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ return new()
+ {
+ AccessToken = context.BackchannelAccessToken!,
+ AccessTokenExpirationDate = context.BackchannelAccessTokenExpirationDate,
+ IdentityToken = context.BackchannelIdentityToken,
+ IdentityTokenPrincipal = context.BackchannelIdentityTokenPrincipal,
+ Principal = context.MergedPrincipal,
+ Properties = context.Properties,
+ RefreshToken = context.RefreshToken,
+ TokenResponse = context.TokenResponse ?? new(),
+ UserInfoToken = context.UserInfoToken,
+ UserInfoTokenPrincipal = context.UserInfoTokenPrincipal
+ };
+ }
+
+ catch (ProtocolException exception) when (exception.Error is Errors.AuthorizationPending)
+ {
+#if NET
+ await Task.Delay(interval, TimeProvider.System, source.Token);
+#else
+ await Task.Delay(interval, source.Token);
+#endif
+ }
+
+ catch (ProtocolException exception) when (exception.Error is Errors.SlowDown)
+ {
+ // When the error indicates that token requests are sent too frequently,
+ // slow down the token redeeming process by increasing the interval.
+#if NET
+ await Task.Delay(interval += TimeSpan.FromSeconds(5), TimeProvider.System, source.Token);
+#else
+ await Task.Delay(interval += TimeSpan.FromSeconds(5), source.Token);
+#endif
+ }
+ }
+ }
+
+ ///
+ /// Initiates a Client-Initiated Backchannel Authentication (CIBA) process.
+ ///
+ /// The backchannel challenge request.
+ /// The backchannel challenge result.
+ public async ValueTask ChallengeUsingBackchannelAsync(BackchannelChallengeRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+
+ request.CancellationToken.ThrowIfCancellationRequested();
+
+ await using var scope = _provider.CreateAsyncScope();
+
+ var dispatcher = scope.ServiceProvider.GetRequiredService();
+ var options = scope.ServiceProvider.GetRequiredService>();
+
+ var transaction = new OpenIddictClientTransaction
+ {
+ CancellationToken = request.CancellationToken,
+ Options = options.CurrentValue,
+ ServiceProvider = scope.ServiceProvider
+ };
+
+ var context = new ProcessChallengeContext(transaction)
+ {
+ BackchannelAuthenticationRequest = request.AdditionalBackchannelAuthenticationRequestParameters
+ is Dictionary parameters ? new(parameters) : new(),
+ BindingMessage = request.BindingMessage,
+ GrantType = GrantTypes.Ciba,
+ IdentityTokenHint = request.IdentityTokenHint,
+ Issuer = request.Issuer,
+ LoginHint = request.LoginHint,
+ LoginHintToken = request.LoginHintToken,
+ Principal = new ClaimsPrincipal(new ClaimsIdentity()),
+ ProviderName = request.ProviderName,
+ RegistrationId = request.RegistrationId,
+ Request = new(),
+ RequestedExpiry = request.RequestedExpiry
+ };
+
+ if (request.Scopes is { Count: > 0 })
+ {
+ context.Scopes.UnionWith(request.Scopes);
+ }
+
+ if (request.Properties is { Count: > 0 })
+ {
+ foreach (var property in request.Properties)
+ {
+ context.Properties[property.Key] = property.Value;
+ }
+ }
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0374(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ return new()
+ {
+ AuthenticationRequestId = context.AuthenticationRequestId!,
+ BackchannelAuthenticationResponse = context.BackchannelAuthenticationResponse ?? new(),
+ ExpiresIn = TimeSpan.FromSeconds((double) context.BackchannelAuthenticationResponse?.ExpiresIn!),
+ Interval = TimeSpan.FromSeconds((long?) context.BackchannelAuthenticationResponse?[Parameters.Interval] ?? 5),
+ Properties = context.Properties
+ };
+ }
+
///
/// Authenticates using the specified device authorization code.
///
@@ -1650,6 +1823,151 @@ public class OpenIddictClientService
}
}
+ ///
+ /// Sends the backchannel authentication request and retrieves the corresponding response.
+ ///
+ /// The client registration.
+ /// The server configuration.
+ /// The backchannel authentication request.
+ /// The uri of the remote backchannel authentication endpoint.
+ /// The client authentication method, if applicable.
+ /// The client certificate, if applicable.
+ /// The that can be used to abort the operation.
+ /// The backchannel authentication response.
+ internal async ValueTask SendBackchannelAuthenticationRequestAsync(
+ OpenIddictClientRegistration registration, OpenIddictConfiguration configuration,
+ OpenIddictRequest request, Uri uri, string? method,
+ X509Certificate2? certificate, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(registration);
+ ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(uri);
+
+ if (!uri.IsAbsoluteUri || OpenIddictHelpers.IsImplicitFileUri(uri))
+ {
+ throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(uri));
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ await using var scope = _provider.CreateAsyncScope();
+
+ var dispatcher = scope.ServiceProvider.GetRequiredService();
+ var options = scope.ServiceProvider.GetRequiredService>();
+
+ var transaction = new OpenIddictClientTransaction
+ {
+ CancellationToken = cancellationToken,
+ Options = options.CurrentValue,
+ ServiceProvider = scope.ServiceProvider
+ };
+
+ request = await PrepareBackchannelAuthenticationRequestAsync();
+ request = await ApplyBackchannelAuthenticationRequestAsync();
+
+ var response = await ExtractBackchannelAuthenticationResponseAsync();
+
+ return await HandleBackchannelAuthenticationResponseAsync();
+
+ async ValueTask PrepareBackchannelAuthenticationRequestAsync()
+ {
+ var context = new PrepareBackchannelAuthenticationRequestContext(transaction)
+ {
+ ClientAuthenticationMethod = method,
+ Configuration = configuration,
+ RemoteUri = uri,
+ Registration = registration,
+ Request = request,
+ LocalCertificate = certificate
+ };
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0537(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ return context.Request;
+ }
+
+ async ValueTask ApplyBackchannelAuthenticationRequestAsync()
+ {
+ var context = new ApplyBackchannelAuthenticationRequestContext(transaction)
+ {
+ RemoteUri = uri,
+ Configuration = configuration,
+ Registration = registration,
+ Request = request
+ };
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0538(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ context.Logger.LogInformation(6307, SR.GetResourceString(SR.ID6307), context.RemoteUri, context.Request);
+
+ return context.Request;
+ }
+
+ async ValueTask ExtractBackchannelAuthenticationResponseAsync()
+ {
+ var context = new ExtractBackchannelAuthenticationResponseContext(transaction)
+ {
+ RemoteUri = uri,
+ Configuration = configuration,
+ Registration = registration,
+ Request = request
+ };
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0539(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ Debug.Assert(context.Response is not null, SR.GetResourceString(SR.ID4007));
+
+ context.Logger.LogInformation(6308, SR.GetResourceString(SR.ID6308), context.RemoteUri, context.Response);
+
+ return context.Response;
+ }
+
+ async ValueTask HandleBackchannelAuthenticationResponseAsync()
+ {
+ var context = new HandleBackchannelAuthenticationResponseContext(transaction)
+ {
+ RemoteUri = uri,
+ Configuration = configuration,
+ Registration = registration,
+ Request = request,
+ Response = response
+ };
+
+ await dispatcher.DispatchAsync(context);
+
+ if (context.IsRejected)
+ {
+ throw new ProtocolException(
+ SR.FormatID0540(context.Error, context.ErrorDescription, context.ErrorUri),
+ context.Error, context.ErrorDescription, context.ErrorUri);
+ }
+
+ return context.Response;
+ }
+ }
+
///
/// Sends the introspection request and retrieves the corresponding response.
///
diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs
new file mode 100644
index 00000000..08c557e7
--- /dev/null
+++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs
@@ -0,0 +1,236 @@
+using System.Security.Claims;
+using System.Text.Json;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+using Xunit;
+using static OpenIddict.Client.OpenIddictClientEvents;
+using static OpenIddict.Client.OpenIddictClientHandlers;
+
+namespace OpenIddict.Client.Tests;
+
+public class OpenIddictClientHandlersBackchannelTests
+{
+ [Fact]
+ public async Task EvaluateBackchannelAuthenticationRequest_RequestIsSentForCibaGrant()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateChallengeContext(provider);
+ context.LoginHint = "bob@fabrikam.com";
+
+ // Act
+ await new EvaluateBackchannelAuthenticationRequest().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.SendBackchannelAuthenticationRequest);
+ }
+
+ [Theory]
+ [InlineData(null, null, null)]
+ [InlineData("bob@fabrikam.com", "token", null)]
+ [InlineData("bob@fabrikam.com", null, "id_token")]
+ public async Task EvaluateBackchannelAuthenticationRequest_ThrowsAnExceptionForInvalidHints(string? hint, string? token, string? identity)
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateChallengeContext(provider);
+ context.LoginHint = hint;
+ context.LoginHintToken = token;
+ context.IdentityTokenHint = identity;
+
+ // Act and assert
+ var exception = await Assert.ThrowsAsync(
+ async () => await new EvaluateBackchannelAuthenticationRequest().HandleAsync(context));
+
+ Assert.Equal(SR.GetResourceString(SR.ID0541), exception.Message);
+ }
+
+ [Fact]
+ public async Task AttachBackchannelAuthenticationRequestParameters_ParametersAreAttached()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateChallengeContext(provider);
+ context.BindingMessage = "W4SCT";
+ context.LoginHint = "bob@fabrikam.com";
+ context.RequestedExpiry = TimeSpan.FromSeconds(119.5);
+ context.Scopes.Add(Scopes.Profile);
+
+ // Act
+ await new AttachBackchannelAuthenticationRequestParameters().HandleAsync(context);
+
+ // Assert
+ Assert.NotNull(context.BackchannelAuthenticationRequest);
+ Assert.Equal("openid profile", context.BackchannelAuthenticationRequest.Scope);
+ Assert.Equal("bob@fabrikam.com", context.BackchannelAuthenticationRequest.LoginHint);
+ Assert.Equal("W4SCT", context.BackchannelAuthenticationRequest.BindingMessage);
+ Assert.Equal(120, context.BackchannelAuthenticationRequest.RequestedExpiry);
+ Assert.Null(context.BackchannelAuthenticationRequest.IdTokenHint);
+ }
+
+ [Fact]
+ public async Task ValidateAuthenticationRequestId_MissingIdentifierCausesAnError()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateResponseContext(provider, new OpenIddictResponse { ExpiresIn = 120 });
+
+ // Act
+ await new Backchannel.ValidateAuthenticationRequestId().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(Errors.ServerError, context.Error);
+ Assert.Equal(SR.FormatID2168(Parameters.AuthReqId), context.ErrorDescription);
+ }
+
+ [Fact]
+ public async Task ValidateExpiration_MissingExpirationCausesAnError()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateResponseContext(provider, new OpenIddictResponse { AuthReqId = "id" });
+
+ // Act
+ await new Backchannel.ValidateExpiration().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(SR.FormatID2168(Parameters.ExpiresIn), context.ErrorDescription);
+ }
+
+ [Theory]
+ [InlineData(Errors.UnknownUserId, Errors.UnknownUserId)]
+ [InlineData(Errors.ExpiredLoginHintToken, Errors.ExpiredLoginHintToken)]
+ [InlineData(Errors.InvalidClient, Errors.InvalidRequest)]
+ [InlineData("custom_error", Errors.ServerError)]
+ public async Task HandleErrorResponse_ErrorsAreMapped(string error, string expected)
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateResponseContext(provider, new OpenIddictResponse { Error = error });
+
+ // Act
+ await new Backchannel.HandleErrorResponse().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(expected, context.Error);
+ }
+
+ [Fact]
+ public async Task ValidateWellKnownParameters_InvalidAuthenticationRequestIdTypeCausesAnError()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var context = CreateResponseContext(provider, new OpenIddictResponse(
+ JsonSerializer.Deserialize("""{ "auth_req_id": 42, "expires_in": 120 }""")));
+
+ // Act
+ await new Backchannel.ValidateWellKnownParameters().HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(SR.FormatID2107(Parameters.AuthReqId), context.ErrorDescription);
+ }
+
+ [Fact]
+ public async Task ExtractBackchannelAuthenticationEndpoint_MetadataIsExtracted()
+ {
+ // Arrange
+ using var provider = CreateProvider();
+ var options = provider.GetRequiredService>().CurrentValue;
+
+ var context = new HandleConfigurationResponseContext(new OpenIddictClientTransaction
+ {
+ CancellationToken = CancellationToken.None,
+ Configuration = new OpenIddictConfiguration(),
+ Options = options,
+ Registration = options.Registrations[0],
+ ServiceProvider = provider
+ })
+ {
+ Response = new OpenIddictResponse(JsonSerializer.Deserialize("""
+ {
+ "backchannel_authentication_endpoint": "https://www.contoso.com/connect/ciba",
+ "backchannel_token_delivery_modes_supported": [ "poll" ],
+ "backchannel_user_code_parameter_supported": false
+ }
+ """))
+ };
+
+ // Act
+ await new OpenIddictClientHandlers.Discovery.ExtractBackchannelAuthenticationEndpoint().HandleAsync(context);
+
+ // Assert
+ Assert.False(context.IsRejected);
+ Assert.Equal(new Uri("https://www.contoso.com/connect/ciba"), context.Configuration.BackchannelAuthenticationEndpoint);
+ Assert.Contains(BackchannelTokenDeliveryModes.Poll, context.Configuration.BackchannelTokenDeliveryModesSupported);
+ Assert.False(context.Configuration.BackchannelUserCodeParameterSupported);
+ }
+
+ private static ServiceProvider CreateProvider()
+ {
+ var services = new ServiceCollection();
+
+ services.AddOpenIddict()
+ .AddClient(options =>
+ {
+ options.AllowClientInitiatedBackchannelAuthenticationFlow();
+
+ options.AddEphemeralEncryptionKey()
+ .AddEphemeralSigningKey();
+
+ options.AddRegistration(new OpenIddictClientRegistration
+ {
+ ClientId = "Fabrikam",
+ Configuration = new OpenIddictConfiguration
+ {
+ Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute)
+ },
+ Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute)
+ });
+ });
+
+ return services.BuildServiceProvider();
+ }
+
+ private static ProcessChallengeContext CreateChallengeContext(IServiceProvider provider)
+ {
+ var options = provider.GetRequiredService>().CurrentValue;
+
+ return new ProcessChallengeContext(new OpenIddictClientTransaction
+ {
+ CancellationToken = CancellationToken.None,
+ Configuration = new OpenIddictConfiguration(),
+ Options = options,
+ Registration = options.Registrations[0],
+ Request = new OpenIddictRequest(),
+ ServiceProvider = provider
+ })
+ {
+ ClientId = "Fabrikam",
+ GrantType = GrantTypes.Ciba,
+ Principal = new ClaimsPrincipal(new ClaimsIdentity())
+ };
+ }
+
+ private static HandleBackchannelAuthenticationResponseContext CreateResponseContext(
+ IServiceProvider provider, OpenIddictResponse response)
+ {
+ var options = provider.GetRequiredService>().CurrentValue;
+
+ return new HandleBackchannelAuthenticationResponseContext(new OpenIddictClientTransaction
+ {
+ CancellationToken = CancellationToken.None,
+ Configuration = new OpenIddictConfiguration(),
+ Options = options,
+ Registration = options.Registrations[0],
+ ServiceProvider = provider
+ })
+ {
+ Request = new OpenIddictRequest(),
+ Response = response
+ };
+ }
+}