Browse Source

Add Client-Initiated Backchannel Authentication (poll mode) to the client stack

- OpenIddictClientService.ChallengeUsingBackchannelAsync/AuthenticateWithBackchannelAsync.
- Backchannel authentication request pipeline (client authentication negotiation, client
  assertions, mTLS certificates, System.Net.Http integration, response validation).
- CIBA grant support at the token endpoint (auth_req_id, identity token required).
- Discovery extraction of the backchannel authentication metadata.
- Only enforce the pushed authorization requests requirement for interactive flows.
pull/2549/head
pieroviano 2 months ago
parent
commit
b67cf1f3fc
  1. 42
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 41
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Backchannel.cs
  3. 1
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  4. 9
      src/OpenIddict.Client/OpenIddictClientBuilder.cs
  5. 123
      src/OpenIddict.Client/OpenIddictClientEvents.Backchannel.cs
  6. 60
      src/OpenIddict.Client/OpenIddictClientEvents.cs
  7. 1
      src/OpenIddict.Client/OpenIddictClientExtensions.cs
  8. 14
      src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs
  9. 203
      src/OpenIddict.Client/OpenIddictClientHandlers.Backchannel.cs
  10. 56
      src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
  11. 423
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  12. 223
      src/OpenIddict.Client/OpenIddictClientModels.cs
  13. 318
      src/OpenIddict.Client/OpenIddictClientService.cs
  14. 236
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs

42
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -1821,6 +1821,36 @@ To attach it, enable the pass-through mode or register a custom event handler fo
<data name="ID0535" xml:space="preserve">
<value>The authentication request identifier could not be generated: {0} ({1}).</value>
</data>
<data name="ID0536" xml:space="preserve">
<value>An authentication request identifier must be specified when using the Client-Initiated Backchannel Authentication grant.</value>
</data>
<data name="ID0537" xml:space="preserve">
<value>An error occurred while preparing the backchannel authentication request.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0538" xml:space="preserve">
<value>An error occurred while sending the backchannel authentication request.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0539" xml:space="preserve">
<value>An error occurred while extracting the backchannel authentication response.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0540" xml:space="preserve">
<value>An error occurred while handling the backchannel authentication response.
Error: {0}
Error description: {1}
Error URI: {2}</value>
</data>
<data name="ID0541" xml:space="preserve">
<value>Exactly one of the login hint, login hint token or identity token hint must be specified when using the Client-Initiated Backchannel Authentication grant.</value>
</data>
<data name="ID0532" xml:space="preserve">
<value>The backchannel authentication request was not correctly extracted.
To extract backchannel authentication requests, create a class implementing 'IOpenIddictServerHandler&lt;ExtractBackchannelAuthenticationRequestContext&gt;' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.</value>
@ -2485,6 +2515,9 @@ To apply backchannel authentication responses, create a class implementing 'IOpe
<data name="ID2218" xml:space="preserve">
<value>The client application is not allowed to use the Client-Initiated Backchannel Authentication flow.</value>
</data>
<data name="ID2219" xml:space="preserve">
<value>The backchannel authentication request was rejected by the remote server.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>
@ -3373,6 +3406,15 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6305" xml:space="preserve">
<value>The backchannel authentication request was rejected because invalid scopes were specified: {Scopes}.</value>
</data>
<data name="ID6306" xml:space="preserve">
<value>The backchannel authentication request was rejected by the remote authorization server: {Response}.</value>
</data>
<data name="ID6307" xml:space="preserve">
<value>The backchannel authentication request was successfully sent to {Uri}: {Request}.</value>
</data>
<data name="ID6308" xml:space="preserve">
<value>The backchannel authentication response returned by {Uri} was successfully extracted: {Response}.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

