Browse Source

Add OpenID Connect Client-Initiated Backchannel Authentication (poll mode) to the server stack

- New backchannel authentication endpoint (SetBackchannelAuthenticationEndpointUris,
  AllowClientInitiatedBackchannelAuthenticationFlow, ASP.NET Core/OWIN pass-through).
- auth_req_id issued as an inactive reference token, redeemed with the
  urn:openid:params:grant-type:ciba grant (authorization_pending, access_denied, expired_token).
- OpenIddictServerService to list, approve and reject pending requests.
- Generic polling interval (interval parameter + slow_down) for the device code and CIBA grants.
- Discovery metadata and configuration validation.
pull/2549/head
pieroviano 2 months ago
parent
commit
bbd52cbf99
  1. 30
      src/OpenIddict.Abstractions/OpenIddictConstants.cs
  2. 66
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 16
      src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
  4. 47
      src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs
  5. 45
      src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs
  6. 18
      src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs
  7. 10
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreBuilder.cs
  8. 1
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreExtensions.cs
  9. 5
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs
  10. 20
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlerFilters.cs
  11. 39
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Backchannel.cs
  12. 1
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
  13. 8
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreOptions.cs
  14. 10
      src/OpenIddict.Server.Owin/OpenIddictServerOwinBuilder.cs
  15. 1
      src/OpenIddict.Server.Owin/OpenIddictServerOwinExtensions.cs
  16. 5
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs
  17. 20
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlerFilters.cs
  18. 41
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Backchannel.cs
  19. 1
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
  20. 8
      src/OpenIddict.Server.Owin/OpenIddictServerOwinOptions.cs
  21. 73
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  22. 24
      src/OpenIddict.Server/OpenIddictServerConfiguration.cs
  23. 7
      src/OpenIddict.Server/OpenIddictServerEndpointType.cs
  24. 159
      src/OpenIddict.Server/OpenIddictServerEvents.Backchannel.cs
  25. 10
      src/OpenIddict.Server/OpenIddictServerEvents.Discovery.cs
  26. 10
      src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs
  27. 77
      src/OpenIddict.Server/OpenIddictServerEvents.cs
  28. 4
      src/OpenIddict.Server/OpenIddictServerExtensions.cs
  29. 42
      src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
  30. 859
      src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs
  31. 12
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  32. 27
      src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
  33. 64
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  34. 354
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  35. 20
      src/OpenIddict.Server/OpenIddictServerOptions.cs
  36. 329
      src/OpenIddict.Server/OpenIddictServerService.cs
  37. 521
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs
  38. 76
      test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs
  39. 52
      test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs
  40. 243
      test/OpenIddict.Server.Tests/OpenIddictServerServiceTests.cs

30
src/OpenIddict.Abstractions/OpenIddictConstants.cs

@ -126,8 +126,10 @@ public static class OpenIddictConstants
{
public const string AccessTokenLifetime = "oi_act_lft";
public const string Audience = "oi_aud";
public const string AuthenticationRequestIdLifetime = "oi_arid_lft";
public const string AuthorizationCodeLifetime = "oi_auc_lft";
public const string AuthorizationId = "oi_au_id";
public const string BindingMessage = "oi_bdg_msg";
public const string ClaimDestinationsMap = "oi_cl_dstn";
public const string CodeChallenge = "oi_cd_chlg";
public const string CodeChallengeMethod = "oi_cd_chlg_meth";
@ -165,6 +167,13 @@ public static class OpenIddictConstants
}
}
public static class BackchannelTokenDeliveryModes
{
public const string Ping = "ping";
public const string Poll = "poll";
public const string Push = "push";
}
public static class ClaimRequestMembers
{
public const string Essential = "essential";
@ -224,10 +233,12 @@ public static class OpenIddictConstants
public const string AccountSelectionRequired = "account_selection_required";
public const string AuthorizationPending = "authorization_pending";
public const string ConsentRequired = "consent_required";
public const string ExpiredLoginHintToken = "expired_login_hint_token";
public const string ExpiredToken = "expired_token";
public const string InsufficientAccess = "insufficient_access";
public const string InsufficientScope = "insufficient_scope";
public const string InteractionRequired = "interaction_required";
public const string InvalidBindingMessage = "invalid_binding_message";
public const string InvalidClient = "invalid_client";
public const string InvalidGrant = "invalid_grant";
public const string InvalidRequest = "invalid_request";
@ -236,8 +247,10 @@ public static class OpenIddictConstants
public const string InvalidScope = "invalid_scope";
public const string InvalidTarget = "invalid_target";
public const string InvalidToken = "invalid_token";
public const string InvalidUserCode = "invalid_user_code";
public const string LoginRequired = "login_required";
public const string MissingToken = "missing_token";
public const string MissingUserCode = "missing_user_code";
public const string RegistrationNotSupported = "registration_not_supported";
public const string RequestNotSupported = "request_not_supported";
public const string RequestUriNotSupported = "request_uri_not_supported";
@ -245,6 +258,7 @@ public static class OpenIddictConstants
public const string SlowDown = "slow_down";
public const string TemporarilyUnavailable = "temporarily_unavailable";
public const string UnauthorizedClient = "unauthorized_client";
public const string UnknownUserId = "unknown_user_id";
public const string UnmetAuthenticationRequirements = "unmet_authentication_requirements";
public const string UnsupportedGrantType = "unsupported_grant_type";
public const string UnsupportedResponseType = "unsupported_response_type";
@ -254,6 +268,7 @@ public static class OpenIddictConstants
public static class GrantTypes
{
public const string AuthorizationCode = "authorization_code";
public const string Ciba = "urn:openid:params:grant-type:ciba";
public const string ClientCredentials = "client_credentials";
public const string DeviceCode = "urn:ietf:params:oauth:grant-type:device_code";
public const string Implicit = "implicit";
@ -277,6 +292,7 @@ public static class OpenIddictConstants
public static class Private
{
public const string AuthenticationRequestId = "oi_arid+jwt";
public const string AuthorizationCode = "oi_auc+jwt";
public const string DeviceCode = "oi_dvc+jwt";
public const string RefreshToken = "oi_reft+jwt";
@ -291,6 +307,10 @@ public static class OpenIddictConstants
public const string AcrValuesSupported = "acr_values_supported";
public const string AuthorizationEndpoint = "authorization_endpoint";
public const string AuthorizationResponseIssParameterSupported = "authorization_response_iss_parameter_supported";
public const string BackchannelAuthenticationEndpoint = "backchannel_authentication_endpoint";
public const string BackchannelAuthenticationRequestSigningAlgValuesSupported = "backchannel_authentication_request_signing_alg_values_supported";
public const string BackchannelTokenDeliveryModesSupported = "backchannel_token_delivery_modes_supported";
public const string BackchannelUserCodeParameterSupported = "backchannel_user_code_parameter_supported";
public const string ClaimsLocalesSupported = "claims_locales_supported";
public const string ClaimsParameterSupported = "claims_parameter_supported";
public const string ClaimsSupported = "claims_supported";
@ -365,11 +385,14 @@ public static class OpenIddictConstants
public const string ActorTokenType = "actor_token_type";
public const string Assertion = "assertion";
public const string Audience = "audience";
public const string AuthReqId = "auth_req_id";
public const string BindingMessage = "binding_message";
public const string Claims = "claims";
public const string ClaimsLocales = "claims_locales";
public const string ClientAssertion = "client_assertion";
public const string ClientAssertionType = "client_assertion_type";
public const string ClientId = "client_id";
public const string ClientNotificationToken = "client_notification_token";
public const string ClientSecret = "client_secret";
public const string Code = "code";
public const string CodeChallenge = "code_challenge";
@ -389,6 +412,7 @@ public static class OpenIddictConstants
public const string Iss = "iss";
public const string IssuedTokenType = "issued_token_type";
public const string LoginHint = "login_hint";
public const string LoginHintToken = "login_hint_token";
public const string Keys = "keys";
public const string MaxAge = "max_age";
public const string Nonce = "nonce";
@ -400,6 +424,7 @@ public static class OpenIddictConstants
public const string RefreshToken = "refresh_token";
public const string Registration = "registration";
public const string Request = "request";
public const string RequestedExpiry = "requested_expiry";
public const string RequestedTokenType = "requested_token_type";
public const string RequestUri = "request_uri";
public const string Resource = "resource";
@ -424,6 +449,7 @@ public static class OpenIddictConstants
public static class Endpoints
{
public const string Authorization = "ept:authorization";
public const string BackchannelAuthentication = "ept:backchannel_authentication";
public const string DeviceAuthorization = "ept:device_authorization";
public const string EndSession = "ept:end_session";
public const string Introspection = "ept:introspection";
@ -435,6 +461,7 @@ public static class OpenIddictConstants
public static class GrantTypes
{
public const string AuthorizationCode = "gt:authorization_code";
public const string Ciba = "gt:urn:openid:params:grant-type:ciba";
public const string ClientCredentials = "gt:client_credentials";
public const string DeviceCode = "gt:urn:ietf:params:oauth:grant-type:device_code";
public const string Implicit = "gt:implicit";
@ -487,6 +514,7 @@ public static class OpenIddictConstants
public static class Properties
{
public const string Destinations = ".destinations";
public const string LastPollingDate = ".last_polling_date";
}
public static class RequestTokenTypes
@ -579,6 +607,7 @@ public static class OpenIddictConstants
public static class TokenLifetimes
{
public const string AccessToken = "tkn_lft:act";
public const string AuthenticationRequestId = "tkn_lft:arid";
public const string AuthorizationCode = "tkn_lft:auc";
public const string DeviceCode = "tkn_lft:dvc";
public const string IdentityToken = "tkn_lft:idt";
@ -647,6 +676,7 @@ public static class OpenIddictConstants
public static class Private
{
public const string AuthenticationRequestId = "urn:openiddict:params:oauth:token-type:auth_req_id";
public const string AuthorizationCode = "urn:openiddict:params:oauth:token-type:authorization_code";
public const string ClientAssertion = "urn:openiddict:params:oauth:token-type:client_assertion";
public const string DeviceCode = "urn:openiddict:params:oauth:token-type:device_code";

66
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -1801,6 +1801,33 @@ To enable request object support, call 'services.AddOpenIddict().AddServer().Ena
<data name="ID0526" xml:space="preserve">
<value>A signed request object must be sent but no asymmetric signing key was attached to the client registration.
To use signed request objects, attach an asymmetric signing key or certificate to the client registration.</value>
</data>
<data name="ID0527" xml:space="preserve">
<value>The backchannel authentication endpoint must be enabled to use the Client-Initiated Backchannel Authentication flow.</value>
</data>
<data name="ID0528" xml:space="preserve">
<value>The Client-Initiated Backchannel Authentication flow must be enabled when the backchannel authentication endpoint is enabled.</value>
</data>
<data name="ID0529" xml:space="preserve">
<value>The Client-Initiated Backchannel Authentication flow cannot be used when the degraded mode is enabled, when token storage is disabled or when no explicit issuer is configured.</value>
</data>
<data name="ID0531" xml:space="preserve">
<value>A principal containing an authenticated identity and a subject claim must be attached to the backchannel authentication request context.
To attach it, enable the pass-through mode or register a custom event handler for the 'HandleBackchannelAuthenticationRequestContext' event.</value>
</data>
<data name="ID0534" xml:space="preserve">
<value>The principal used to approve a backchannel authentication request must contain an authenticated identity and the same subject as the one attached to the request.</value>
</data>
<data name="ID0535" xml:space="preserve">
<value>The authentication request identifier could not be generated: {0} ({1}).</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>
</data>
<data name="ID0533" xml:space="preserve">
<value>The backchannel authentication response was not correctly applied.
To apply backchannel authentication responses, create a class implementing 'IOpenIddictServerHandler&lt;ApplyBackchannelAuthenticationResponseContext&gt;' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.</value>
</data>
<data name="ID2000" xml:space="preserve">
<value>The security token is missing.</value>
@ -2440,6 +2467,24 @@ To use signed request objects, attach an asymmetric signing key or certificate t
<data name="ID2212" xml:space="preserve">
<value>The '{0}' claim of the request object is missing or invalid.</value>
</data>
<data name="ID2213" xml:space="preserve">
<value>The client application is polling the token endpoint too frequently.</value>
</data>
<data name="ID2214" xml:space="preserve">
<value>Exactly one of the 'login_hint', 'login_hint_token' or 'id_token_hint' parameters must be specified.</value>
</data>
<data name="ID2215" xml:space="preserve">
<value>The mandatory 'openid' scope is missing.</value>
</data>
<data name="ID2216" xml:space="preserve">
<value>The '{0}' parameter is required when using the Client-Initiated Backchannel Authentication grant.</value>
</data>
<data name="ID2217" xml:space="preserve">
<value>This client application is not allowed to use the backchannel authentication endpoint.</value>
</data>
<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="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>
@ -3307,6 +3352,27 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6298" xml:space="preserve">
<value>The authorization request was rejected because the request object was invalid: {Error} ({Description}).</value>
</data>
<data name="ID6299" xml:space="preserve">
<value>The token request was rejected because the client application polled the token '{Identifier}' too frequently.</value>
</data>
<data name="ID6300" xml:space="preserve">
<value>The backchannel authentication request was successfully extracted: {Request}.</value>
</data>
<data name="ID6301" xml:space="preserve">
<value>The backchannel authentication request was successfully validated.</value>
</data>
<data name="ID6302" xml:space="preserve">
<value>The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the backchannel authentication endpoint.</value>
</data>
<data name="ID6303" xml:space="preserve">
<value>The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the Client-Initiated Backchannel Authentication flow.</value>
</data>
<data name="ID6304" xml:space="preserve">
<value>The backchannel authentication request was rejected because the application '{ClientId}' was not allowed to use the scope {Scope}.</value>
</data>
<data name="ID6305" xml:space="preserve">
<value>The backchannel authentication request was rejected because invalid scopes were specified: {Scopes}.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

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

@ -26,6 +26,22 @@ public sealed class OpenIddictConfiguration
/// </summary>
public bool? AuthorizationResponseIssParameterSupported { get; set; }
/// <summary>
/// Gets or sets the URI of the backchannel authentication endpoint.
/// </summary>
public Uri? BackchannelAuthenticationEndpoint { get; set; }
/// <summary>
/// Gets the backchannel token delivery modes supported by the server.
/// </summary>
public HashSet<string> BackchannelTokenDeliveryModesSupported { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets a boolean indicating whether the "user_code" parameter
/// is supported by the backchannel authentication endpoint.
/// </summary>
public bool? BackchannelUserCodeParameterSupported { get; set; }
/// <summary>
/// Gets the code challenge methods supported by the server.
/// </summary>

47
src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs

@ -500,6 +500,19 @@ public static class OpenIddictExtensions
return string.Equals(request.GrantType, GrantTypes.DeviceCode, StringComparison.Ordinal);
}
/// <summary>
/// Determines whether the "grant_type" parameter corresponds to the Client-Initiated Backchannel Authentication grant.
/// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html for more information.
/// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><see langword="true"/> if the request is a CIBA grant request, <see langword="false"/> otherwise.</returns>
public static bool IsCibaGrantType(this OpenIddictRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return string.Equals(request.GrantType, GrantTypes.Ciba, StringComparison.Ordinal);
}
/// <summary>
/// Determines whether the "grant_type" parameter corresponds to the password grant.
/// See http://tools.ietf.org/html/rfc6749#section-4.3.2 for more information.
@ -2564,6 +2577,22 @@ public static class OpenIddictExtensions
public static TimeSpan? GetAuthorizationCodeLifetime(this ClaimsPrincipal principal)
=> GetLifetime(principal, Claims.Private.AuthorizationCodeLifetime);
/// <summary>
/// Gets the authentication request identifier lifetime associated with the claims identity.
/// </summary>
/// <param name="identity">The claims identity.</param>
/// <returns>The authentication request identifier lifetime or <see langword="null"/> if the claim cannot be found.</returns>
public static TimeSpan? GetAuthenticationRequestIdLifetime(this ClaimsIdentity identity)
=> GetLifetime(identity, Claims.Private.AuthenticationRequestIdLifetime);
/// <summary>
/// Gets the authentication request identifier lifetime associated with the claims principal.
/// </summary>
/// <param name="principal">The claims principal.</param>
/// <returns>The authentication request identifier lifetime or <see langword="null"/> if the claim cannot be found.</returns>
public static TimeSpan? GetAuthenticationRequestIdLifetime(this ClaimsPrincipal principal)
=> GetLifetime(principal, Claims.Private.AuthenticationRequestIdLifetime);
/// <summary>
/// Gets the device code lifetime associated with the claims identity.
/// </summary>
@ -3234,6 +3263,24 @@ public static class OpenIddictExtensions
public static ClaimsPrincipal SetDeviceCodeLifetime(this ClaimsPrincipal principal, TimeSpan? lifetime)
=> principal.SetClaim(Claims.Private.DeviceCodeLifetime, (long?) lifetime?.TotalSeconds);
/// <summary>
/// Sets the authentication request identifier lifetime associated with the claims identity.
/// </summary>
/// <param name="identity">The claims identity.</param>
/// <param name="lifetime">The authentication request identifier lifetime to store.</param>
/// <returns>The claims identity.</returns>
public static ClaimsIdentity SetAuthenticationRequestIdLifetime(this ClaimsIdentity identity, TimeSpan? lifetime)
=> identity.SetClaim(Claims.Private.AuthenticationRequestIdLifetime, (long?) lifetime?.TotalSeconds);
/// <summary>
/// Sets the authentication request identifier lifetime associated with the claims principal.
/// </summary>
/// <param name="principal">The claims principal.</param>
/// <param name="lifetime">The authentication request identifier lifetime to store.</param>
/// <returns>The claims principal.</returns>
public static ClaimsPrincipal SetAuthenticationRequestIdLifetime(this ClaimsPrincipal principal, TimeSpan? lifetime)
=> principal.SetClaim(Claims.Private.AuthenticationRequestIdLifetime, (long?) lifetime?.TotalSeconds);
/// <summary>
/// Sets the identity token lifetime associated with the claims identity.
/// </summary>

45
src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs

@ -255,6 +255,51 @@ public class OpenIddictRequest : OpenIddictMessage
set => SetParameter(OpenIddictConstants.Parameters.CodeVerifier, value);
}
/// <summary>
/// Gets or sets the "auth_req_id" parameter.
/// </summary>
public string? AuthReqId
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.AuthReqId);
set => SetParameter(OpenIddictConstants.Parameters.AuthReqId, value);
}
/// <summary>
/// Gets or sets the "binding_message" parameter.
/// </summary>
public string? BindingMessage
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.BindingMessage);
set => SetParameter(OpenIddictConstants.Parameters.BindingMessage, value);
}
/// <summary>
/// Gets or sets the "client_notification_token" parameter.
/// </summary>
public string? ClientNotificationToken
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.ClientNotificationToken);
set => SetParameter(OpenIddictConstants.Parameters.ClientNotificationToken, value);
}
/// <summary>
/// Gets or sets the "login_hint_token" parameter.
/// </summary>
public string? LoginHintToken
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.LoginHintToken);
set => SetParameter(OpenIddictConstants.Parameters.LoginHintToken, value);
}
/// <summary>
/// Gets or sets the "requested_expiry" parameter.
/// </summary>
public long? RequestedExpiry
{
get => (long?) GetParameter(OpenIddictConstants.Parameters.RequestedExpiry);
set => SetParameter(OpenIddictConstants.Parameters.RequestedExpiry, value);
}
/// <summary>
/// Gets or sets the "device_code" parameter.
/// </summary>

