Browse Source
- 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
40 changed files with 3336 additions and 19 deletions
@ -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 |
|||
]; |
|||
} |
|||
} |
|||
@ -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 |
|||
]; |
|||
} |
|||
} |
|||
@ -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; |
|||
} |
|||
} |
|||
@ -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; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -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; } |
|||
} |
|||
@ -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); |
|||
}); |
|||
} |
|||
@ -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…
Reference in new issue