41
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<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Backchannel authentication request processing:
*/
CreateHttpClient<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
PreparePostHttpRequest<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachHttpVersion<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachJsonAcceptHeaders<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachUserAgentHeader<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachFromHeader<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachBasicAuthenticationCredentials<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
AttachHttpParameters<PrepareBackchannelAuthenticationRequestContext>.Descriptor,
SendHttpRequest<ApplyBackchannelAuthenticationRequestContext>.Descriptor,
DisposeHttpRequest<ApplyBackchannelAuthenticationRequestContext>.Descriptor,
/*
* Backchannel authentication response processing:
*/
DecompressResponseContent<ExtractBackchannelAuthenticationResponseContext>.Descriptor,
ExtractJsonHttpResponse<ExtractBackchannelAuthenticationResponseContext>.Descriptor,
ExtractWwwAuthenticateHeader<ExtractBackchannelAuthenticationResponseContext>.Descriptor,
ValidateHttpResponse<ExtractBackchannelAuthenticationResponseContext>.Descriptor,
DisposeHttpResponse<ExtractBackchannelAuthenticationResponseContext>.Descriptor
];
}
}

1
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs

@ -24,6 +24,7 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } =
[
.. Authorization.DefaultHandlers,
.. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,

9
src/OpenIddict.Client/OpenIddictClientBuilder.cs

@ -945,6 +945,15 @@ public sealed class OpenIddictClientBuilder
public OpenIddictClientBuilder AllowDeviceAuthorizationFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.DeviceCode));
/// <summary>
/// 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.
/// </summary>
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
public OpenIddictClientBuilder AllowClientInitiatedBackchannelAuthenticationFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.Ciba));
/// <summary>
/// Enables hybrid flow support. For more information
/// about this specific OpenID Connect flow, visit