18
src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs

@ -122,6 +122,24 @@ public class OpenIddictResponse : OpenIddictMessage
set => SetParameter(OpenIddictConstants.Parameters.Code, value);
}
/// <summary>
/// Gets or sets the "auth_req_id" parameter.
/// </summary>
public string? AuthReqId
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.AuthReqId);
set => SetParameter(OpenIddictConstants.Parameters.AuthReqId, value);
}
/// <summary>
/// Gets or sets the "interval" parameter.
/// </summary>
public long? Interval
{
get => (long?) GetParameter(OpenIddictConstants.Parameters.Interval);
set => SetParameter(OpenIddictConstants.Parameters.Interval, value);
}
/// <summary>
/// Gets or sets the "device_code" parameter.
/// </summary>

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

@ -74,6 +74,16 @@ public sealed class OpenIddictServerAspNetCoreBuilder
public OpenIddictServerAspNetCoreBuilder EnableAuthorizationEndpointPassthrough()
=> Configure(options => options.EnableAuthorizationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect backchannel authentication endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests
/// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
/// <returns>The <see cref="OpenIddictServerAspNetCoreBuilder"/> instance.</returns>
public OpenIddictServerAspNetCoreBuilder EnableBackchannelAuthenticationEndpointPassthrough()
=> Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

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

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

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

@ -162,7 +162,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
// are attached to the authentication properties bag so they can be accessed from user code.
var principal = context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.EndSession
OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.BackchannelAuthentication
=> context.IdentityTokenPrincipal,
OpenIddictServerEndpointType.EndUserVerification => context.UserCodePrincipal,
@ -174,6 +175,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
=> context.AuthorizationCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
=> context.DeviceCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType()
=> context.AuthenticationRequestIdPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType()
=> context.RefreshTokenPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()

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

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

39
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Backchannel.cs

@ -0,0 +1,39 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
namespace OpenIddict.Server.AspNetCore;
public static partial class OpenIddictServerAspNetCoreHandlers
{
public static class Backchannel
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Backchannel authentication request extraction:
*/
ExtractPostRequest<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ExtractClientCertificate<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
/*
* Backchannel authentication request handling:
*/
EnablePassthroughMode<HandleBackchannelAuthenticationRequestContext, RequireBackchannelAuthenticationEndpointPassthroughEnabled>.Descriptor,
/*
* Backchannel authentication response processing:
*/
AttachHttpResponseCode<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
ProcessJsonResponse<ApplyBackchannelAuthenticationResponseContext>.Descriptor
];
}
}

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

@ -52,6 +52,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ResolveHostSignOutProperties.Descriptor,
.. Authentication.DefaultHandlers,
.. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,

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

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

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

@ -74,6 +74,16 @@ public sealed class OpenIddictServerOwinBuilder
public OpenIddictServerOwinBuilder EnableAuthorizationEndpointPassthrough()
=> Configure(options => options.EnableAuthorizationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect backchannel authentication endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.
/// Once validated, the rest of the request processing pipeline is invoked, so that OpenID Connect requests
/// can be handled at a later stage (in a custom middleware or in a MVC controller, for instance).
/// </summary>
/// <returns>The <see cref="OpenIddictServerOwinBuilder"/> instance.</returns>
public OpenIddictServerOwinBuilder EnableBackchannelAuthenticationEndpointPassthrough()
=> Configure(options => options.EnableBackchannelAuthenticationEndpointPassthrough = true);
/// <summary>
/// Enables the pass-through mode for the OpenID Connect end session endpoint.
/// When the pass-through mode is used, OpenID Connect requests are initially handled by OpenIddict.

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

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

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

@ -175,7 +175,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
// To return the most appropriate one, the principal is selected based on the endpoint type.
var principal = context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.EndSession
OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.BackchannelAuthentication
=> context.IdentityTokenPrincipal,
OpenIddictServerEndpointType.EndUserVerification => context.UserCodePrincipal,
@ -187,6 +188,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
=> context.AuthorizationCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
=> context.DeviceCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType()
=> context.AuthenticationRequestIdPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType()
=> context.RefreshTokenPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()

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

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

41
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Backchannel.cs

@ -0,0 +1,41 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
namespace OpenIddict.Server.Owin;
public static partial class OpenIddictServerOwinHandlers
{
public static class Backchannel
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Backchannel authentication request extraction:
*/
ExtractPostRequest<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ExtractClientCertificate<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractBackchannelAuthenticationRequestContext>.Descriptor,
/*
* Backchannel authentication request handling:
*/
EnablePassthroughMode<HandleBackchannelAuthenticationRequestContext, RequireBackchannelAuthenticationEndpointPassthroughEnabled>.Descriptor,
/*
* Backchannel authentication response processing:
*/
AttachHttpResponseCode<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
AttachOwinResponseChallenge<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
SuppressFormsAuthenticationRedirect<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyBackchannelAuthenticationResponseContext>.Descriptor,
ProcessJsonResponse<ApplyBackchannelAuthenticationResponseContext>.Descriptor
];
}
}

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

@ -50,6 +50,7 @@ public static partial class OpenIddictServerOwinHandlers
ResolveHostSignOutProperties.Descriptor,
.. Authentication.DefaultHandlers,
.. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,

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

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

73
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -914,7 +914,7 @@ public sealed class OpenIddictServerBuilder
GrantTypes.AuthorizationCode or GrantTypes.ClientCredentials or
GrantTypes.DeviceCode or GrantTypes.Implicit or
GrantTypes.Password or GrantTypes.RefreshToken or
GrantTypes.TokenExchange
GrantTypes.TokenExchange or GrantTypes.Ciba
=> throw new ArgumentException(SR.FormatID0517(type), nameof(type)),
_ => Configure(options => options.GrantTypes.Add(type))
@ -929,6 +929,15 @@ public sealed class OpenIddictServerBuilder
public OpenIddictServerBuilder AllowDeviceAuthorizationFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.DeviceCode));
/// <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="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowClientInitiatedBackchannelAuthenticationFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.Ciba));
/// <summary>
/// Enables hybrid flow support. For more information
/// about this specific OpenID Connect flow, visit
@ -1054,6 +1063,49 @@ public sealed class OpenIddictServerBuilder
});
}
/// <summary>
/// Sets the relative or absolute URIs associated to the backchannel authentication endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
/// Note: only the first URI will be returned as part of the discovery document.
/// </summary>
/// <param name="uris">The URIs associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetBackchannelAuthenticationEndpointUris(
[StringSyntax(StringSyntaxAttribute.Uri)] params string[] uris)
{
ArgumentNullException.ThrowIfNull(uris);
return SetBackchannelAuthenticationEndpointUris([.. uris.Select(uri => new Uri(uri, UriKind.RelativeOrAbsolute))]);
}
/// <summary>
/// Sets the relative or absolute URIs associated to the backchannel authentication endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
/// Note: only the first URI will be returned as part of the discovery document.
/// </summary>
/// <param name="uris">The URIs associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetBackchannelAuthenticationEndpointUris(params Uri[] uris)
{
ArgumentNullException.ThrowIfNull(uris);
if (Array.Exists(uris, OpenIddictHelpers.IsImplicitFileUri))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0072), nameof(uris));
}
if (Array.Exists(uris, static uri => uri.OriginalString.StartsWith("~", StringComparison.OrdinalIgnoreCase)))
{
throw new ArgumentException(SR.FormatID0081("~"), nameof(uris));
}
return Configure(options =>
{
options.BackchannelAuthenticationEndpointUris.Clear();
options.BackchannelAuthenticationEndpointUris.AddRange(uris);
});
}
/// <summary>
/// Sets the relative or absolute URIs associated to the configuration endpoint.
/// If an empty array is specified, the endpoint will be considered disabled.
@ -1792,6 +1844,25 @@ public sealed class OpenIddictServerBuilder
public OpenIddictServerBuilder SetDeviceCodeLifetime(TimeSpan? lifetime)
=> Configure(options => options.DeviceCodeLifetime = lifetime);
/// <summary>
/// Sets the authentication request identifier lifetime, after which client applications
/// are unable to send a grant_type=urn:openid:params:grant-type:ciba token request.
/// While discouraged, <see langword="null"/> can be specified to issue identifiers that never expire.
/// </summary>
/// <param name="lifetime">The authentication request identifier lifetime.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetAuthenticationRequestIdLifetime(TimeSpan? lifetime)
=> Configure(options => options.AuthenticationRequestIdLifetime = lifetime);
/// <summary>
/// Sets the minimum polling interval client applications must respect when using the device code
/// or CIBA grants. If <see langword="null"/> is specified, the polling interval is not enforced.
/// </summary>
/// <param name="interval">The polling interval.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetPollingInterval(TimeSpan? interval)
=> Configure(options => options.PollingInterval = interval);
/// <summary>
/// Sets the identity token lifetime, after which client
/// applications should refuse processing identity tokens.

24
src/OpenIddict.Server/OpenIddictServerConfiguration.cs

@ -222,6 +222,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
}
var uris = options.AuthorizationEndpointUris.Distinct()
.Concat(options.BackchannelAuthenticationEndpointUris.Distinct())
.Concat(options.ConfigurationEndpointUris.Distinct())
.Concat(options.JsonWebKeySetEndpointUris.Distinct())
.Concat(options.DeviceAuthorizationEndpointUris.Distinct())
@ -257,6 +258,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
// Ensure the token endpoint has been enabled when the authorization code,
// client credentials, device, password or refresh token grants are supported.
if (options.TokenEndpointUris.Count is 0 && (options.GrantTypes.Contains(GrantTypes.AuthorizationCode) ||
options.GrantTypes.Contains(GrantTypes.Ciba) ||
options.GrantTypes.Contains(GrantTypes.ClientCredentials) ||
options.GrantTypes.Contains(GrantTypes.DeviceCode) ||
options.GrantTypes.Contains(GrantTypes.Password) ||
@ -277,6 +279,25 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
builder.AddError(SR.GetResourceString(SR.ID0084));
}
// Ensure the backchannel authentication endpoint and the CIBA grant are always enabled together.
if (options.BackchannelAuthenticationEndpointUris.Count is 0 && options.GrantTypes.Contains(GrantTypes.Ciba))
{
builder.AddError(SR.GetResourceString(SR.ID0527));
}
if (options.BackchannelAuthenticationEndpointUris.Count is > 0 && !options.GrantTypes.Contains(GrantTypes.Ciba))
{
builder.AddError(SR.GetResourceString(SR.ID0528));
}
// Ensure the CIBA grant is not used with the degraded mode, with token storage disabled or without an explicit
// issuer, as authentication requests are persisted and completed outside the context of an HTTP request.
if (options.GrantTypes.Contains(GrantTypes.Ciba) &&
(options.EnableDegradedMode || options.DisableTokenStorage || options.Issuer is null))
{
builder.AddError(SR.GetResourceString(SR.ID0529));
}
// Ensure the grant types/response types configuration is consistent.
foreach (var type in options.ResponseTypes)
{
@ -298,7 +319,8 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
}
// Ensure at least one client authentication method is enabled (unless no non-interactive endpoint was enabled).
if (options.ClientAuthenticationMethods.Count is 0 && (options.DeviceAuthorizationEndpointUris.Count is not 0 ||
if (options.ClientAuthenticationMethods.Count is 0 && (options.BackchannelAuthenticationEndpointUris.Count is not 0 ||
options.DeviceAuthorizationEndpointUris.Count is not 0 ||
options.IntrospectionEndpointUris.Count is not 0 ||
options.PushedAuthorizationEndpointUris.Count is not 0 ||
options.RevocationEndpointUris.Count is not 0 ||

7
src/OpenIddict.Server/OpenIddictServerEndpointType.cs

@ -69,5 +69,10 @@ public enum OpenIddictServerEndpointType
/// <summary>
/// Pushed authorization endpoint.
/// </summary>
PushedAuthorization = 11
PushedAuthorization = 11,
/// <summary>
/// Backchannel authentication endpoint.
/// </summary>
BackchannelAuthentication = 12
}

159
src/OpenIddict.Server/OpenIddictServerEvents.Backchannel.cs

@ -0,0 +1,159 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Security.Claims;
namespace OpenIddict.Server;
public static partial class OpenIddictServerEvents
{
/// <summary>
/// Represents an event called for each request to the backchannel authentication endpoint to give
/// the user code a chance to manually extract the request from the ambient HTTP context.
/// </summary>
public sealed class ExtractBackchannelAuthenticationRequestContext : BaseValidatingContext
{
/// <summary>
/// Creates a new instance of the <see cref="ExtractBackchannelAuthenticationRequestContext"/> class.
/// </summary>
public ExtractBackchannelAuthenticationRequestContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request, or <see langword="null"/> if it wasn't extracted yet.
/// </summary>
public OpenIddictRequest? Request
{
get => Transaction.Request;
set => Transaction.Request = value;
}
}
/// <summary>
/// Represents an event called for each request to the backchannel authentication endpoint
/// to determine if the request is valid and should continue to be processed.
/// </summary>
public sealed class ValidateBackchannelAuthenticationRequestContext : BaseValidatingClientContext
{
/// <summary>
/// Creates a new instance of the <see cref="ValidateBackchannelAuthenticationRequestContext"/> class.
/// </summary>
public ValidateBackchannelAuthenticationRequestContext(OpenIddictServerTransaction 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 security principal extracted
/// from the identity token hint, if applicable.
/// </summary>
public ClaimsPrincipal? IdentityTokenHintPrincipal { get; set; }
}
/// <summary>
/// Represents an event called for each validated backchannel authentication request to allow the user code
/// to identify the end user (using the login_hint, login_hint_token or id_token_hint parameters), notify
/// the end user out-of-band and attach a principal containing the identity of the end user.
/// </summary>
public sealed class HandleBackchannelAuthenticationRequestContext : BaseValidatingTicketContext
{
/// <summary>
/// Creates a new instance of the <see cref="HandleBackchannelAuthenticationRequestContext"/> class.
/// </summary>
public HandleBackchannelAuthenticationRequestContext(OpenIddictServerTransaction 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 security principal extracted
/// from the identity token hint, if applicable.
/// </summary>
public ClaimsPrincipal? IdentityTokenHintPrincipal { get; set; }
/// <summary>
/// Gets the additional parameters returned to the client application.
/// </summary>
public Dictionary<string, OpenIddictParameter> Parameters { get; private set; }
= new(StringComparer.Ordinal);
/// <summary>
/// Allows OpenIddict to return a sign-in response using the specified principal.
/// </summary>
/// <param name="principal">The claims principal.</param>
public void SignIn(ClaimsPrincipal principal) => Principal = principal;
/// <summary>
/// Allows OpenIddict to return a sign-in response using the specified principal.
/// </summary>
/// <param name="principal">The claims principal.</param>
/// <param name="parameters">The additional parameters returned to the client application.</param>
public void SignIn(ClaimsPrincipal principal, IDictionary<string, OpenIddictParameter> parameters)
{
Principal = principal;
Parameters = new(parameters, StringComparer.Ordinal);
}
}
/// <summary>
/// Represents an event called before the backchannel authentication response is returned to the caller.
/// </summary>
public sealed class ApplyBackchannelAuthenticationResponseContext : BaseRequestContext
{
/// <summary>
/// Creates a new instance of the <see cref="ApplyBackchannelAuthenticationResponseContext"/> class.
/// </summary>
public ApplyBackchannelAuthenticationResponseContext(OpenIddictServerTransaction transaction)
: base(transaction)
{
}
/// <summary>
/// Gets or sets the request, or <see langword="null"/> if it couldn't be extracted.
/// </summary>
public OpenIddictRequest? Request
{
get => Transaction.Request;
set => Transaction.Request = value;
}
/// <summary>
/// Gets or sets the response.
/// </summary>
public OpenIddictResponse Response
{
get => Transaction.Response!;
set => Transaction.Response = value;
}
/// <summary>
/// Gets the error code returned to the client application.
/// When the response indicates a successful response,
/// this property returns <see langword="null"/>.
/// </summary>
public string? Error => Response.Error;
}
}

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

@ -96,6 +96,16 @@ public static partial class OpenIddictServerEvents
/// </summary>
public Uri? AuthorizationEndpoint { get; set; }
/// <summary>
/// Gets or sets the backchannel authentication endpoint URI.
/// </summary>
public Uri? BackchannelAuthenticationEndpoint { get; set; }
/// <summary>
/// Gets the backchannel token delivery modes supported by the authorization server.
/// </summary>
public HashSet<string> BackchannelTokenDeliveryModes { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the JSON Web Key Set endpoint URI.
/// </summary>

10
src/OpenIddict.Server/OpenIddictServerEvents.Exchange.cs

@ -72,6 +72,11 @@ public static partial class OpenIddictServerEvents
/// </summary>
public ClaimsPrincipal? DeviceCodePrincipal { get; set; }
/// <summary>
/// Gets or sets the security principal extracted from the authentication request identifier, if applicable.
/// </summary>
public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; }
/// <summary>
/// Gets or sets the security principal extracted from the refresh token, if applicable.
/// </summary>
@ -121,6 +126,11 @@ public static partial class OpenIddictServerEvents
/// </summary>
public ClaimsPrincipal? DeviceCodePrincipal { get; set; }
/// <summary>
/// Gets or sets the security principal extracted from the authentication request identifier, if applicable.
/// </summary>
public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; }
/// <summary>
/// Gets or sets the security principal extracted from the refresh token, if applicable.
/// </summary>

77
src/OpenIddict.Server/OpenIddictServerEvents.cs

@ -367,6 +367,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool ExtractDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an authentication
/// request identifier should be extracted from the current context.
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool ExtractAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether a generic
/// token should be extracted from the current context.
@ -466,6 +475,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool RequireDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an authentication request identifier
/// must be resolved for the authentication to be considered valid.
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool RequireAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether a generic token
/// must be resolved for the authentication to be considered valid.
@ -565,6 +583,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool ValidateDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the authentication request
/// identifier extracted from the current request should be validated.
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool ValidateAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the generic
/// token extracted from the current request should be validated.
@ -664,6 +691,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool RejectDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an invalid authentication request identifier
/// will cause the authentication demand to be rejected or will be ignored.
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool RejectAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an invalid generic token
/// will cause the authentication demand to be rejected or will be ignored.
@ -778,6 +814,16 @@ public static partial class OpenIddictServerEvents
/// </summary>
public ClaimsPrincipal? DeviceCodePrincipal { get; set; }
/// <summary>
/// Gets or sets the authentication request identifier to validate, if applicable.
/// </summary>
public string? AuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets the principal extracted from the authentication request identifier, if applicable.
/// </summary>
public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; }
/// <summary>
/// Gets or sets the generic token to validate, if applicable.
/// </summary>
@ -959,6 +1005,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool GenerateDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an authentication request
/// identifier should be generated (and optionally returned to the client).
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool GenerateAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether an issued token
/// should be generated (and optionally returned to the client).
@ -1031,6 +1086,15 @@ public static partial class OpenIddictServerEvents
/// </remarks>
public bool IncludeDeviceCode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the generated authentication request
/// identifier should be returned to the client application as part of the response.
/// </summary>
/// <remarks>
/// Note: overriding the value of this property is generally not recommended.
/// </remarks>
public bool IncludeAuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether the generated issued token
/// should be returned to the client application as part of the response.
@ -1115,6 +1179,19 @@ public static partial class OpenIddictServerEvents
/// </summary>
public ClaimsPrincipal? DeviceCodePrincipal { get; set; }
/// <summary>
/// Gets or sets the generated authentication request identifier, if applicable.
/// The identifier will only be returned if <see cref="IncludeAuthenticationRequestId"/>
/// is set to <see langword="true"/>.
/// </summary>
public string? AuthenticationRequestId { get; set; }
/// <summary>
/// Gets or sets the principal containing the claims that will be
/// used to create the authentication request identifier, if applicable.
/// </summary>
public ClaimsPrincipal? AuthenticationRequestIdPrincipal { get; set; }
/// <summary>
/// Gets or sets the generated issued token, if applicable.
/// The issued token will only be returned if

4
src/OpenIddict.Server/OpenIddictServerExtensions.cs

@ -30,6 +30,7 @@ public static class OpenIddictServerExtensions
builder.Services.AddOptions();
builder.Services.TryAddSingleton<IOpenIddictServerDispatcher, OpenIddictServerDispatcher>();
builder.Services.TryAddScoped<OpenIddictServerService>();
// Register the built-in server event handlers used by the OpenIddict server components.
// Note: the order used here is not important, as the actual order is set in the options.
@ -53,6 +54,9 @@ public static class OpenIddictServerExtensions
builder.Services.TryAddSingleton<RequireClientSecretParameter>();
builder.Services.TryAddSingleton<RequireConfigurationRequest>();
builder.Services.TryAddSingleton<RequireDegradedModeDisabled>();
builder.Services.TryAddSingleton<RequireAuthenticationRequestIdGenerated>();
builder.Services.TryAddSingleton<RequireAuthenticationRequestIdValidated>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationRequest>();
builder.Services.TryAddSingleton<RequireDeviceAuthorizationRequest>();
builder.Services.TryAddSingleton<RequireDeviceCodeGenerated>();
builder.Services.TryAddSingleton<RequireDeviceCodeValidated>();

42
src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs

@ -249,6 +249,48 @@ public static class OpenIddictServerHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if no authentication request identifier is generated.
/// </summary>
public sealed class RequireAuthenticationRequestIdGenerated : IOpenIddictServerHandlerFilter<ProcessSignInContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(ProcessSignInContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.GenerateAuthenticationRequestId);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if no authentication request identifier is validated.
/// </summary>
public sealed class RequireAuthenticationRequestIdValidated : IOpenIddictServerHandlerFilter<ProcessAuthenticationContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.ValidateAuthenticationRequestId);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the request is not a backchannel authentication request.
/// </summary>
public sealed class RequireBackchannelAuthenticationRequest : IOpenIddictServerHandlerFilter<BaseContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(BaseContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.EndpointType is OpenIddictServerEndpointType.BackchannelAuthentication);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if the request is not a device request.
/// </summary>

859
src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs

@ -0,0 +1,859 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.Diagnostics;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace OpenIddict.Server;
public static partial class OpenIddictServerHandlers
{
public static class Backchannel
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Backchannel authentication request top-level processing:
*/
ExtractBackchannelAuthenticationRequest.Descriptor,
ValidateBackchannelAuthenticationRequest.Descriptor,
HandleBackchannelAuthenticationRequest.Descriptor,
ApplyBackchannelAuthenticationResponse<ProcessChallengeContext>.Descriptor,
ApplyBackchannelAuthenticationResponse<ProcessErrorContext>.Descriptor,
ApplyBackchannelAuthenticationResponse<ProcessRequestContext>.Descriptor,
ApplyBackchannelAuthenticationResponse<ProcessSignInContext>.Descriptor,
/*
* Backchannel authentication request validation:
*/
ValidateRequestParameter.Descriptor,
ValidateScopeParameter.Descriptor,
ValidateHintParameters.Descriptor,
ValidateRequestedExpiryParameter.Descriptor,
ValidateClientCredentialsParameters.Descriptor,
ValidateScopes.Descriptor,
ValidateAuthentication.Descriptor,
ValidateEndpointPermissions.Descriptor,
ValidateGrantTypePermissions.Descriptor,
ValidateScopePermissions.Descriptor,
/*
* Backchannel authentication request handling:
*/
AttachPrincipal.Descriptor
];
/// <summary>
/// Contains the logic responsible for extracting backchannel authentication requests and invoking the corresponding event handlers.
/// </summary>
public sealed class ExtractBackchannelAuthenticationRequest : IOpenIddictServerHandler<ProcessRequestContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ExtractBackchannelAuthenticationRequest(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<ExtractBackchannelAuthenticationRequest>()
.SetOrder(100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new ExtractBackchannelAuthenticationRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
if (notification.Request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0532));
}
context.Logger.LogInformation(6300, SR.GetResourceString(SR.ID6300), notification.Request);
}
}
/// <summary>
/// Contains the logic responsible for validating backchannel authentication requests and invoking the corresponding event handlers.
/// </summary>
public sealed class ValidateBackchannelAuthenticationRequest : IOpenIddictServerHandler<ProcessRequestContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ValidateBackchannelAuthenticationRequest(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<ValidateBackchannelAuthenticationRequest>()
.SetOrder(ExtractBackchannelAuthenticationRequest.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new ValidateBackchannelAuthenticationRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification);
// Store the context object in the transaction so it can be later retrieved by handlers
// that want to access the identity token hint principal without triggering a new validation.
context.Transaction.SetProperty(typeof(ValidateBackchannelAuthenticationRequestContext).FullName!, notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
context.Logger.LogInformation(6301, SR.GetResourceString(SR.ID6301));
}
}
/// <summary>
/// Contains the logic responsible for handling backchannel authentication requests and invoking the corresponding event handlers.
/// </summary>
public sealed class HandleBackchannelAuthenticationRequest : IOpenIddictServerHandler<ProcessRequestContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public HandleBackchannelAuthenticationRequest(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<HandleBackchannelAuthenticationRequest>()
.SetOrder(ValidateBackchannelAuthenticationRequest.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new HandleBackchannelAuthenticationRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
// Unlike other endpoints, the backchannel authentication endpoint requires identifying the end user:
// since OpenIddict cannot resolve the user from the hints itself, a principal MUST be attached by
// the application (typically using the pass-through mode or a custom event handler).
if (notification.Principal is not { Identity.IsAuthenticated: true } principal ||
string.IsNullOrEmpty(principal.GetClaim(Claims.Subject)))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0531));
}
var @event = new ProcessSignInContext(context.Transaction)
{
Principal = principal,
Response = new OpenIddictResponse()
};
if (notification.Parameters.Count is > 0)
{
foreach (var parameter in notification.Parameters)
{
@event.Parameters.Add(parameter.Key, parameter.Value);
}
}
await _dispatcher.DispatchAsync(@event);
if (@event.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (@event.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (@event.IsRejected)
{
context.Reject(
error: @event.Error ?? Errors.InvalidGrant,
description: @event.ErrorDescription,
uri: @event.ErrorUri);
return;
}
}
}
/// <summary>
/// Contains the logic responsible for processing backchannel authentication responses and invoking the corresponding event handlers.
/// </summary>
public sealed class ApplyBackchannelAuthenticationResponse<TContext> : IOpenIddictServerHandler<TContext> where TContext : BaseRequestContext
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ApplyBackchannelAuthenticationResponse(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireBackchannelAuthenticationRequest>()
.UseSingletonHandler<ApplyBackchannelAuthenticationResponse<TContext>>()
.SetOrder(500_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new ApplyBackchannelAuthenticationResponseContext(context.Transaction);
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
throw new InvalidOperationException(SR.GetResourceString(SR.ID0533));
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that specify the unsupported request parameter.
/// </summary>
public sealed class ValidateRequestParameter : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateRequestParameter>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Note: signed authentication requests are not supported yet.
if (!string.IsNullOrEmpty(context.Request.Request))
{
context.Reject(
error: Errors.RequestNotSupported,
description: SR.FormatID2028(Parameters.Request),
uri: SR.FormatID8000(SR.ID2028));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that don't specify a valid scope parameter.
/// </summary>
public sealed class ValidateScopeParameter : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateScopeParameter>()
.SetOrder(ValidateRequestParameter.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Backchannel authentication requests MUST contain the "openid" scope.
//
// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1.
if (!context.Request.HasScope(Scopes.OpenId))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2215),
uri: SR.FormatID8000(SR.ID2215));
return ValueTask.CompletedTask;
}
// Reject requests that specify scope=offline_access if the refresh token flow is not enabled.
if (context.Request.HasScope(Scopes.OfflineAccess) && !context.Options.GrantTypes.Contains(GrantTypes.RefreshToken))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2035(Scopes.OfflineAccess),
uri: SR.FormatID8000(SR.ID2035));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that don't specify exactly one hint.
/// </summary>
public sealed class ValidateHintParameters : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateHintParameters>()
.SetOrder(ValidateScopeParameter.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Backchannel authentication requests MUST contain one and only one of the login_hint_token,
// id_token_hint or login_hint parameters, that are used to identify the end user.
//
// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1.
var count = (string.IsNullOrEmpty(context.Request.LoginHint) ? 0 : 1) +
(string.IsNullOrEmpty(context.Request.LoginHintToken) ? 0 : 1) +
(string.IsNullOrEmpty(context.Request.IdTokenHint) ? 0 : 1);
if (count is not 1)
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2214),
uri: SR.FormatID8000(SR.ID2214));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that specify an invalid requested_expiry.
/// </summary>
public sealed class ValidateRequestedExpiryParameter : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateRequestedExpiryParameter>()
.SetOrder(ValidateHintParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Request.HasParameter(Parameters.RequestedExpiry) && context.Request.RequestedExpiry is not > 0)
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2052(Parameters.RequestedExpiry),
uri: SR.FormatID8000(SR.ID2052));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that specify invalid client credentials parameters.
/// </summary>
public sealed class ValidateClientCredentialsParameters : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateClientCredentialsParameters>()
.SetOrder(ValidateRequestedExpiryParameter.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Ensure a client_assertion_type is specified when a client_assertion was attached.
if (!string.IsNullOrEmpty(context.Request.ClientAssertion) &&
string.IsNullOrEmpty(context.Request.ClientAssertionType))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2037(Parameters.ClientAssertionType, Parameters.ClientAssertion),
uri: SR.FormatID8000(SR.ID2037));
return ValueTask.CompletedTask;
}
// Ensure a client_assertion is specified when a client_assertion_type was attached.
if (string.IsNullOrEmpty(context.Request.ClientAssertion) &&
!string.IsNullOrEmpty(context.Request.ClientAssertionType))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2037(Parameters.ClientAssertion, Parameters.ClientAssertionType),
uri: SR.FormatID8000(SR.ID2037));
return ValueTask.CompletedTask;
}
// Reject requests that use multiple client authentication methods.
//
// See https://tools.ietf.org/html/rfc6749#section-2.3 for more information.
if (!string.IsNullOrEmpty(context.Request.ClientAssertion) &&
!string.IsNullOrEmpty(context.Request.ClientSecret))
{
context.Logger.LogInformation(6140, SR.GetResourceString(SR.ID6140));
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2087),
uri: SR.FormatID8000(SR.ID2087));
return ValueTask.CompletedTask;
}
// Ensure the specified client_assertion_type is supported.
if (!string.IsNullOrEmpty(context.Request.ClientAssertionType) &&
!context.Options.ClientAssertionTypes.Contains(context.Request.ClientAssertionType))
{
context.Reject(
error: Errors.InvalidClient,
description: SR.FormatID2032(Parameters.ClientAssertionType),
uri: SR.FormatID8000(SR.ID2032));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests that use unregistered scopes.
/// Note: this handler partially works with the degraded mode but is not used when scope validation is disabled.
/// </summary>
public sealed class ValidateScopes : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.AddFilter<RequireScopeValidationEnabled>()
.UseSingletonHandler<ValidateScopes>()
.SetOrder(ValidateClientCredentialsParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// If all the specified scopes are registered in the options, avoid making a database lookup.
var scopes = context.Request.GetScopes().ToHashSet(StringComparer.Ordinal);
scopes.ExceptWith(context.Options.Scopes);
if (scopes.Count is not 0 && !context.Options.EnableDegradedMode)
{
var manager = context.ServiceProvider.GetService<IOpenIddictScopeManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
await foreach (var scope in manager.FindByNamesAsync([.. scopes], context.CancellationToken))
{
var name = await manager.GetNameAsync(scope, context.CancellationToken);
if (!string.IsNullOrEmpty(name))
{
scopes.Remove(name);
}
}
}
// If at least one scope was not recognized, return an error.
if (scopes.Count is not 0)
{
context.Logger.LogInformation(6305, SR.GetResourceString(SR.ID6305), scopes);
context.Reject(
error: Errors.InvalidScope,
description: SR.FormatID2052(Parameters.Scope),
uri: SR.FormatID8000(SR.ID2052));
return;
}
}
}
/// <summary>
/// Contains the logic responsible for applying the authentication logic to backchannel authentication requests.
/// </summary>
public sealed class ValidateAuthentication : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ValidateAuthentication(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<ValidateAuthentication>()
.SetOrder(ValidateScopes.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new ProcessAuthenticationContext(context.Transaction);
await _dispatcher.DispatchAsync(notification);
// Store the context object in the transaction so it can be later retrieved by handlers
// that want to access the authentication result without triggering a new authentication flow.
context.Transaction.SetProperty(typeof(ProcessAuthenticationContext).FullName!, notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
// Attach the security principal extracted from the identity token hint to the validation context.
context.IdentityTokenHintPrincipal = notification.IdentityTokenPrincipal;
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests made by applications
/// that haven't been granted the backchannel authentication endpoint permission.
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public sealed class ValidateEndpointPermissions : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.AddFilter<RequireClientIdParameter>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireEndpointPermissionsEnabled>()
.UseSingletonHandler<ValidateEndpointPermissions>()
.SetOrder(ValidateAuthentication.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
if (!await manager.HasPermissionAsync(application, Permissions.Endpoints.BackchannelAuthentication, context.CancellationToken))
{
context.Logger.LogInformation(6302, SR.GetResourceString(SR.ID6302), context.ClientId);
context.Reject(
error: Errors.UnauthorizedClient,
description: SR.GetResourceString(SR.ID2217),
uri: SR.FormatID8000(SR.ID2217));
return;
}
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests made by unauthorized applications.
/// Note: this handler is not used when the degraded mode is enabled or when grant type permissions are disabled.
/// </summary>
public sealed class ValidateGrantTypePermissions : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.AddFilter<RequireClientIdParameter>()
.AddFilter<RequireGrantTypePermissionsEnabled>()
.AddFilter<RequireDegradedModeDisabled>()
.UseSingletonHandler<ValidateGrantTypePermissions>()
.SetOrder(ValidateEndpointPermissions.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// Reject the request if the application is not allowed to use the CIBA grant.
if (!await manager.HasPermissionAsync(application, Permissions.GrantTypes.Ciba, context.CancellationToken))
{
context.Logger.LogInformation(6303, SR.GetResourceString(SR.ID6303), context.ClientId);
context.Reject(
error: Errors.UnauthorizedClient,
description: SR.GetResourceString(SR.ID2218),
uri: SR.FormatID8000(SR.ID2218));
return;
}
// Reject the request if the offline_access scope was request and
// if the application is not allowed to use the refresh token grant.
if (context.Request.HasScope(Scopes.OfflineAccess) &&
!await manager.HasPermissionAsync(application, Permissions.GrantTypes.RefreshToken, context.CancellationToken))
{
context.Logger.LogInformation(6304, SR.GetResourceString(SR.ID6304), context.ClientId, Scopes.OfflineAccess);
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2065(Scopes.OfflineAccess),
uri: SR.FormatID8000(SR.ID2065));
return;
}
}
}
/// <summary>
/// Contains the logic responsible for rejecting backchannel authentication requests made by applications
/// that haven't been granted the appropriate scope permissions.
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public sealed class ValidateScopePermissions : IOpenIddictServerHandler<ValidateBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateBackchannelAuthenticationRequestContext>()
.AddFilter<RequireClientIdParameter>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireScopePermissionsEnabled>()
.UseSingletonHandler<ValidateScopePermissions>()
.SetOrder(ValidateGrantTypePermissions.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
foreach (var scope in context.Request.GetScopes())
{
// Avoid validating the "openid" and "offline_access" scopes as they represent protocol scopes.
if (string.Equals(scope, Scopes.OfflineAccess, StringComparison.Ordinal) ||
string.Equals(scope, Scopes.OpenId, StringComparison.Ordinal))
{
continue;
}
// Reject the request if the application is not allowed to use the iterated scope.
if (!await manager.HasPermissionAsync(application, Permissions.Prefixes.Scope + scope, context.CancellationToken))
{
context.Logger.LogInformation(6304, SR.GetResourceString(SR.ID6304), context.ClientId, scope);
context.Reject(
error: Errors.InvalidRequest,
description: SR.GetResourceString(SR.ID2051),
uri: SR.FormatID8000(SR.ID2051));
return;
}
}
}
}
/// <summary>
/// Contains the logic responsible for attaching the principal
/// extracted from the identity token hint to the event context.
/// </summary>
public sealed class AttachPrincipal : IOpenIddictServerHandler<HandleBackchannelAuthenticationRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<HandleBackchannelAuthenticationRequestContext>()
.UseSingletonHandler<AttachPrincipal>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(HandleBackchannelAuthenticationRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateBackchannelAuthenticationRequestContext>(
typeof(ValidateBackchannelAuthenticationRequestContext).FullName!)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal;
return ValueTask.CompletedTask;
}
}
}
}

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