123
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
{
/// <summary>
/// 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.
/// </summary>
public sealed class PrepareBackchannelAuthenticationRequestContext : BaseExternalContext
{
/// <summary>
/// Creates a new instance of the <see cref="PrepareBackchannelAuthenticationRequestContext"/> class.
/// </summary>
public PrepareBackchannelAuthenticationRequestContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
}
/// <summary>
/// Represents an event called for each request to the backchannel authentication endpoint
/// to send the backchannel authentication request to the remote authorization server.
/// </summary>
public sealed class ApplyBackchannelAuthenticationRequestContext : BaseExternalContext
{
/// <summary>
/// Creates a new instance of the <see cref="ApplyBackchannelAuthenticationRequestContext"/> class.
/// </summary>
public ApplyBackchannelAuthenticationRequestContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
}
/// <summary>
/// Represents an event called for each backchannel authentication response
/// to extract the response parameters from the server response.
/// </summary>
public sealed class ExtractBackchannelAuthenticationResponseContext : BaseExternalContext
{
/// <summary>
/// Creates a new instance of the <see cref="ExtractBackchannelAuthenticationResponseContext"/> class.
/// </summary>
public ExtractBackchannelAuthenticationResponseContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
/// <summary>
/// Gets or sets the response, or <see langword="null"/> if it wasn't extracted yet.
/// </summary>
public OpenIddictResponse? Response
{
get => Transaction.Response;
set => Transaction.Response = value;
}
}
/// <summary>
/// Represents an event called for each backchannel authentication response.
/// </summary>
public sealed class HandleBackchannelAuthenticationResponseContext : BaseExternalContext
{
/// <summary>
/// Creates a new instance of the <see cref="HandleBackchannelAuthenticationResponseContext"/> class.
/// </summary>
public HandleBackchannelAuthenticationResponseContext(OpenIddictClientTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request.
/// </summary>
public OpenIddictRequest Request
{
get => Transaction.Request!;
set => Transaction.Request = value;
}
/// <summary>
/// Gets or sets the response.
/// </summary>
public OpenIddictResponse Response
{
get => Transaction.Response!;
set => Transaction.Response = value;
}
}
}

60
src/OpenIddict.Client/OpenIddictClientEvents.cs

@ -796,6 +796,12 @@ public static partial class OpenIddictClientEvents
/// </summary>
public string? BackchannelIdentityToken { get; set; }
/// <summary>
/// Gets or sets the authentication request identifier (auth_req_id)
/// used with the CIBA grant, if applicable.
/// </summary>
public string? AuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets the device code to validate, if applicable.
/// </summary>
@ -1174,6 +1180,60 @@ public static partial class OpenIddictClientEvents
/// </summary>
public HashSet<string> Scopes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the optional login hint token that will be sent to the authorization server, if applicable.
/// </summary>
public string? LoginHintToken { get; set; }
/// <summary>
/// Gets or sets the optional binding message that will be sent to
/// the backchannel authentication endpoint, if applicable.
/// </summary>
public string? BindingMessage { get; set; }
/// <summary>
/// Gets or sets the optional requested expiry that will be sent to
/// the backchannel authentication endpoint, if applicable.
/// </summary>
public TimeSpan? RequestedExpiry { get; set; }
/// <summary>
/// Gets or sets the URI of the backchannel authentication endpoint, if applicable.
/// </summary>
public Uri? BackchannelAuthenticationEndpoint { get; set; }
/// <summary>
/// Gets or sets the client authentication method used when communicating
/// with the backchannel authentication endpoint, if applicable.
/// </summary>
public string? BackchannelAuthenticationEndpointClientAuthenticationMethod { get; set; }
/// <summary>
/// Gets or sets the X.509 client certificate used when communicating
/// with the backchannel authentication endpoint, if applicable.
/// </summary>
public X509Certificate2? BackchannelAuthenticationEndpointClientCertificate { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether a backchannel authentication request should be sent.
/// </summary>
public bool SendBackchannelAuthenticationRequest { get; set; }
/// <summary>
/// Gets or sets the request sent to the backchannel authentication endpoint, if applicable.
/// </summary>
public OpenIddictRequest? BackchannelAuthenticationRequest { get; set; }
/// <summary>
/// Gets or sets the response returned by the backchannel authentication endpoint, if applicable.
/// </summary>
public OpenIddictResponse? BackchannelAuthenticationResponse { get; set; }
/// <summary>
/// Gets or sets the authentication request identifier returned by the backchannel authentication endpoint, if applicable.
/// </summary>
public string? AuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets the URI of the device authorization endpoint, if applicable.
/// </summary>

1
src/OpenIddict.Client/OpenIddictClientExtensions.cs

@ -56,6 +56,7 @@ public static class OpenIddictClientExtensions
builder.Services.TryAddSingleton<RequirePostLogoutRedirectionRequest>();
builder.Services.TryAddSingleton<RequirePushedAuthorizationRequest>();
builder.Services.TryAddSingleton<RequireRequestObject>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationRequest>();
builder.Services.TryAddSingleton<RequireRedirectionRequest>();
builder.Services.TryAddSingleton<RequireRefreshTokenValidated>();
builder.Services.TryAddSingleton<RequireRevocationClientAssertionGenerated>();

14
src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs

@ -350,6 +350,20 @@ public static class OpenIddictClientHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if no backchannel authentication request is expected to be sent.
/// </summary>
public sealed class RequireBackchannelAuthenticationRequest : IOpenIddictClientHandlerFilter<ProcessChallengeContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(ProcessChallengeContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.SendBackchannelAuthenticationRequest);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if no request object is expected to be sent.
/// </summary>

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

56
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
}
}
/// <summary>
/// Contains the logic responsible for extracting the backchannel authentication
/// endpoint URI and the associated metadata from the discovery document.
/// </summary>
public sealed class ExtractBackchannelAuthenticationEndpoint : IOpenIddictClientHandler<HandleConfigurationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleConfigurationResponseContext>()
.UseSingletonHandler<ExtractBackchannelAuthenticationEndpoint>()
.SetOrder(ExtractDeviceAuthorizationEndpoint.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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<string?>?) context.Response[Metadata.BackchannelTokenDeliveryModesSupported] ?? [])
{
if (!string.IsNullOrEmpty(mode))
{
context.Configuration.BackchannelTokenDeliveryModesSupported.Add(mode);
}
}
context.Configuration.BackchannelUserCodeParameterSupported = (bool?)
context.Response[Metadata.BackchannelUserCodeParameterSupported];
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting the introspection endpoint URI from the discovery document.
/// </summary>

423
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
}
}
/// <summary>
/// Contains the logic responsible for determining whether a backchannel authentication request should be sent.
/// </summary>
public sealed class EvaluateBackchannelAuthenticationRequest : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.UseSingletonHandler<EvaluateBackchannelAuthenticationRequest>()
.SetOrder(EvaluateDeviceAuthorizationRequest.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for negotiating the best backchannel authentication endpoint
/// client authentication method supported by both the client and the authorization server.
/// </summary>
public sealed class AttachBackchannelAuthenticationEndpointClientAuthenticationMethod : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<AttachBackchannelAuthenticationEndpointClientAuthenticationMethod>()
.SetOrder(AttachDeviceAuthorizationEndpointClientAuthenticationMethod.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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<string>,
_ => 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;
}
}
/// <summary>
/// Contains the logic responsible for attaching the client certificate used for
/// the backchannel authentication endpoint to the challenge context, if applicable.
/// </summary>
public sealed class AttachBackchannelAuthenticationEndpointClientCertificate : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<AttachBackchannelAuthenticationEndpointClientCertificate>()
.SetOrder(AttachDeviceAuthorizationEndpointClientCertificate.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for resolving the URI of the backchannel authentication endpoint.
/// </summary>
public sealed class ResolveBackchannelAuthenticationEndpoint : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<ResolveBackchannelAuthenticationEndpoint>()
.SetOrder(ResolveDeviceAuthorizationEndpoint.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for attaching the parameters to the backchannel authentication request, if applicable.
/// </summary>
public sealed class AttachBackchannelAuthenticationRequestParameters : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<AttachBackchannelAuthenticationRequestParameters>()
.SetOrder(AttachDeviceAuthorizationRequestParameters.Descriptor.Order + 500)
.Build();
/// <inheritdoc/>
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<string>(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;
}
}
/// <summary>
/// Contains the logic responsible for attaching the client credentials to the backchannel authentication request, if applicable.
/// </summary>
public sealed class AttachBackchannelAuthenticationRequestClientCredentials : IOpenIddictClientHandler<ProcessChallengeContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<AttachBackchannelAuthenticationRequestClientCredentials>()
.SetOrder(AttachDeviceAuthorizationRequestClientCredentials.Descriptor.Order + 500)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for sending the backchannel authentication request, if applicable.
/// </summary>
public sealed class SendBackchannelAuthenticationRequest : IOpenIddictClientHandler<ProcessChallengeContext>
{
private readonly OpenIddictClientService _service;
public SendBackchannelAuthenticationRequest(OpenIddictClientService service)
=> _service = service ?? throw new ArgumentNullException(nameof(service));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<SendBackchannelAuthenticationRequest>()
.SetOrder(SendDeviceAuthorizationRequest.Descriptor.Order + 500)
.Build();
/// <inheritdoc/>
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;
}
}
/// <summary>
/// Contains the logic responsible for attaching the client credentials to the pushed authorization endpoint request, if applicable.
/// </summary>
@ -7263,6 +7672,8 @@ public static partial class OpenIddictClientHandlers
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessChallengeContext>()
// Note: pushed authorization requests only apply to interactive flows (e.g device or CIBA flows are not affected).
.AddFilter<RequireInteractiveGrantType>()
.UseSingletonHandler<ValidatePushedAuthorizationRequirement>()
.SetOrder(AttachPushedAuthorizationRequestClientCredentials.Descriptor.Order + 1_000)
.Build();

223
src/OpenIddict.Client/OpenIddictClientModels.cs