@ -238,6 +238,9 @@ public static partial class OpenIddictServerHandlers
[Metadata.UserInfoEndpoint] = notification.UserInfoEndpoint?.AbsoluteUri,
[Metadata.DeviceAuthorizationEndpoint] = notification.DeviceAuthorizationEndpoint?.AbsoluteUri,
[Metadata.PushedAuthorizationRequestEndpoint] = notification.PushedAuthorizationEndpoint?.AbsoluteUri,
[Metadata.BackchannelAuthenticationEndpoint] = notification.BackchannelAuthenticationEndpoint?.AbsoluteUri,
[Metadata.BackchannelTokenDeliveryModesSupported] = notification.BackchannelTokenDeliveryModes.ToImmutableArray<string?>(),
[Metadata.BackchannelUserCodeParameterSupported] = notification.BackchannelAuthenticationEndpoint is not null ? false : null,
[Metadata.MtlsEndpointAliases] = CreateMtlsEndpointAliases(notification),
[Metadata.JwksUri] = notification.JsonWebKeySetEndpoint?.AbsoluteUri,
[Metadata.GrantTypesSupported] = notification.GrantTypes.ToImmutableArray<string?>(),
@ -407,6 +410,15 @@ public static partial class OpenIddictServerHandlers
context.AuthorizationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.AuthorizationEndpointUris.FirstOrDefault());
context.BackchannelAuthenticationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.BackchannelAuthenticationEndpointUris.FirstOrDefault());
// Note: OpenIddict only supports the poll delivery mode.
if (context.BackchannelAuthenticationEndpoint is not null)
{
context.BackchannelTokenDeliveryModes.Add(BackchannelTokenDeliveryModes.Poll);
}
context.DeviceAuthorizationEndpoint ??= OpenIddictHelpers.CreateAbsoluteUri(
context.BaseUri, context.Options.DeviceAuthorizationEndpointUris.FirstOrDefault());

27
src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs

@ -413,6 +413,7 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context);
if (!context.Request.IsAuthorizationCodeGrantType() &&
!context.Request.IsCibaGrantType() &&
!context.Request.IsClientCredentialsGrantType() &&
!context.Request.IsDeviceCodeGrantType())
{
@ -608,6 +609,18 @@ public static partial class OpenIddictServerHandlers
return ValueTask.CompletedTask;
}
// Reject grant_type=urn:openid:params:grant-type:ciba requests missing the authentication request identifier.
// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.1.
if (context.Request.IsCibaGrantType() && string.IsNullOrEmpty(context.Request.AuthReqId))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2216(Parameters.AuthReqId),
uri: SR.FormatID8000(SR.ID2216));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
@ -885,6 +898,7 @@ public static partial class OpenIddictServerHandlers
//
// For more information, see https://tools.ietf.org/html/rfc6749#section-6.
if (!string.IsNullOrEmpty(context.Request.Scope) && (context.Request.IsAuthorizationCodeGrantType() ||
context.Request.IsCibaGrantType() ||
context.Request.IsDeviceCodeGrantType()))
{
context.Logger.LogInformation(6094, SR.GetResourceString(SR.ID6094), Parameters.Scope);
@ -929,6 +943,7 @@ public static partial class OpenIddictServerHandlers
// Prevent audiences parameters from being attached to token requests that don't use the
// OAuth 2.0 Token Exchange grant type, unless the specified grant type is a custom value.
if (context.Request.IsAuthorizationCodeGrantType() || context.Request.IsClientCredentialsGrantType() ||
context.Request.IsCibaGrantType() ||
context.Request.IsDeviceCodeGrantType() || context.Request.IsImplicitFlow() ||
context.Request.IsPasswordGrantType() || context.Request.IsRefreshTokenGrantType())
{
@ -1214,6 +1229,7 @@ public static partial class OpenIddictServerHandlers
context.ActorTokenPrincipal = notification.ActorTokenPrincipal;
context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal;
context.DeviceCodePrincipal = notification.DeviceCodePrincipal;
context.AuthenticationRequestIdPrincipal = notification.AuthenticationRequestIdPrincipal;
context.RefreshTokenPrincipal = notification.RefreshTokenPrincipal;
context.SubjectTokenPrincipal = notification.SubjectTokenPrincipal;
}
@ -1570,12 +1586,14 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context);
if (context.Request.IsAuthorizationCodeGrantType() ||
context.Request.IsCibaGrantType() ||
context.Request.IsDeviceCodeGrantType() ||
context.Request.IsRefreshTokenGrantType())
{
var principal = context.Request.GrantType switch
{
GrantTypes.AuthorizationCode => context.AuthorizationCodePrincipal,
GrantTypes.Ciba => context.AuthenticationRequestIdPrincipal,
GrantTypes.DeviceCode => context.DeviceCodePrincipal,
GrantTypes.RefreshToken => context.RefreshTokenPrincipal,
@ -1593,7 +1611,7 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0043));
}
if (context.Request.IsDeviceCodeGrantType())
if (context.Request.IsCibaGrantType() || context.Request.IsDeviceCodeGrantType())
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0044));
}
@ -2082,6 +2100,7 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context);
if (!context.Request.IsAuthorizationCodeGrantType() &&
!context.Request.IsCibaGrantType() &&
!context.Request.IsDeviceCodeGrantType() &&
!context.Request.IsRefreshTokenGrantType() &&
!context.Request.IsTokenExchangeGrantType())
@ -2094,6 +2113,7 @@ public static partial class OpenIddictServerHandlers
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.ActorTokenPrincipal = notification.ActorTokenPrincipal;
context.AuthenticationRequestIdPrincipal = notification.AuthenticationRequestIdPrincipal;
context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal;
context.DeviceCodePrincipal = notification.DeviceCodePrincipal;
context.RefreshTokenPrincipal = notification.RefreshTokenPrincipal;
@ -2104,6 +2124,7 @@ public static partial class OpenIddictServerHandlers
context.Principal ??= context.Request.GrantType switch
{
GrantTypes.AuthorizationCode => notification.AuthorizationCodePrincipal,
GrantTypes.Ciba => notification.AuthenticationRequestIdPrincipal,
GrantTypes.DeviceCode => notification.DeviceCodePrincipal,
GrantTypes.RefreshToken => notification.RefreshTokenPrincipal,
@ -2150,6 +2171,7 @@ public static partial class OpenIddictServerHandlers
// If the error indicates an invalid token, return a standard invalid_grant.
if (context.Request is null || !(context.Request.IsAuthorizationCodeGrantType() ||
context.Request.IsCibaGrantType() ||
context.Request.IsDeviceCodeGrantType() ||
context.Request.IsRefreshTokenGrantType() ||
context.Request.IsTokenExchangeGrantType()))
@ -2162,6 +2184,9 @@ public static partial class OpenIddictServerHandlers
// Keep "expired_token" errors as-is if the request is a device code token request.
Errors.ExpiredToken when context.Request.IsDeviceCodeGrantType() => Errors.ExpiredToken,
// Similarly, keep "expired_token" errors as-is if the request is a CIBA token request.
Errors.ExpiredToken when context.Request.IsCibaGrantType() => Errors.ExpiredToken,
// Convert "invalid_token" errors to "invalid_grant".
Errors.InvalidToken => Errors.InvalidGrant,

64
src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs

@ -13,6 +13,7 @@ using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@ -257,6 +258,9 @@ public static partial class OpenIddictServerHandlers
// For device codes, only the short "oi_dvc+jwt" form is valid.
TokenTypeIdentifiers.Private.DeviceCode => [JsonWebTokenTypes.Private.DeviceCode],
// For authentication request identifiers, only the short "oi_arid+jwt" form is valid.
TokenTypeIdentifiers.Private.AuthenticationRequestId => [JsonWebTokenTypes.Private.AuthenticationRequestId],
// For refresh tokens, only the short "oi_reft+jwt" form is valid.
TokenTypeIdentifiers.RefreshToken => [JsonWebTokenTypes.Private.RefreshToken],
@ -585,6 +589,7 @@ public static partial class OpenIddictServerHandlers
JsonWebTokenTypes.Private.AuthorizationCode => TokenTypeIdentifiers.Private.AuthorizationCode,
JsonWebTokenTypes.Private.DeviceCode => TokenTypeIdentifiers.Private.DeviceCode,
JsonWebTokenTypes.Private.AuthenticationRequestId => TokenTypeIdentifiers.Private.AuthenticationRequestId,
JsonWebTokenTypes.Private.RefreshToken => TokenTypeIdentifiers.RefreshToken,
JsonWebTokenTypes.Private.RequestToken => TokenTypeIdentifiers.Private.RequestToken,
JsonWebTokenTypes.Private.UserCode => TokenTypeIdentifiers.Private.UserCode,
@ -984,6 +989,7 @@ public static partial class OpenIddictServerHandlers
{
TokenTypeIdentifiers.Private.ClientAssertion => Errors.InvalidClient,
TokenTypeIdentifiers.Private.DeviceCode => Errors.ExpiredToken,
TokenTypeIdentifiers.Private.AuthenticationRequestId => Errors.ExpiredToken,
_ => Errors.InvalidToken
},
description: context.Principal.GetTokenType() switch
@ -1298,6 +1304,24 @@ public static partial class OpenIddictServerHandlers
// If the token is not marked as valid yet, return an authorization_pending error.
if (await manager.HasStatusAsync(token, Statuses.Inactive, context.CancellationToken))
{
// If a polling interval was configured, return a slow_down error if the client
// application polls the token endpoint more frequently than what is allowed.
if (context.EndpointType is OpenIddictServerEndpointType.Token &&
context.Options.PollingInterval is TimeSpan interval &&
context.Principal.GetTokenType() is TokenTypeIdentifiers.Private.AuthenticationRequestId or
TokenTypeIdentifiers.Private.DeviceCode &&
!await TryUpdatePollingDateAsync(token, interval))
{
context.Logger.LogInformation(6299, SR.GetResourceString(SR.ID6299), context.TokenId);
context.Reject(
error: Errors.SlowDown,
description: SR.GetResourceString(SR.ID2213),
uri: SR.FormatID8000(SR.ID2213));
return;
}
context.Logger.LogInformation(6003, SR.GetResourceString(SR.ID6003), context.TokenId);
context.Reject(
@ -1352,6 +1376,40 @@ public static partial class OpenIddictServerHandlers
return;
}
async ValueTask<bool> TryUpdatePollingDateAsync(object token, TimeSpan interval)
{
var now = context.Options.TimeProvider.GetUtcNow();
var properties = await manager.GetPropertiesAsync(token, context.CancellationToken);
if (properties.TryGetValue(Properties.LastPollingDate, out JsonElement element) &&
element.ValueKind is JsonValueKind.Number && element.TryGetInt64(out long value) &&
now < DateTimeOffset.FromUnixTimeSeconds(value) + interval)
{
return false;
}
var descriptor = new OpenIddictTokenDescriptor();
await manager.PopulateAsync(descriptor, token, context.CancellationToken);
using var document = JsonDocument.Parse(now.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture));
descriptor.Properties[Properties.LastPollingDate] = document.RootElement.Clone();
try
{
await manager.UpdateAsync(token, descriptor, context.CancellationToken);
}
// If the entry was concurrently updated (e.g because the client application sent concurrent polling
// requests or because the end user approved the demand at the same time), consider the request as
// too frequent: a subsequent polling request will be able to retrieve the updated token entry.
catch (OpenIddictExceptions.ConcurrencyException)
{
return false;
}
return true;
}
async ValueTask<bool> IsReusableAsync(object token)
{
// If the reuse leeway was set to null, return false to indicate
@ -1568,6 +1626,10 @@ public static partial class OpenIddictServerHandlers
// corresponding the user, which allows the client to redeem the device code.
TokenTypeIdentifiers.Private.DeviceCode => Statuses.Inactive,
// Similarly, authentication request identifiers are marked as inactive until the end user
// approves the backchannel authentication request using the OpenIddict server service.
TokenTypeIdentifiers.Private.AuthenticationRequestId => Statuses.Inactive,
// For all other tokens, "valid" is the default status.
_ => Statuses.Valid
};
@ -1737,6 +1799,7 @@ public static partial class OpenIddictServerHandlers
// For authorization/device/user codes and refresh tokens,
// attach claims destinations to the JWT claims collection.
if (context.TokenType is TokenTypeIdentifiers.Private.AuthorizationCode or TokenTypeIdentifiers.Private.DeviceCode or
TokenTypeIdentifiers.Private.AuthenticationRequestId or
TokenTypeIdentifiers.RefreshToken or TokenTypeIdentifiers.Private.UserCode or
TokenTypeIdentifiers.Private.RequestToken)
{
@ -1758,6 +1821,7 @@ public static partial class OpenIddictServerHandlers
TokenTypeIdentifiers.AccessToken => JsonWebTokenTypes.AccessToken,
TokenTypeIdentifiers.Private.AuthorizationCode => JsonWebTokenTypes.Private.AuthorizationCode,
TokenTypeIdentifiers.Private.DeviceCode => JsonWebTokenTypes.Private.DeviceCode,
TokenTypeIdentifiers.Private.AuthenticationRequestId => JsonWebTokenTypes.Private.AuthenticationRequestId,
TokenTypeIdentifiers.IdentityToken => JsonWebTokenTypes.GenericJsonWebToken,
TokenTypeIdentifiers.RefreshToken => JsonWebTokenTypes.Private.RefreshToken,
TokenTypeIdentifiers.Private.RequestToken => JsonWebTokenTypes.Private.RequestToken,

354
src/OpenIddict.Server/OpenIddictServerHandlers.cs

@ -56,6 +56,7 @@ public static partial class OpenIddictServerHandlers
ValidateAccessToken.Descriptor,
ValidateAuthorizationCode.Descriptor,
ValidateDeviceCode.Descriptor,
ValidateAuthenticationRequestId.Descriptor,
ValidateGenericToken.Descriptor,
ValidateIdentityToken.Descriptor,
ValidateRefreshToken.Descriptor,
@ -91,6 +92,7 @@ public static partial class OpenIddictServerHandlers
PrepareAccessTokenPrincipal.Descriptor,
PrepareAuthorizationCodePrincipal.Descriptor,
PrepareDeviceCodePrincipal.Descriptor,
PrepareAuthenticationRequestIdPrincipal.Descriptor,
PrepareIssuedTokenPrincipal.Descriptor,
PrepareRequestTokenPrincipal.Descriptor,
PrepareRefreshTokenPrincipal.Descriptor,
@ -100,6 +102,7 @@ public static partial class OpenIddictServerHandlers
GenerateAccessToken.Descriptor,
GenerateAuthorizationCode.Descriptor,
GenerateDeviceCode.Descriptor,
GenerateAuthenticationRequestId.Descriptor,
GenerateIssuedToken.Descriptor,
GenerateRequestToken.Descriptor,
GenerateRefreshToken.Descriptor,
@ -130,6 +133,7 @@ public static partial class OpenIddictServerHandlers
AttachCustomErrorParameters.Descriptor,
.. Authentication.DefaultHandlers,
.. Backchannel.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
@ -168,6 +172,7 @@ public static partial class OpenIddictServerHandlers
context.EndpointType =
Matches(context.Options.AuthorizationEndpointUris) ? OpenIddictServerEndpointType.Authorization :
Matches(context.Options.BackchannelAuthenticationEndpointUris) ? OpenIddictServerEndpointType.BackchannelAuthentication :
Matches(context.Options.ConfigurationEndpointUris) ? OpenIddictServerEndpointType.Configuration :
Matches(context.Options.DeviceAuthorizationEndpointUris) ? OpenIddictServerEndpointType.DeviceAuthorization :
Matches(context.Options.EndSessionEndpointUris) ? OpenIddictServerEndpointType.EndSession :
@ -258,7 +263,7 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Revocation or OpenIddictServerEndpointType.Token or
OpenIddictServerEndpointType.UserInfo
OpenIddictServerEndpointType.UserInfo or OpenIddictServerEndpointType.BackchannelAuthentication
=> default,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0002)),
@ -309,6 +314,18 @@ public static partial class OpenIddictServerHandlers
_ => (false, false, false, false)
};
(context.ExtractAuthenticationRequestId,
context.RequireAuthenticationRequestId,
context.ValidateAuthenticationRequestId,
context.RejectAuthenticationRequestId) = context.EndpointType switch
{
// The CIBA grant requires sending a valid authentication request identifier.
OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType()
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractAuthorizationCode,
context.RequireAuthorizationCode,
context.ValidateAuthorizationCode,
@ -331,7 +348,7 @@ public static partial class OpenIddictServerHandlers
// present and invalid client assertions are always automatically rejected by OpenIddict.
OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or
OpenIddictServerEndpointType.Token
OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication
=> (true, false, true, true),
_ => (false, false, false, false)
@ -377,6 +394,10 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.PushedAuthorization
=> (true, false, true, false),
// Identity token hints received by the backchannel authentication endpoint are used to
// identify the end user and invalid hints always cause the request to be rejected.
OpenIddictServerEndpointType.BackchannelAuthentication => (true, false, true, true),
_ => (false, false, false, false)
};
@ -468,6 +489,14 @@ public static partial class OpenIddictServerHandlers
_ => (null, null)
};
context.AuthenticationRequestId = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractAuthenticationRequestId
=> context.Request.AuthReqId,
_ => null
};
context.AuthorizationCode = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractAuthorizationCode
@ -480,7 +509,7 @@ public static partial class OpenIddictServerHandlers
{
OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or
OpenIddictServerEndpointType.Token
OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication
when context.ExtractClientAssertion
=> (context.Request.ClientAssertion, context.Request.ClientAssertionType),
@ -506,8 +535,9 @@ public static partial class OpenIddictServerHandlers
context.IdentityToken = context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.PushedAuthorization when context.ExtractIdentityToken
=> context.Request.IdTokenHint,
@ -583,6 +613,7 @@ public static partial class OpenIddictServerHandlers
if ((context.RequireAccessToken && string.IsNullOrEmpty(context.AccessToken)) ||
(context.RequireActorToken && string.IsNullOrEmpty(context.ActorToken)) ||
(context.RequireAuthenticationRequestId && string.IsNullOrEmpty(context.AuthenticationRequestId)) ||
(context.RequireAuthorizationCode && string.IsNullOrEmpty(context.AuthorizationCode)) ||
(context.RequireClientAssertion && string.IsNullOrEmpty(context.ClientAssertion)) ||
(context.RequireDeviceCode && string.IsNullOrEmpty(context.DeviceCode)) ||
@ -961,6 +992,7 @@ public static partial class OpenIddictServerHandlers
// never allow anonymous clients, even if the corresponding option is enabled.
case OpenIddictServerEndpointType.Token when context.Options.AcceptAnonymousClients &&
!context.Request.IsAuthorizationCodeGrantType() &&
!context.Request.IsCibaGrantType() &&
!context.Request.IsClientCredentialsGrantType() &&
!context.Request.IsDeviceCodeGrantType():
return;
@ -1009,7 +1041,7 @@ public static partial class OpenIddictServerHandlers
// For non-interactive endpoints, return "invalid_client" instead of "invalid_request".
OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or
OpenIddictServerEndpointType.Token
OpenIddictServerEndpointType.Token or OpenIddictServerEndpointType.BackchannelAuthentication
=> Errors.InvalidClient,
_ => Errors.InvalidRequest
@ -1773,6 +1805,81 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for validating the authentication request identifier resolved from the context.
/// </summary>
public sealed class ValidateAuthenticationRequestId : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ValidateAuthenticationRequestId(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireAuthenticationRequestIdValidated>()
.UseSingletonHandler<ValidateAuthenticationRequestId>()
.SetOrder(ValidateDeviceCode.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (string.IsNullOrEmpty(context.AuthenticationRequestId))
{
return;
}
var notification = new ValidateTokenContext(context.Transaction)
{
DisableAudienceValidation = true,
Token = context.AuthenticationRequestId,
ValidTokenTypes = { TokenTypeIdentifiers.Private.AuthenticationRequestId }
};
if (!string.IsNullOrEmpty(context.ClientId))
{
notification.ValidPresenters.Add(context.ClientId);
}
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
if (context.RejectAuthenticationRequestId)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
return;
}
context.AuthenticationRequestIdPrincipal = notification.Principal;
}
}
/// <summary>
/// Contains the logic responsible for validating tokens of unknown types resolved from the context.
/// </summary>
@ -1905,10 +2012,12 @@ public static partial class OpenIddictServerHandlers
// Audience and presenter validation is disabled for the authorization and end session endpoints
// as these endpoints implement specialized event handlers that use more complex rules.
DisableAudienceValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.PushedAuthorization,
// Don't validate the lifetime of identity token used as hints.
DisableLifetimeValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.PushedAuthorization,
DisablePresenterValidation = context.EndpointType is OpenIddictServerEndpointType.Authorization or
@ -2498,8 +2607,9 @@ public static partial class OpenIddictServerHandlers
context.Response.Error ??= context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
=> Errors.AccessDenied,
@ -2511,8 +2621,9 @@ public static partial class OpenIddictServerHandlers
context.Response.ErrorDescription ??= context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
=> SR.GetResourceString(SR.ID2015),
@ -2524,8 +2635,9 @@ public static partial class OpenIddictServerHandlers
context.Response.ErrorUri ??= context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.BackchannelAuthentication or
OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.PushedAuthorization
=> SR.FormatID8000(SR.ID2015),
@ -2734,6 +2846,7 @@ public static partial class OpenIddictServerHandlers
break;
case OpenIddictServerEndpointType.Authorization:
case OpenIddictServerEndpointType.BackchannelAuthentication:
case OpenIddictServerEndpointType.EndUserVerification:
case OpenIddictServerEndpointType.Token:
if (context.Principal is not { Identity: ClaimsIdentity })
@ -2769,7 +2882,8 @@ public static partial class OpenIddictServerHandlers
{
// The following claims MUST be represented as unique strings.
Claims.AuthenticationContextReference or Claims.Subject or
Claims.Private.AuthorizationId or Claims.Private.CreationDate or
Claims.Private.AuthorizationId or Claims.Private.BindingMessage or
Claims.Private.CreationDate or
Claims.Private.DeviceCodeId or Claims.Private.ExpirationDate or
Claims.Private.SessionId or Claims.Private.TokenId
=> values is [{ ValueType: ClaimValueTypes.String }],
@ -2798,6 +2912,7 @@ public static partial class OpenIddictServerHandlers
// The following claims MUST be represented as unique integers.
Claims.Private.AccessTokenLifetime or Claims.Private.AuthorizationCodeLifetime or
Claims.Private.AuthenticationRequestIdLifetime or
Claims.Private.DeviceCodeLifetime or Claims.Private.IdentityTokenLifetime or
Claims.Private.RefreshTokenLifetime or Claims.Private.RefreshTokenLifetime or
Claims.Private.RequestTokenLifetime
@ -2854,6 +2969,7 @@ public static partial class OpenIddictServerHandlers
case OpenIddictServerEndpointType.Authorization:
case OpenIddictServerEndpointType.EndUserVerification:
case OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType() &&
!context.Options.DisableRollingRefreshTokens:
@ -2873,6 +2989,9 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType()
=> notification.AuthorizationCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType()
=> notification.AuthenticationRequestIdPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
=> notification.DeviceCodePrincipal,
@ -2965,6 +3084,7 @@ public static partial class OpenIddictServerHandlers
{
case OpenIddictServerEndpointType.EndUserVerification:
case OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType():
case OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType():
break;
@ -2985,6 +3105,9 @@ public static partial class OpenIddictServerHandlers
OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType()
=> notification.AuthorizationCodePrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsCibaGrantType()
=> notification.AuthenticationRequestIdPrincipal,
OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
=> notification.DeviceCodePrincipal,
@ -3200,6 +3323,14 @@ public static partial class OpenIddictServerHandlers
_ => (false, false)
};
(context.GenerateAuthenticationRequestId, context.IncludeAuthenticationRequestId) = context.EndpointType switch
{
// For backchannel authentication requests, always generate and return an authentication request identifier.
OpenIddictServerEndpointType.BackchannelAuthentication => (true, true),
_ => (false, false)
};
(context.GenerateAuthorizationCode, context.IncludeAuthorizationCode) = context.EndpointType switch
{
// Never generate an authorization code if request caching was enabled and the authorization
@ -3762,6 +3893,105 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for preparing and attaching the claims principal used
/// to generate the authentication request identifier, if one is going to be returned.
/// </summary>
public sealed class PrepareAuthenticationRequestIdPrincipal : IOpenIddictServerHandler<ProcessSignInContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessSignInContext>()
.AddFilter<RequireAuthenticationRequestIdGenerated>()
.UseSingletonHandler<PrepareAuthenticationRequestIdPrincipal>()
.SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessSignInContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Create a new principal containing only the filtered claims.
// Actors identities are also filtered (delegation scenarios).
var principal = context.Principal.Clone(claim =>
{
// Never include the the following claims to ensure they are not inherited from the parent token:
if (string.Equals(claim.Type, Claims.JwtId, StringComparison.OrdinalIgnoreCase) ||
string.Equals(claim.Type, Claims.Private.TokenId, StringComparison.OrdinalIgnoreCase) ||
string.Equals(claim.Type, Claims.ExpiresAt, StringComparison.OrdinalIgnoreCase) ||
string.Equals(claim.Type, Claims.IssuedAt, StringComparison.OrdinalIgnoreCase) ||
string.Equals(claim.Type, Claims.NotBefore, StringComparison.OrdinalIgnoreCase) ||
string.Equals(claim.Type, Claims.Confirmation, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Other claims are always included in the authentication request identifier, even private claims.
return true;
});
principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow());
// If a specific token lifetime was attached to the principal, prefer it over any other value.
var lifetime = context.Principal.GetAuthenticationRequestIdLifetime();
// If the client to which the token is returned is known, use the attached setting if available.
if (lifetime is null && !context.Options.EnableDegradedMode && !string.IsNullOrEmpty(context.ClientId))
{
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await manager.GetSettingsAsync(application, context.CancellationToken);
if (settings.TryGetValue(Settings.TokenLifetimes.AuthenticationRequestId, out string? setting) &&
TimeSpan.TryParse(setting, CultureInfo.InvariantCulture, out var value))
{
lifetime = value;
}
}
// Otherwise, fall back to the global value.
lifetime ??= context.Options.AuthenticationRequestIdLifetime;
// If the client application requested a shorter expiration, honor it.
if (context.Request.RequestedExpiry is > 0 and long expiry &&
(lifetime is null || TimeSpan.FromSeconds(expiry) < lifetime))
{
lifetime = TimeSpan.FromSeconds(expiry);
}
if (lifetime is not null)
{
principal.SetExpirationDate(principal.GetCreationDate() + lifetime.Value);
}
// Use the server identity as the token issuer.
principal.SetClaim(Claims.Private.Issuer, (context.Options.Issuer ?? context.BaseUri) switch
{
{ IsAbsoluteUri: true } uri => uri.AbsoluteUri,
// Throw an exception if the issuer cannot be retrieved or is not valid.
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0496))
});
// Store the binding message so that it can be displayed to the end user when approving the request.
if (!string.IsNullOrEmpty(context.Request.BindingMessage))
{
principal.SetClaim(Claims.Private.BindingMessage, context.Request.BindingMessage);
}
context.AuthenticationRequestIdPrincipal = principal;
}
}
/// <summary>
/// Contains the logic responsible for preparing and attaching the claims principal
/// used to generate the issued token, if one is going to be returned.
@ -4733,6 +4963,72 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for generating an authentication request identifier for the current sign-in operation.
/// </summary>
public sealed class GenerateAuthenticationRequestId : IOpenIddictServerHandler<ProcessSignInContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public GenerateAuthenticationRequestId(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessSignInContext>()
.AddFilter<RequireAuthenticationRequestIdGenerated>()
.UseSingletonHandler<GenerateAuthenticationRequestId>()
.SetOrder(GenerateDeviceCode.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessSignInContext context)
{
ArgumentNullException.ThrowIfNull(context);
var notification = new GenerateTokenContext(context.Transaction)
{
ClientId = context.ClientId,
CreateTokenEntry = !context.Options.DisableTokenStorage,
// Note: authentication request identifiers are always reference tokens so that
// their payload can be replaced when the end user approves the authentication request.
IsReferenceToken = !context.Options.DisableTokenStorage,
PersistTokenPayload = !context.Options.DisableTokenStorage,
Principal = context.AuthenticationRequestIdPrincipal!,
TokenFormat = TokenFormats.Private.JsonWebToken,
TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId
};
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
if (notification.IsRejected)
{
context.Reject(
error: notification.Error ?? Errors.InvalidRequest,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
context.AuthenticationRequestId = notification.Token;
}
}
/// <summary>
/// Contains the logic responsible for generating an issued token for the current sign-in operation.
/// </summary>
@ -5388,6 +5684,11 @@ public static partial class OpenIddictServerHandlers
}
}
if (context.IncludeAuthenticationRequestId)
{
context.Response.AuthReqId = context.AuthenticationRequestId;
}
if (context.IncludeAuthorizationCode)
{
context.Response.Code = context.AuthorizationCode;
@ -5482,6 +5783,33 @@ public static partial class OpenIddictServerHandlers
// parameter is required in device authorization responses.
_ => 5 * 60 // 5 minutes, in seconds.
};
// If a polling interval was configured, return it to the client application.
if (context.Options.PollingInterval is TimeSpan interval)
{
context.Response.Interval = (long) Math.Ceiling(interval.TotalSeconds);
}
}
else if (context.EndpointType is OpenIddictServerEndpointType.BackchannelAuthentication)
{
context.Response.ExpiresIn = context.AuthenticationRequestIdPrincipal?.GetExpirationDate() switch
{
// If an expiration date was set on the authentication request
// identifier principal, return it to the client application.
DateTimeOffset date when date > context.Options.TimeProvider.GetUtcNow()
=> (long) ((date - context.Options.TimeProvider.GetUtcNow()).TotalSeconds + .5),
// Otherwise, return an arbitrary value, as the "expires_in"
// parameter is required in backchannel authentication responses.
_ => 5 * 60 // 5 minutes, in seconds.
};
// If a polling interval was configured, return it to the client application.
if (context.Options.PollingInterval is TimeSpan interval)
{
context.Response.Interval = (long) Math.Ceiling(interval.TotalSeconds);
}
}
else if (context.EndpointType is OpenIddictServerEndpointType.PushedAuthorization)