@ -651,6 +651,229 @@ public static class OpenIddictClientModels
public required ClaimsPrincipal? UserInfoTokenPrincipal { get; init; }
}
/// <summary>
/// Represents a backchannel authentication request (CIBA token polling).
/// </summary>
public sealed record class BackchannelAuthenticationRequest
{
/// <summary>
/// Gets or sets the parameters that will be added to the token request.
/// </summary>
public Dictionary<string, OpenIddictParameter>? AdditionalTokenRequestParameters { get; init; }
/// <summary>
/// Gets or sets the authentication request identifier returned during the challenge phase.
/// </summary>
public required string AuthenticationRequestId { get; init; }
/// <summary>
/// Gets or sets the cancellation token that will be
/// used to determine if the operation was aborted.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Gets or sets a boolean indicating whether userinfo should be disabled.
/// </summary>
public bool DisableUserInfo { get; init; }
/// <summary>
/// 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).
/// </summary>
public required TimeSpan Interval { get; init; }
/// <summary>
/// Gets or sets the issuer used to resolve the client registration.
/// </summary>
public Uri? Issuer { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that will be added to the context.
/// </summary>
public Dictionary<string, string?>? Properties { get; init; }
/// <summary>
/// Gets or sets the provider name used to resolve the client registration.
/// </summary>
public string? ProviderName { get; init; }
/// <summary>
/// Gets or sets the unique identifier of the client registration that will be used.
/// </summary>
public string? RegistrationId { get; init; }
/// <summary>
/// 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).
/// </summary>
public required TimeSpan Timeout { get; init; }
/// <summary>
/// Gets or sets the X.509 client certificate used to bind the access and/or
/// refresh tokens issued by the authorization server, if applicable.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public X509Certificate2? TokenBindingCertificate { get; init; }
}
/// <summary>
/// Represents a backchannel authentication result.
/// </summary>
public sealed record class BackchannelAuthenticationResult
{
/// <summary>
/// Gets or sets the access token.
/// </summary>
public required string AccessToken { get; init; }
/// <summary>
/// Gets or sets the expiration date of the access token, if available.
/// </summary>
public required DateTimeOffset? AccessTokenExpirationDate { get; init; }
/// <summary>
/// Gets or sets the identity token, if available.
/// </summary>
public required string? IdentityToken { get; init; }
/// <summary>
/// Gets or sets the principal extracted from the identity token, if available.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public required ClaimsPrincipal? IdentityTokenPrincipal { get; init; }
/// <summary>
/// Gets or sets a merged principal containing all the claims
/// extracted from the identity token and userinfo token principals.
/// </summary>
public required ClaimsPrincipal Principal { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that were present in the context.
/// </summary>
public required Dictionary<string, string?> Properties { get; init; }
/// <summary>
/// Gets or sets the refresh token, if available.
/// </summary>
public required string? RefreshToken { get; init; }
/// <summary>
/// Gets or sets the token response.
/// </summary>
public required OpenIddictResponse TokenResponse { get; init; }
/// <summary>
/// Gets or sets the userinfo token, if available.
/// </summary>
public required string? UserInfoToken { get; init; }
/// <summary>
/// Gets or sets the principal extracted from the userinfo token or response, if available.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public required ClaimsPrincipal? UserInfoTokenPrincipal { get; init; }
}
/// <summary>
/// Represents a backchannel challenge request (CIBA authentication request).
/// </summary>
public sealed record class BackchannelChallengeRequest
{
/// <summary>
/// Gets or sets the parameters that will be added to the backchannel authentication request.
/// </summary>
public Dictionary<string, OpenIddictParameter>? AdditionalBackchannelAuthenticationRequestParameters { get; init; }
/// <summary>
/// Gets or sets the binding message displayed to the end user, if applicable.
/// </summary>
public string? BindingMessage { get; init; }
/// <summary>
/// Gets or sets the cancellation token that will be
/// used to determine if the operation was aborted.
/// </summary>
public CancellationToken CancellationToken { get; init; }
/// <summary>
/// Gets or sets the identity token hint used to identify the end user, if applicable.
/// </summary>
public string? IdentityTokenHint { get; init; }
/// <summary>
/// Gets or sets the issuer used to resolve the client registration.
/// </summary>
public Uri? Issuer { get; init; }
/// <summary>
/// Gets or sets the login hint used to identify the end user, if applicable.
/// </summary>
public string? LoginHint { get; init; }
/// <summary>
/// Gets or sets the login hint token used to identify the end user, if applicable.
/// </summary>
public string? LoginHintToken { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that will be added to the context.
/// </summary>
public Dictionary<string, string?>? Properties { get; init; }
/// <summary>
/// Gets or sets the provider name used to resolve the client registration.
/// </summary>
public string? ProviderName { get; init; }
/// <summary>
/// Gets or sets the unique identifier of the client registration that will be used.
/// </summary>
public string? RegistrationId { get; init; }
/// <summary>
/// Gets or sets the requested lifetime of the authentication request identifier, if applicable.
/// </summary>
public TimeSpan? RequestedExpiry { get; init; }
/// <summary>
/// Gets the scopes that will be sent to the authorization server.
/// </summary>
public List<string>? Scopes { get; init; }
}
/// <summary>
/// Represents a backchannel challenge result.
/// </summary>
public sealed record class BackchannelChallengeResult
{
/// <summary>
/// Gets or sets the authentication request identifier.
/// </summary>
public required string AuthenticationRequestId { get; init; }
/// <summary>
/// Gets or sets the backchannel authentication response.
/// </summary>
public required OpenIddictResponse BackchannelAuthenticationResponse { get; init; }
/// <summary>
/// Gets or sets the remaining lifetime of the authentication request identifier.
/// </summary>
public required TimeSpan ExpiresIn { get; init; }
/// <summary>
/// Gets or sets the interval at which token requests should be sent.
/// </summary>
public required TimeSpan Interval { get; init; }
/// <summary>
/// Gets or sets the application-specific properties that were present in the context.
/// </summary>
public required Dictionary<string, string?> Properties { get; init; }
}
/// <summary>
/// Represents a device authentication request.
/// </summary>

318
src/OpenIddict.Client/OpenIddictClientService.cs

@ -582,6 +582,179 @@ public class OpenIddictClientService
};
}
/// <summary>
/// Authenticates using the specified authentication request identifier (CIBA poll mode).
/// </summary>
/// <param name="request">The backchannel authentication request.</param>
/// <returns>The backchannel authentication result.</returns>
public async ValueTask<BackchannelAuthenticationResult> 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<IOpenIddictClientDispatcher>();
var options = scope.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
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<string, OpenIddictParameter> 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
}
}
}
/// <summary>
/// Initiates a Client-Initiated Backchannel Authentication (CIBA) process.
/// </summary>
/// <param name="request">The backchannel challenge request.</param>
/// <returns>The backchannel challenge result.</returns>
public async ValueTask<BackchannelChallengeResult> ChallengeUsingBackchannelAsync(BackchannelChallengeRequest request)
{
ArgumentNullException.ThrowIfNull(request);
request.CancellationToken.ThrowIfCancellationRequested();
await using var scope = _provider.CreateAsyncScope();
var dispatcher = scope.ServiceProvider.GetRequiredService<IOpenIddictClientDispatcher>();
var options = scope.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
var transaction = new OpenIddictClientTransaction
{
CancellationToken = request.CancellationToken,
Options = options.CurrentValue,
ServiceProvider = scope.ServiceProvider
};
var context = new ProcessChallengeContext(transaction)
{
BackchannelAuthenticationRequest = request.AdditionalBackchannelAuthenticationRequestParameters
is Dictionary<string, OpenIddictParameter> 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
};
}
/// <summary>
/// Authenticates using the specified device authorization code.
/// </summary>
@ -1650,6 +1823,151 @@ public class OpenIddictClientService
}
}
/// <summary>
/// Sends the backchannel authentication request and retrieves the corresponding response.
/// </summary>
/// <param name="registration">The client registration.</param>
/// <param name="configuration">The server configuration.</param>
/// <param name="request">The backchannel authentication request.</param>
/// <param name="uri">The uri of the remote backchannel authentication endpoint.</param>
/// <param name="method">The client authentication method, if applicable.</param>
/// <param name="certificate">The client certificate, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The backchannel authentication response.</returns>
internal async ValueTask<OpenIddictResponse> 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<IOpenIddictClientDispatcher>();
var options = scope.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
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<OpenIddictRequest> 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<OpenIddictRequest> 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<OpenIddictResponse> 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<OpenIddictResponse> 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;
}
}
/// <summary>
/// Sends the introspection request and retrieves the corresponding response.
/// </summary>

236
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<InvalidOperationException>(
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<JsonElement>("""{ "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<IOptionsMonitor<OpenIddictClientOptions>>().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<JsonElement>("""
{
"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<IOptionsMonitor<OpenIddictClientOptions>>().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<IOptionsMonitor<OpenIddictClientOptions>>().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
};
}
}
Loading…
Cancel
Save