20
src/OpenIddict.Server/OpenIddictServerOptions.cs

@ -63,6 +63,11 @@ public sealed class OpenIddictServerOptions
/// </summary>
public List<Uri> AuthorizationEndpointUris { get; } = [];
/// <summary>
/// Gets the absolute and relative URIs associated to the backchannel authentication endpoint.
/// </summary>
public List<Uri> BackchannelAuthenticationEndpointUris { get; } = [];
/// <summary>
/// Gets the absolute and relative URIs associated to the configuration endpoint.
/// </summary>
@ -251,6 +256,21 @@ public sealed class OpenIddictServerOptions
/// </summary>
public TimeSpan? AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1);
/// <summary>
/// Gets or sets the period of time authentication request identifiers (auth_req_id) returned by the backchannel
/// authentication endpoint remain valid after being issued. The default value is 5 minutes. While not recommended,
/// this property can be set to <see langword="null"/> to issue authentication request identifiers that never expire.
/// </summary>
public TimeSpan? AuthenticationRequestIdLifetime { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>
/// Gets or sets the minimum period of time client applications must wait between two polling token requests made
/// using the device code or the Client-Initiated Backchannel Authentication grants. The default value is 5 seconds.
/// Token requests sent before this period has elapsed are rejected with a "slow_down" error. If this property is
/// set to <see langword="null"/>, the polling interval is neither returned to the client nor enforced.
/// </summary>
public TimeSpan? PollingInterval { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// Gets or sets the period of time device codes remain valid after being issued. The default value is 10 minutes.
/// The client application is expected to start a whole new authentication flow after the device code has expired.

329
src/OpenIddict.Server/OpenIddictServerService.cs

@ -0,0 +1,329 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using static OpenIddict.Abstractions.OpenIddictExceptions;
namespace OpenIddict.Server;
/// <summary>
/// Provides high-level APIs for performing server-side operations that are not tied to an HTTP request,
/// like completing Client-Initiated Backchannel Authentication (CIBA) requests once approved by the end user.
/// </summary>
public class OpenIddictServerService
{
private readonly IServiceProvider _provider;
/// <summary>
/// Creates a new instance of the <see cref="OpenIddictServerService"/> class.
/// </summary>
/// <param name="provider">The service provider.</param>
public OpenIddictServerService(IServiceProvider provider)
=> _provider = provider ?? throw new ArgumentNullException(nameof(provider));
/// <summary>
/// Lists the pending backchannel authentication requests associated with the specified subject.
/// </summary>
/// <param name="subject">The subject (typically, the user identifier).</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The pending backchannel authentication requests.</returns>
public virtual IAsyncEnumerable<OpenIddictServerBackchannelAuthenticationRequest> ListPendingBackchannelAuthenticationRequestsAsync(
string subject, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(subject);
var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
var manager = _provider.GetService<IOpenIddictTokenManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
return ExecuteAsync(cancellationToken);
async IAsyncEnumerable<OpenIddictServerBackchannelAuthenticationRequest> ExecuteAsync(
[EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var token in manager.FindBySubjectAsync(subject, cancellationToken))
{
var request = await GetPendingRequestAsync(options, manager, token, cancellationToken);
if (request is not null)
{
yield return request;
}
}
}
}
/// <summary>
/// Retrieves the pending backchannel authentication request corresponding to the specified identifier.
/// </summary>
/// <param name="identifier">The identifier of the backchannel authentication request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The pending request or <see langword="null"/> if no pending request corresponds to the identifier.</returns>
public virtual async ValueTask<OpenIddictServerBackchannelAuthenticationRequest?> GetPendingBackchannelAuthenticationRequestAsync(
string identifier, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(identifier);
var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
var manager = _provider.GetService<IOpenIddictTokenManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
return await manager.FindByIdAsync(identifier, cancellationToken) switch
{
object token => await GetPendingRequestAsync(options, manager, token, cancellationToken),
null => null
};
}
/// <summary>
/// Approves the specified backchannel authentication request, which allows the client application
/// to redeem the authentication request identifier using the CIBA grant.
/// </summary>
/// <param name="identifier">The identifier of the backchannel authentication request.</param>
/// <param name="principal">
/// The principal used to create the tokens returned to the client application. If this parameter
/// is <see langword="null"/>, the principal attached to the backchannel authentication request is used.
/// The principal must contain the same subject as the one attached to the backchannel authentication request.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// <see langword="true"/> if the request was approved, <see langword="false"/> if it was not found,
/// is no longer pending or was concurrently updated (in which case, the operation can be retried).
/// </returns>
public virtual async ValueTask<bool> ApproveBackchannelAuthenticationRequestAsync(
string identifier, ClaimsPrincipal? principal = null, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(identifier);
var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
var manager = _provider.GetService<IOpenIddictTokenManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var token = await manager.FindByIdAsync(identifier, cancellationToken);
if (token is null || await GetPendingRequestAsync(options, manager, token, cancellationToken) is not { } request)
{
return false;
}
principal ??= request.Principal;
if (principal is not { Identity.IsAuthenticated: true } ||
!string.Equals(principal.GetClaim(Claims.Subject), request.Subject, StringComparison.Ordinal))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0534));
}
// Create a new principal containing only the filtered claims.
var result = principal.Clone(static claim =>
!string.Equals(claim.Type, Claims.JwtId, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(claim.Type, Claims.Private.TokenId, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(claim.Type, Claims.ExpiresAt, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(claim.Type, Claims.IssuedAt, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(claim.Type, Claims.NotBefore, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(claim.Type, Claims.Confirmation, StringComparison.OrdinalIgnoreCase));
// Restore the internal claims (e.g presenters or scopes) attached to the initial request, unless overridden.
foreach (var claims in request.Principal.Claims
.Where(static claim => claim.Type.StartsWith(Claims.Prefixes.Private, StringComparison.Ordinal))
.GroupBy(static claim => claim.Type, StringComparer.Ordinal))
{
if (!result.HasClaim(claims.Key) && result.Identity is ClaimsIdentity identity)
{
identity.AddClaims(claims);
}
}
result.SetCreationDate(request.CreationDate ?? options.TimeProvider.GetUtcNow())
.SetExpirationDate(request.ExpirationDate)
.SetTokenId(identifier)
.SetClaim(Claims.Private.Issuer, (options.Issuer ?? throw new InvalidOperationException(
SR.GetResourceString(SR.ID0529))).AbsoluteUri);
var transaction = new OpenIddictServerTransaction
{
CancellationToken = cancellationToken,
Options = options,
ServiceProvider = _provider
};
var context = new OpenIddictServerEvents.GenerateTokenContext(transaction)
{
ClientId = request.ClientId,
CreateTokenEntry = false,
IsReferenceToken = false,
PersistTokenPayload = false,
Principal = result,
TokenFormat = TokenFormats.Private.JsonWebToken,
TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId
};
await _provider.GetRequiredService<IOpenIddictServerDispatcher>().DispatchAsync(context);
if (context.IsRejected || string.IsNullOrEmpty(context.Token))
{
throw new InvalidOperationException(SR.FormatID0535(context.Error, context.ErrorDescription));
}
var descriptor = new OpenIddictTokenDescriptor();
await manager.PopulateAsync(descriptor, token, cancellationToken);
descriptor.Payload = context.Token;
descriptor.Principal = result;
descriptor.Status = Statuses.Valid;
descriptor.Subject = request.Subject;
try
{
await manager.UpdateAsync(token, descriptor, cancellationToken);
}
catch (ConcurrencyException)
{
return false;
}
return true;
}
/// <summary>
/// Rejects the specified backchannel authentication request, which causes the
/// token requests sent by the client application to be rejected with an access_denied error.
/// </summary>
/// <param name="identifier">The identifier of the backchannel authentication request.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><see langword="true"/> if the request was rejected, <see langword="false"/> otherwise.</returns>
public virtual async ValueTask<bool> RejectBackchannelAuthenticationRequestAsync(
string identifier, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(identifier);
var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
var manager = _provider.GetService<IOpenIddictTokenManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var token = await manager.FindByIdAsync(identifier, cancellationToken);
if (token is null || await GetPendingRequestAsync(options, manager, token, cancellationToken) is null)
{
return false;
}
return await manager.TryRejectAsync(token, cancellationToken);
}
private static async ValueTask<OpenIddictServerBackchannelAuthenticationRequest?> GetPendingRequestAsync(
OpenIddictServerOptions options, IOpenIddictTokenManager manager, object token, CancellationToken cancellationToken)
{
if (!await manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, cancellationToken) ||
!await manager.HasStatusAsync(token, Statuses.Inactive, cancellationToken))
{
return null;
}
var date = await manager.GetExpirationDateAsync(token, cancellationToken);
if (date is not null && date < options.TimeProvider.GetUtcNow())
{
return null;
}
var payload = await manager.GetPayloadAsync(token, cancellationToken);
if (string.IsNullOrEmpty(payload))
{
return null;
}
// Note: the payload is validated using the server token validation parameters (and not using the generic
// token validation pipeline) to avoid rejecting the token because its status is still marked as inactive.
var parameters = options.TokenValidationParameters.Clone();
parameters.ValidateLifetime = false;
parameters.ValidIssuer = options.Issuer?.AbsoluteUri;
parameters.ValidateIssuer = parameters.ValidIssuer is not null;
parameters.ValidTypes = [JsonWebTokenTypes.Private.AuthenticationRequestId];
var result = await options.JsonWebTokenHandler.ValidateTokenAsync(payload, parameters);
if (!result.IsValid)
{
return null;
}
var principal = new ClaimsPrincipal(result.ClaimsIdentity);
// Restore the claim destinations from the special oi_cl_dstn claim (represented as a dictionary/JSON object).
var jwt = (JsonWebToken) result.SecurityToken;
if ((jwt.InnerToken ?? jwt).TryGetPayloadValue(Claims.Private.ClaimDestinationsMap, out Dictionary<string, string[]> destinations))
{
var builder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(StringComparer.Ordinal);
foreach (var destination in destinations)
{
builder.Add(destination.Key, [.. destination.Value]);
}
principal.SetDestinations(builder.ToImmutable());
}
return new OpenIddictServerBackchannelAuthenticationRequest
{
BindingMessage = principal.GetClaim(Claims.Private.BindingMessage),
ClientId = principal.GetPresenters().FirstOrDefault(),
CreationDate = await manager.GetCreationDateAsync(token, cancellationToken),
ExpirationDate = date,
Identifier = (await manager.GetIdAsync(token, cancellationToken))!,
Principal = principal,
Scopes = principal.GetScopes(),
Subject = principal.GetClaim(Claims.Subject)
};
}
}
/// <summary>
/// Represents a pending backchannel authentication request.
/// </summary>
public sealed class OpenIddictServerBackchannelAuthenticationRequest
{
/// <summary>
/// Gets the binding message specified by the client application, if applicable.
/// </summary>
public string? BindingMessage { get; init; }
/// <summary>
/// Gets the identifier of the client application that initiated the request.
/// </summary>
public string? ClientId { get; init; }
/// <summary>
/// Gets the creation date of the request.
/// </summary>
public DateTimeOffset? CreationDate { get; init; }
/// <summary>
/// Gets the expiration date of the request.
/// </summary>
public DateTimeOffset? ExpirationDate { get; init; }
/// <summary>
/// Gets the identifier of the request.
/// </summary>
public required string Identifier { get; init; }
/// <summary>
/// Gets the principal attached to the request.
/// </summary>
public required ClaimsPrincipal Principal { get; init; }
/// <summary>
/// Gets the scopes requested by the client application.
/// </summary>
public ImmutableArray<string> Scopes { get; init; } = [];
/// <summary>
/// Gets the subject of the end user.
/// </summary>
public string? Subject { get; init; }
}

521
test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs

@ -0,0 +1,521 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.Net.Http;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using OpenIddict.Core;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
using static OpenIddict.Server.OpenIddictServerHandlers.Protection;
namespace OpenIddict.Server.IntegrationTests;
public abstract partial class OpenIddictServerIntegrationTests
{
[Theory]
[InlineData(nameof(HttpMethod.Delete))]
[InlineData(nameof(HttpMethod.Get))]
[InlineData(nameof(HttpMethod.Head))]
[InlineData(nameof(HttpMethod.Options))]
[InlineData(nameof(HttpMethod.Put))]
[InlineData(nameof(HttpMethod.Trace))]
public async Task ExtractBackchannelAuthenticationRequest_UnexpectedMethodReturnsAnError(string method)
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.SendAsync(method, "/connect/ciba", new OpenIddictRequest());
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.GetResourceString(SR.ID2084), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2084), response.ErrorUri);
}
[Fact]
public async Task ValidateBackchannelAuthenticationRequest_MissingOpenIdScopeCausesAnError()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
LoginHint = "bob@fabrikam.com",
Scope = Scopes.Profile
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.GetResourceString(SR.ID2215), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2215), response.ErrorUri);
}
[Theory]
[InlineData(null, null, null)]
[InlineData("bob@fabrikam.com", "token", null)]
[InlineData("bob@fabrikam.com", null, "id_token")]
[InlineData(null, "token", "id_token")]
public async Task ValidateBackchannelAuthenticationRequest_InvalidHintsCauseAnError(string? hint, string? token, string? identity)
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
IdTokenHint = identity,
LoginHint = hint,
LoginHintToken = token,
Scope = Scopes.OpenId
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.GetResourceString(SR.ID2214), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2214), response.ErrorUri);
}
[Theory]
[InlineData("0")]
[InlineData("-10")]
[InlineData("value")]
public async Task ValidateBackchannelAuthenticationRequest_InvalidRequestedExpiryCausesAnError(string expiry)
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
LoginHint = "bob@fabrikam.com",
Scope = Scopes.OpenId,
[Parameters.RequestedExpiry] = expiry
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.FormatID2052(Parameters.RequestedExpiry), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2052), response.ErrorUri);
}
[Fact]
public async Task ValidateBackchannelAuthenticationRequest_RequestParameterCausesAnError()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
Request = "eyJhbGciOiJub25lIn0.e30.",
Scope = Scopes.OpenId
});
// Assert
Assert.Equal(Errors.RequestNotSupported, response.Error);
Assert.Equal(SR.FormatID2028(Parameters.Request), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2028), response.ErrorUri);
}
[Fact]
public async Task ValidateBackchannelAuthenticationRequest_MissingClientIdCausesAnError()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
LoginHint = "bob@fabrikam.com",
Scope = Scopes.OpenId
});
// Assert
Assert.Equal(Errors.InvalidClient, response.Error);
Assert.Equal(SR.FormatID2029(Parameters.ClientId), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2029), response.ErrorUri);
}
[Fact]
public async Task HandleBackchannelAuthenticationRequest_ThrowsAnExceptionWhenNoPrincipalIsAttached()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act and assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
LoginHint = "bob@fabrikam.com",
Scope = Scopes.OpenId
});
});
Assert.Equal(SR.GetResourceString(SR.ID0531), exception.Message);
}
[Fact]
public async Task HandleBackchannelAuthenticationRequest_AllowsRejectingRequest()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
ConfigureBackchannelAuthentication(options);
options.AddEventHandler<HandleBackchannelAuthenticationRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.Reject(Errors.UnknownUserId, "The user is unknown.");
return ValueTask.CompletedTask;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
ClientId = "Fabrikam",
LoginHint = "bob@fabrikam.com",
Scope = Scopes.OpenId
});
// Assert
Assert.Equal(Errors.UnknownUserId, response.Error);
Assert.Equal("The user is unknown.", response.ErrorDescription);
}
[Fact]
public async Task HandleBackchannelAuthenticationRequest_ReturnsAuthenticationRequestIdentifier()
{
// Arrange
var token = new OpenIddictToken();
OpenIddictTokenDescriptor? created = null;
await using var server = await CreateServerAsync(options =>
{
ConfigureBackchannelAuthentication(options);
options.Services.AddSingleton(CreateTokenManager(mock =>
{
mock.Setup(manager => manager.CreateAsync(It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<CancellationToken>()))
.Callback((OpenIddictTokenDescriptor descriptor, CancellationToken _) => created = descriptor)
.ReturnsAsync(token);
mock.Setup(manager => manager.GetIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("3E228451-1555-46F7-A471-951EFBA23A56");
mock.Setup(manager => manager.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
}));
options.AddEventHandler<HandleBackchannelAuthenticationRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
Assert.Equal("bob@fabrikam.com", context.Request.LoginHint);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetClaim(Claims.Subject, "Bob le Magnifique");
return ValueTask.CompletedTask;
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest
{
BindingMessage = "W4SCT",
ClientId = "Fabrikam",
LoginHint = "bob@fabrikam.com",
RequestedExpiry = 120,
Scope = Scopes.OpenId
});
// Assert
Assert.Null(response.Error);
Assert.NotNull(response.AuthReqId);
Assert.InRange(response.ExpiresIn ?? 0, 115, 120);
Assert.Equal(5, response.Interval);
Assert.NotNull(created);
Assert.Equal(Statuses.Inactive, created.Status);
Assert.Equal("Bob le Magnifique", created.Subject);
Assert.Equal(TokenTypeIdentifiers.Private.AuthenticationRequestId, created.Type);
Assert.Equal("W4SCT", created.Principal?.GetClaim(Claims.Private.BindingMessage));
}
[Fact]
public async Task ValidateTokenRequest_MissingAuthenticationRequestIdCausesAnError()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
ClientId = "Fabrikam",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.FormatID2216(Parameters.AuthReqId), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2216), response.ErrorUri);
}
[Fact]
public async Task ValidateTokenRequest_MissingClientIdCausesAnErrorForCibaRequests()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(Errors.InvalidRequest, response.Error);
Assert.Equal(SR.FormatID2029(Parameters.ClientId), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2029), response.ErrorUri);
}
[Theory]
[InlineData(null, Errors.AuthorizationPending)]
[InlineData(-60, Errors.AuthorizationPending)]
[InlineData(-2, Errors.SlowDown)]
public async Task ValidateTokenRequest_PendingAuthenticationRequestCausesAnError(int? lastPolling, string error)
{
// Arrange
var token = new OpenIddictToken();
var properties = ImmutableDictionary.CreateBuilder<string, JsonElement>(StringComparer.Ordinal);
if (lastPolling is not null)
{
properties.Add(Properties.LastPollingDate, JsonSerializer.SerializeToElement(
(TimeProvider.System.GetUtcNow() + TimeSpan.FromSeconds(lastPolling.Value)).ToUnixTimeSeconds()));
}
var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive, properties.ToImmutable());
await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager));
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29",
ClientId = "Fabrikam",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(error, response.Error);
Mock.Get(manager).Verify(manager => manager.UpdateAsync(token, It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<CancellationToken>()),
error is Errors.SlowDown ? Times.Never() : Times.Once());
}
[Fact]
public async Task ValidateTokenRequest_PollingIntervalIsNotEnforcedWhenDisabled()
{
// Arrange
var token = new OpenIddictToken();
var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive,
ImmutableDictionary.Create<string, JsonElement>(StringComparer.Ordinal));
await using var server = await CreateServerAsync(options =>
{
ConfigureAuthenticationRequestValidation(options, manager);
options.SetPollingInterval(null);
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29",
ClientId = "Fabrikam",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(Errors.AuthorizationPending, response.Error);
Mock.Get(manager).Verify(manager => manager.GetPropertiesAsync(token, It.IsAny<CancellationToken>()), Times.Never());
}
[Fact]
public async Task ValidateTokenRequest_RejectedAuthenticationRequestCausesAnAccessDeniedError()
{
// Arrange
var token = new OpenIddictToken();
var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Rejected,
ImmutableDictionary.Create<string, JsonElement>(StringComparer.Ordinal));
await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager));
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29",
ClientId = "Fabrikam",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(Errors.AccessDenied, response.Error);
}
[Fact]
public async Task ValidateTokenRequest_ExpiredAuthenticationRequestCausesAnExpiredTokenError()
{
// Arrange
var token = new OpenIddictToken();
var manager = CreateAuthenticationRequestTokenManager(token, Statuses.Inactive,
ImmutableDictionary.Create<string, JsonElement>(StringComparer.Ordinal),
expiration: TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1));
await using var server = await CreateServerAsync(options => ConfigureAuthenticationRequestValidation(options, manager));
await using var client = await server.CreateClientAsync();
// Act
var response = await client.PostAsync("/connect/token", new OpenIddictRequest
{
AuthReqId = "8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29",
ClientId = "Fabrikam",
GrantType = GrantTypes.Ciba
});
// Assert
Assert.Equal(Errors.ExpiredToken, response.Error);
}
[Fact]
public async Task HandleConfigurationRequest_BackchannelAuthenticationMetadataIsReturned()
{
// Arrange
await using var server = await CreateServerAsync(ConfigureBackchannelAuthentication);
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/.well-known/openid-configuration");
// Assert
Assert.Equal("http://localhost/connect/ciba", (string?) response[Metadata.BackchannelAuthenticationEndpoint]);
Assert.Equal([BackchannelTokenDeliveryModes.Poll], (ImmutableArray<string?>?) response[Metadata.BackchannelTokenDeliveryModesSupported]);
Assert.False((bool) response[Metadata.BackchannelUserCodeParameterSupported]);
Assert.Contains(GrantTypes.Ciba, (ImmutableArray<string?>?) response[Metadata.GrantTypesSupported] ?? [], StringComparer.Ordinal);
}
private void ConfigureBackchannelAuthentication(OpenIddictServerBuilder options)
{
options.SetBackchannelAuthenticationEndpointUris("/connect/ciba")
.AllowClientInitiatedBackchannelAuthenticationFlow()
.SetIssuer(new Uri("https://www.contoso.com/", UriKind.Absolute));
options.DisableAuthorizationStorage();
options.Services.AddSingleton(CreateApplicationManager(mock =>
{
var application = new OpenIddictApplication();
mock.Setup(manager => manager.FindByClientIdAsync("Fabrikam", It.IsAny<CancellationToken>()))
.ReturnsAsync(application);
mock.Setup(manager => manager.HasClientTypeAsync(application, ClientTypes.Public, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
mock.Setup(manager => manager.GetSettingsAsync(application, It.IsAny<CancellationToken>()))
.ReturnsAsync(ImmutableDictionary.Create<string, string>(StringComparer.Ordinal));
}));
}
private void ConfigureAuthenticationRequestValidation(OpenIddictServerBuilder options, OpenIddictTokenManager<OpenIddictToken> manager)
{
ConfigureBackchannelAuthentication(options);
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal([TokenTypeIdentifiers.Private.AuthenticationRequestId], context.ValidTokenTypes);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetClaim(Claims.Subject, "Bob le Magnifique")
.SetPresenters("Fabrikam")
.SetTokenId("60FFF7EA-F98E-437B-937E-5073CC313103")
.SetTokenType(TokenTypeIdentifiers.Private.AuthenticationRequestId);
return ValueTask.CompletedTask;
});
builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
});
options.Services.AddSingleton(manager);
}
private OpenIddictTokenManager<OpenIddictToken> CreateAuthenticationRequestTokenManager(
OpenIddictToken token, string status, ImmutableDictionary<string, JsonElement> properties, DateTimeOffset? expiration = null)
=> CreateTokenManager(mock =>
{
mock.Setup(manager => manager.FindByReferenceIdAsync("8C8F4F4B-6F0A-4E2B-B2D3-3A2DBA3C0B29", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
mock.Setup(manager => manager.GetTypeAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(TokenTypeIdentifiers.Private.AuthenticationRequestId);
mock.Setup(manager => manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
mock.Setup(manager => manager.GetIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("60FFF7EA-F98E-437B-937E-5073CC313103");
mock.Setup(manager => manager.GetPayloadAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("payload");
mock.Setup(manager => manager.FindByIdAsync("60FFF7EA-F98E-437B-937E-5073CC313103", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
mock.Setup(manager => manager.GetExpirationDateAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(expiration ?? TimeProvider.System.GetUtcNow() + TimeSpan.FromMinutes(5));
mock.Setup(manager => manager.HasStatusAsync(token, It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((object _, string value, CancellationToken _) => string.Equals(value, status, StringComparison.Ordinal));
mock.Setup(manager => manager.GetPropertiesAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(properties);
});
}

76
test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs

@ -1870,6 +1870,82 @@ public class OpenIddictServerBuilderTests
Assert.True(options.RequireSignedRequestObjects);
}
[Fact]
public void AllowClientInitiatedBackchannelAuthenticationFlow_CibaGrantIsAdded()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.AllowClientInitiatedBackchannelAuthenticationFlow();
var options = GetOptions(services);
// Assert
Assert.Contains(GrantTypes.Ciba, options.GrantTypes);
}
[Fact]
public void AllowCustomFlow_ThrowsAnExceptionForCibaGrant()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act and assert
var exception = Assert.Throws<ArgumentException>(() => builder.AllowCustomFlow(GrantTypes.Ciba));
Assert.Equal("type", exception.ParamName);
}
[Fact]
public void SetBackchannelAuthenticationEndpointUris_AddsUris()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.SetBackchannelAuthenticationEndpointUris("http://localhost/endpoint-path");
var options = GetOptions(services);
// Assert
Assert.Contains(new Uri("http://localhost/endpoint-path"), options.BackchannelAuthenticationEndpointUris);
}
[Fact]
public void SetAuthenticationRequestIdLifetime_LifetimeIsReplaced()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.SetAuthenticationRequestIdLifetime(TimeSpan.FromMinutes(42));
var options = GetOptions(services);
// Assert
Assert.Equal(TimeSpan.FromMinutes(42), options.AuthenticationRequestIdLifetime);
}
[Fact]
public void SetPollingInterval_IntervalIsReplaced()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.SetPollingInterval(null);
var options = GetOptions(services);
// Assert
Assert.Null(options.PollingInterval);
}
[Fact]
public void EnableRequestObjectSupport_RequestObjectSupportIsEnabled()
{

52
test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs

@ -249,6 +249,58 @@ public class OpenIddictServerConfigurationTests
Assert.Contains(SR.GetResourceString(SR.ID0079), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenBackchannelAuthenticationEndpointIsMissingForCibaGrant()
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.GrantTypes.Add(GrantTypes.Ciba);
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0527), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenCibaGrantIsMissingForBackchannelAuthenticationEndpoint()
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.BackchannelAuthenticationEndpointUris.Add(new Uri("connect/ciba", UriKind.Relative));
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0528), result.Failures!, StringComparer.Ordinal);
}
[Theory]
[InlineData(true, false, true)]
[InlineData(false, true, true)]
[InlineData(false, false, false)]
public void Validate_ReturnsAnErrorWhenCibaGrantIsUsedWithIncompatibleSettings(bool degraded, bool storage, bool issuer)
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.GrantTypes.Add(GrantTypes.Ciba);
options.BackchannelAuthenticationEndpointUris.Add(new Uri("connect/ciba", UriKind.Relative));
options.EnableDegradedMode = degraded;
options.DisableTokenStorage = storage;
options.Issuer = issuer ? new Uri("https://www.contoso.com/", UriKind.Absolute) : null;
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0529), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenSignedRequestObjectsAreRequiredWithoutRequestObjectSupport()
{

243
test/OpenIddict.Server.Tests/OpenIddictServerServiceTests.cs

@ -0,0 +1,243 @@
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Moq;
using Xunit;
using static OpenIddict.Abstractions.OpenIddictExceptions;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace OpenIddict.Server.Tests;
public class OpenIddictServerServiceTests
{
private const string Identifier = "3E228451-1555-46F7-A471-951EFBA23A56";
[Fact]
public async Task ListPendingBackchannelAuthenticationRequestsAsync_ReturnsPendingRequests()
{
// Arrange
var token = new object();
var (provider, _) = await CreateProviderAsync(token, Statuses.Inactive);
var service = provider.GetRequiredService<OpenIddictServerService>();
// Act
var requests = new List<OpenIddictServerBackchannelAuthenticationRequest>();
await foreach (var request in service.ListPendingBackchannelAuthenticationRequestsAsync("Bob"))
{
requests.Add(request);
}
// Assert
var result = Assert.Single(requests);
Assert.Equal(Identifier, result.Identifier);
Assert.Equal("Fabrikam", result.ClientId);
Assert.Equal("W4SCT", result.BindingMessage);
Assert.Equal("Bob", result.Subject);
Assert.Equal([Scopes.OpenId, Scopes.Profile], result.Scopes.ToArray());
}
[Theory]
[InlineData(Statuses.Valid)]
[InlineData(Statuses.Rejected)]
[InlineData(Statuses.Redeemed)]
public async Task GetPendingBackchannelAuthenticationRequestAsync_ReturnsNullForNonPendingRequests(string status)
{
// Arrange
var token = new object();
var (provider, _) = await CreateProviderAsync(token, status);
var service = provider.GetRequiredService<OpenIddictServerService>();
// Act and assert
Assert.Null(await service.GetPendingBackchannelAuthenticationRequestAsync(Identifier));
}
[Fact]
public async Task ApproveBackchannelAuthenticationRequestAsync_UpdatesTokenEntry()
{
// Arrange
var token = new object();
var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive);
var service = provider.GetRequiredService<OpenIddictServerService>();
OpenIddictTokenDescriptor? descriptor = null;
manager.Setup(manager => manager.UpdateAsync(token, It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<CancellationToken>()))
.Callback((object _, OpenIddictTokenDescriptor value, CancellationToken _) => descriptor = value)
.Returns(ValueTask.CompletedTask);
var principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetClaim(Claims.Subject, "Bob")
.SetClaim(Claims.Name, "Bob le Bricoleur");
// Act
var result = await service.ApproveBackchannelAuthenticationRequestAsync(Identifier, principal);
// Assert
Assert.True(result);
Assert.NotNull(descriptor);
Assert.Equal(Statuses.Valid, descriptor.Status);
Assert.Equal("Bob", descriptor.Subject);
Assert.NotNull(descriptor.Payload);
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
var parameters = options.TokenValidationParameters.Clone();
parameters.ValidIssuer = "https://www.contoso.com/";
var validation = await options.JsonWebTokenHandler.ValidateTokenAsync(descriptor.Payload, parameters);
Assert.True(validation.IsValid, validation.Exception?.Message);
var approved = new ClaimsPrincipal(validation.ClaimsIdentity);
Assert.Equal("Bob le Bricoleur", approved.GetClaim(Claims.Name));
Assert.Equal(Identifier, approved.GetTokenId());
Assert.Equal("W4SCT", approved.GetClaim(Claims.Private.BindingMessage));
Assert.True(approved.HasPresenter("Fabrikam"));
}
[Fact]
public async Task ApproveBackchannelAuthenticationRequestAsync_ThrowsAnExceptionForDifferentSubject()
{
// Arrange
var token = new object();
var (provider, _) = await CreateProviderAsync(token, Statuses.Inactive);
var service = provider.GetRequiredService<OpenIddictServerService>();
var principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")).SetClaim(Claims.Subject, "Alice");
// Act and assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await service.ApproveBackchannelAuthenticationRequestAsync(Identifier, principal));
Assert.Equal(SR.GetResourceString(SR.ID0534), exception.Message);
}
[Fact]
public async Task ApproveBackchannelAuthenticationRequestAsync_ReturnsFalseForConcurrentUpdates()
{
// Arrange
var token = new object();
var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive);
var service = provider.GetRequiredService<OpenIddictServerService>();
manager.Setup(manager => manager.UpdateAsync(token, It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<CancellationToken>()))
.Returns(ValueTask.FromException(new ConcurrencyException("concurrency")));
// Act and assert
Assert.False(await service.ApproveBackchannelAuthenticationRequestAsync(Identifier));
}
[Fact]
public async Task ApproveBackchannelAuthenticationRequestAsync_ReturnsFalseForNonPendingRequests()
{
// Arrange
var token = new object();
var (provider, manager) = await CreateProviderAsync(token, Statuses.Valid);
var service = provider.GetRequiredService<OpenIddictServerService>();
// Act and assert
Assert.False(await service.ApproveBackchannelAuthenticationRequestAsync(Identifier));
manager.Verify(manager => manager.UpdateAsync(token, It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<CancellationToken>()), Times.Never());
}
[Fact]
public async Task RejectBackchannelAuthenticationRequestAsync_RejectsTokenEntry()
{
// Arrange
var token = new object();
var (provider, manager) = await CreateProviderAsync(token, Statuses.Inactive);
var service = provider.GetRequiredService<OpenIddictServerService>();
manager.Setup(manager => manager.TryRejectAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
// Act and assert
Assert.True(await service.RejectBackchannelAuthenticationRequestAsync(Identifier));
manager.Verify(manager => manager.TryRejectAsync(token, It.IsAny<CancellationToken>()), Times.Once());
}
private static async Task<(ServiceProvider Provider, Mock<IOpenIddictTokenManager> Manager)> CreateProviderAsync(object token, string status)
{
var manager = new Mock<IOpenIddictTokenManager>();
var services = new ServiceCollection();
services.AddSingleton(manager.Object);
services.AddOpenIddict()
.AddServer(options =>
{
options.SetTokenEndpointUris("connect/token")
.SetBackchannelAuthenticationEndpointUris("connect/ciba")
.AllowClientInitiatedBackchannelAuthenticationFlow()
.SetIssuer(new Uri("https://www.contoso.com/", UriKind.Absolute));
options.AddEphemeralEncryptionKey()
.AddEphemeralSigningKey();
options.DisableAuthorizationStorage();
});
var provider = services.BuildServiceProvider();
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
// Generate the payload of the pending authentication request using the server token generation pipeline.
var context = new GenerateTokenContext(new OpenIddictServerTransaction
{
CancellationToken = CancellationToken.None,
Options = options,
ServiceProvider = provider
})
{
ClientId = "Fabrikam",
CreateTokenEntry = false,
IsReferenceToken = false,
PersistTokenPayload = false,
Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetClaim(Claims.Subject, "Bob")
.SetClaim(Claims.Private.BindingMessage, "W4SCT")
.SetClaim(Claims.Private.Issuer, "https://www.contoso.com/")
.SetPresenters("Fabrikam")
.SetScopes(Scopes.OpenId, Scopes.Profile)
.SetTokenId(Identifier),
TokenFormat = TokenFormats.Private.JsonWebToken,
TokenType = TokenTypeIdentifiers.Private.AuthenticationRequestId
};
await provider.GetRequiredService<IOpenIddictServerDispatcher>().DispatchAsync(context);
Assert.False(string.IsNullOrEmpty(context.Token));
Assert.True(new JsonWebTokenHandler().CanReadToken(context.Token));
manager.Setup(manager => manager.FindByIdAsync(Identifier, It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
manager.Setup(manager => manager.FindBySubjectAsync("Bob", It.IsAny<CancellationToken>()))
.Returns(ListAsync());
manager.Setup(manager => manager.GetIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(Identifier);
manager.Setup(manager => manager.HasTypeAsync(token, TokenTypeIdentifiers.Private.AuthenticationRequestId, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
manager.Setup(manager => manager.HasStatusAsync(token, It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((object _, string value, CancellationToken _) => string.Equals(value, status, StringComparison.Ordinal));
manager.Setup(manager => manager.GetExpirationDateAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(5));
manager.Setup(manager => manager.GetCreationDateAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(DateTimeOffset.UtcNow);
manager.Setup(manager => manager.GetPayloadAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(context.Token);
return (provider, manager);
async IAsyncEnumerable<object> ListAsync()
{
await Task.Yield();
yield return token;
}
}
}
Loading…
Cancel
Save