Browse Source
- Registration endpoint (SetRegistrationEndpointUris, EnableDynamicClientRegistration) implementing RFC 7591 registration and RFC 7592 read/update/delete via ?client_id=, with ASP.NET Core/OWIN JSON extraction, 201/204 status codes, bearer errors and pass-through mode. - Initial access tokens (dedicated scopes or anonymous registration), registration access tokens stored as reference token entries and rotated on read/update. - Client metadata validation, software statement validation with trusted keys, mapping to application descriptors (permissions, requirements, logout settings, stored metadata). - Discovery registration_endpoint and configuration validation.pull/2549/head
31 changed files with 3249 additions and 9 deletions
@ -0,0 +1,224 @@ |
|||
/* |
|||
* 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.Text.Json; |
|||
using Microsoft.AspNetCore; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Net.Http.Headers; |
|||
|
|||
namespace OpenIddict.Server.AspNetCore; |
|||
|
|||
public static partial class OpenIddictServerAspNetCoreHandlers |
|||
{ |
|||
public static class Registration |
|||
{ |
|||
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } = |
|||
[ |
|||
/* |
|||
* Registration request extraction: |
|||
*/ |
|||
ExtractRegistrationRequest.Descriptor, |
|||
ExtractAccessToken<ExtractRegistrationRequestContext>.Descriptor, |
|||
|
|||
/* |
|||
* Registration request handling: |
|||
*/ |
|||
EnablePassthroughMode<HandleRegistrationRequestContext, RequireRegistrationEndpointPassthroughEnabled>.Descriptor, |
|||
|
|||
/* |
|||
* Registration response processing: |
|||
*/ |
|||
AttachHttpResponseCode<ApplyRegistrationResponseContext>.Descriptor, |
|||
AttachCacheControlHeader<ApplyRegistrationResponseContext>.Descriptor, |
|||
AttachWwwAuthenticateHeader<ApplyRegistrationResponseContext>.Descriptor, |
|||
ProcessChallengeErrorResponse<ApplyRegistrationResponseContext>.Descriptor, |
|||
ProcessNoContentResponse.Descriptor, |
|||
ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor |
|||
]; |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for extracting registration requests: client metadata are extracted from
|
|||
/// the JSON payload of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2) and the
|
|||
/// client identifier used by the client configuration endpoint is extracted from the query string.
|
|||
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
|
|||
/// </summary>
|
|||
public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler<ExtractRegistrationRequestContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictServerHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictServerHandlerDescriptor.CreateBuilder<ExtractRegistrationRequestContext>() |
|||
.AddFilter<RequireHttpRequest>() |
|||
.UseSingletonHandler<ExtractRegistrationRequest>() |
|||
.SetOrder(ExtractPostRequest<ExtractRegistrationRequestContext>.Descriptor.Order) |
|||
.SetType(OpenIddictServerHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public async ValueTask HandleAsync(ExtractRegistrationRequestContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
|
|||
// this may indicate that the request was incorrectly processed by another server stack.
|
|||
var request = context.Transaction.GetHttpRequest() |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); |
|||
|
|||
var query = new OpenIddictRequest(request.Query); |
|||
|
|||
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsDelete(request.Method)) |
|||
{ |
|||
context.Transaction.Request = query; |
|||
return; |
|||
} |
|||
|
|||
if (!HttpMethods.IsPost(request.Method) && !HttpMethods.IsPut(request.Method)) |
|||
{ |
|||
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.Method); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.GetResourceString(SR.ID2084), |
|||
uri: SR.FormatID8000(SR.ID2084)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
if (string.IsNullOrEmpty(request.ContentType)) |
|||
{ |
|||
context.Logger.LogInformation(6138, SR.GetResourceString(SR.ID6138), HeaderNames.ContentType); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2081(HeaderNames.ContentType), |
|||
uri: SR.FormatID8000(SR.ID2081)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
// May have media/type; charset=utf-8, allow partial match.
|
|||
if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
context.Logger.LogInformation(6139, SR.GetResourceString(SR.ID6139), HeaderNames.ContentType, request.ContentType); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2082(HeaderNames.ContentType), |
|||
uri: SR.FormatID8000(SR.ID2082)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
JsonElement payload; |
|||
|
|||
try |
|||
{ |
|||
using var document = await JsonDocument.ParseAsync(request.Body, cancellationToken: context.CancellationToken); |
|||
payload = document.RootElement.Clone(); |
|||
} |
|||
|
|||
catch (JsonException) |
|||
{ |
|||
payload = default; |
|||
} |
|||
|
|||
if (payload.ValueKind is not JsonValueKind.Object) |
|||
{ |
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.GetResourceString(SR.ID2419), |
|||
uri: SR.FormatID8000(SR.ID2419)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
if (!TryMergeQueryParameters(new OpenIddictRequest(payload), query, out var result)) |
|||
{ |
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2413(Parameters.ClientId), |
|||
uri: SR.FormatID8000(SR.ID2413)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
context.Transaction.Request = result; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for processing successful client deletion responses, that MUST
|
|||
/// be returned as empty 204 responses (RFC 7592, section 2.3).
|
|||
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
|
|||
/// </summary>
|
|||
public sealed class ProcessNoContentResponse : IOpenIddictServerHandler<ApplyRegistrationResponseContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictServerHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyRegistrationResponseContext>() |
|||
.AddFilter<RequireHttpRequest>() |
|||
.UseSingletonHandler<ProcessNoContentResponse>() |
|||
.SetOrder(ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor.Order - 1_000) |
|||
.SetType(OpenIddictServerHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(ApplyRegistrationResponseContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); |
|||
|
|||
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); |
|||
|
|||
if (response.StatusCode is not 204) |
|||
{ |
|||
return ValueTask.CompletedTask; |
|||
} |
|||
|
|||
context.Logger.LogInformation(6609, SR.GetResourceString(SR.ID6609)); |
|||
context.HandleRequest(); |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Merges the query string parameters with the parameters extracted from the JSON payload.
|
|||
/// </summary>
|
|||
internal static bool TryMergeQueryParameters(OpenIddictRequest payload, OpenIddictRequest query, out OpenIddictRequest result) |
|||
{ |
|||
result = payload; |
|||
|
|||
foreach (var parameter in query.GetParameters()) |
|||
{ |
|||
if (!payload.HasParameter(parameter.Key)) |
|||
{ |
|||
payload.SetParameter(parameter.Key, parameter.Value); |
|||
continue; |
|||
} |
|||
|
|||
// The client identifier specified in the payload of update requests MUST match
|
|||
// the client identifier used to identify the client configuration endpoint.
|
|||
//
|
|||
// See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information.
|
|||
if (parameter.Key is Parameters.ClientId && |
|||
!string.Equals((string?) payload[Parameters.ClientId], (string?) parameter.Value, StringComparison.Ordinal)) |
|||
{ |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
return true; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,219 @@ |
|||
/* |
|||
* 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.Text.Json; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Primitives; |
|||
using Owin; |
|||
using static OpenIddict.Server.Owin.OpenIddictServerOwinConstants; |
|||
|
|||
namespace OpenIddict.Server.Owin; |
|||
|
|||
public static partial class OpenIddictServerOwinHandlers |
|||
{ |
|||
public static class Registration |
|||
{ |
|||
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } = |
|||
[ |
|||
/* |
|||
* Registration request extraction: |
|||
*/ |
|||
ExtractRegistrationRequest.Descriptor, |
|||
ExtractAccessToken<ExtractRegistrationRequestContext>.Descriptor, |
|||
|
|||
/* |
|||
* Registration request handling: |
|||
*/ |
|||
EnablePassthroughMode<HandleRegistrationRequestContext, RequireRegistrationEndpointPassthroughEnabled>.Descriptor, |
|||
|
|||
/* |
|||
* Registration response processing: |
|||
*/ |
|||
AttachHttpResponseCode<ApplyRegistrationResponseContext>.Descriptor, |
|||
AttachOwinResponseChallenge<ApplyRegistrationResponseContext>.Descriptor, |
|||
SuppressFormsAuthenticationRedirect<ApplyRegistrationResponseContext>.Descriptor, |
|||
AttachCacheControlHeader<ApplyRegistrationResponseContext>.Descriptor, |
|||
AttachWwwAuthenticateHeader<ApplyRegistrationResponseContext>.Descriptor, |
|||
ProcessChallengeErrorResponse<ApplyRegistrationResponseContext>.Descriptor, |
|||
ProcessNoContentResponse.Descriptor, |
|||
ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor |
|||
]; |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for extracting registration requests: client metadata are extracted from
|
|||
/// the JSON payload of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2) and the
|
|||
/// client identifier used by the client configuration endpoint is extracted from the query string.
|
|||
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
|
|||
/// </summary>
|
|||
public sealed class ExtractRegistrationRequest : IOpenIddictServerHandler<ExtractRegistrationRequestContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictServerHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictServerHandlerDescriptor.CreateBuilder<ExtractRegistrationRequestContext>() |
|||
.AddFilter<RequireOwinRequest>() |
|||
.UseSingletonHandler<ExtractRegistrationRequest>() |
|||
.SetOrder(ExtractPostRequest<ExtractRegistrationRequestContext>.Descriptor.Order) |
|||
.SetType(OpenIddictServerHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public async ValueTask HandleAsync(ExtractRegistrationRequestContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
|
|||
// this may indicate that the request was incorrectly processed by another server stack.
|
|||
var request = context.Transaction.GetOwinRequest() |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); |
|||
|
|||
var query = new OpenIddictRequest( |
|||
from parameter in request.Query |
|||
let values = new StringValues(parameter.Value) |
|||
select KeyValuePair.Create(parameter.Key, values)); |
|||
|
|||
if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase) || |
|||
string.Equals(request.Method, "DELETE", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
context.Transaction.Request = query; |
|||
return; |
|||
} |
|||
|
|||
if (!string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase) && |
|||
!string.Equals(request.Method, "PUT", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
context.Logger.LogInformation(6137, SR.GetResourceString(SR.ID6137), request.Method); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.GetResourceString(SR.ID2084), |
|||
uri: SR.FormatID8000(SR.ID2084)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
if (string.IsNullOrEmpty(request.ContentType)) |
|||
{ |
|||
context.Logger.LogInformation(6138, SR.GetResourceString(SR.ID6138), Headers.ContentType); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2081(Headers.ContentType), |
|||
uri: SR.FormatID8000(SR.ID2081)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
// May have media/type; charset=utf-8, allow partial match.
|
|||
if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
context.Logger.LogInformation(6139, SR.GetResourceString(SR.ID6139), Headers.ContentType, request.ContentType); |
|||
|
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2082(Headers.ContentType), |
|||
uri: SR.FormatID8000(SR.ID2082)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
JsonElement payload; |
|||
|
|||
try |
|||
{ |
|||
using var document = await JsonDocument.ParseAsync(request.Body, cancellationToken: context.CancellationToken); |
|||
payload = document.RootElement.Clone(); |
|||
} |
|||
|
|||
catch (JsonException) |
|||
{ |
|||
payload = default; |
|||
} |
|||
|
|||
if (payload.ValueKind is not JsonValueKind.Object) |
|||
{ |
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.GetResourceString(SR.ID2419), |
|||
uri: SR.FormatID8000(SR.ID2419)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
var result = new OpenIddictRequest(payload); |
|||
|
|||
foreach (var parameter in query.GetParameters()) |
|||
{ |
|||
if (!result.HasParameter(parameter.Key)) |
|||
{ |
|||
result.SetParameter(parameter.Key, parameter.Value); |
|||
continue; |
|||
} |
|||
|
|||
// The client identifier specified in the payload of update requests MUST match
|
|||
// the client identifier used to identify the client configuration endpoint.
|
|||
//
|
|||
// See https://datatracker.ietf.org/doc/html/rfc7592#section-2.2 for more information.
|
|||
if (parameter.Key is Parameters.ClientId && |
|||
!string.Equals((string?) result[Parameters.ClientId], (string?) parameter.Value, StringComparison.Ordinal)) |
|||
{ |
|||
context.Reject( |
|||
error: Errors.InvalidRequest, |
|||
description: SR.FormatID2413(Parameters.ClientId), |
|||
uri: SR.FormatID8000(SR.ID2413)); |
|||
|
|||
return; |
|||
} |
|||
} |
|||
|
|||
context.Transaction.Request = result; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for processing successful client deletion responses, that MUST
|
|||
/// be returned as empty 204 responses (RFC 7592, section 2.3).
|
|||
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
|
|||
/// </summary>
|
|||
public sealed class ProcessNoContentResponse : IOpenIddictServerHandler<ApplyRegistrationResponseContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictServerHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyRegistrationResponseContext>() |
|||
.AddFilter<RequireOwinRequest>() |
|||
.UseSingletonHandler<ProcessNoContentResponse>() |
|||
.SetOrder(ProcessJsonResponse<ApplyRegistrationResponseContext>.Descriptor.Order - 1_000) |
|||
.SetType(OpenIddictServerHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(ApplyRegistrationResponseContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); |
|||
|
|||
var response = context.Transaction.GetOwinRequest()?.Context.Response |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); |
|||
|
|||
if (response.StatusCode is not 204) |
|||
{ |
|||
return ValueTask.CompletedTask; |
|||
} |
|||
|
|||
context.Logger.LogInformation(6609, SR.GetResourceString(SR.ID6609)); |
|||
context.HandleRequest(); |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,240 @@ |
|||
/* |
|||
* 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; |
|||
using System.Text.Json; |
|||
|
|||
namespace OpenIddict.Server; |
|||
|
|||
public static partial class OpenIddictServerEvents |
|||
{ |
|||
/// <summary>
|
|||
/// Resolves the type of a registration operation from the HTTP method used by the client (RFC 7591 and RFC 7592).
|
|||
/// </summary>
|
|||
internal static OpenIddictServerRegistrationRequestType GetRegistrationRequestType(string? method) => method switch |
|||
{ |
|||
_ when string.Equals(method, "POST", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Registration, |
|||
_ when string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Read, |
|||
_ when string.Equals(method, "PUT", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Update, |
|||
_ when string.Equals(method, "DELETE", StringComparison.OrdinalIgnoreCase) => OpenIddictServerRegistrationRequestType.Deletion, |
|||
|
|||
_ => OpenIddictServerRegistrationRequestType.Unknown |
|||
}; |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each request to the registration endpoint to give the user code
|
|||
/// a chance to manually extract the registration request from the ambient HTTP context.
|
|||
/// </summary>
|
|||
public sealed class ExtractRegistrationRequestContext : BaseValidatingContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="ExtractRegistrationRequestContext"/> class.
|
|||
/// </summary>
|
|||
public ExtractRegistrationRequestContext(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>
|
|||
/// Gets the type of the registration operation, resolved from the HTTP method.
|
|||
/// </summary>
|
|||
public OpenIddictServerRegistrationRequestType RequestType |
|||
=> GetRegistrationRequestType(Transaction.RequestMethod); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each request to the registration endpoint to determine if the request
|
|||
/// is valid and should continue to be processed. Custom handlers can be used to enforce additional
|
|||
/// registration policies (e.g to approve or reject a registration based on the client metadata).
|
|||
/// </summary>
|
|||
public sealed class ValidateRegistrationRequestContext : BaseValidatingContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="ValidateRegistrationRequestContext"/> class.
|
|||
/// </summary>
|
|||
public ValidateRegistrationRequestContext(OpenIddictServerTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the request.
|
|||
/// </summary>
|
|||
public OpenIddictRequest Request |
|||
{ |
|||
get => Transaction.Request!; |
|||
set => Transaction.Request = value; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets the type of the registration operation, resolved from the HTTP method.
|
|||
/// </summary>
|
|||
public OpenIddictServerRegistrationRequestType RequestType |
|||
=> GetRegistrationRequestType(Transaction.RequestMethod); |
|||
|
|||
/// <summary>
|
|||
/// Gets the client identifier targeted by the client configuration endpoint (RFC 7592), if applicable.
|
|||
/// </summary>
|
|||
public string? ClientId => RequestType is OpenIddictServerRegistrationRequestType.Registration |
|||
? null : Transaction.Request?.ClientId; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the security principal extracted from the initial access token, if applicable.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// Note: custom handlers executed before the built-in handlers can set this property
|
|||
/// to accept initial access tokens that are not issued by this authorization server.
|
|||
/// </remarks>
|
|||
public ClaimsPrincipal? InitialAccessTokenPrincipal { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the token entry representing the registration access token, if applicable.
|
|||
/// </summary>
|
|||
public object? RegistrationAccessToken { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the security principal extracted from the software statement, if applicable.
|
|||
/// </summary>
|
|||
public ClaimsPrincipal? SoftwareStatementPrincipal { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the application managed using the client configuration endpoint, if applicable.
|
|||
/// </summary>
|
|||
public object? Application { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the client authentication method resolved from the client metadata.
|
|||
/// </summary>
|
|||
public string? TokenEndpointAuthenticationMethod { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets the grant types resolved from the client metadata.
|
|||
/// </summary>
|
|||
public HashSet<string> GrantTypes { get; } = new(StringComparer.Ordinal); |
|||
|
|||
/// <summary>
|
|||
/// Gets the response types resolved from the client metadata.
|
|||
/// </summary>
|
|||
public HashSet<string> ResponseTypes { get; } = new(StringComparer.Ordinal); |
|||
|
|||
/// <summary>
|
|||
/// Gets the scopes resolved from the client metadata.
|
|||
/// </summary>
|
|||
public HashSet<string> Scopes { get; } = new(StringComparer.Ordinal); |
|||
|
|||
/// <summary>
|
|||
/// Gets the client metadata accepted by the authorization server. Unrecognized
|
|||
/// metadata are ignored, as required by RFC 7591, section 2, and not included.
|
|||
/// </summary>
|
|||
public Dictionary<string, JsonElement> Metadata { get; } = new(StringComparer.Ordinal); |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the descriptor representing the client application that will be created or updated.
|
|||
/// Custom handlers executed after the built-in handlers can inspect or amend it (e.g to restrict
|
|||
/// the permissions granted to the client application) or reject the request.
|
|||
/// </summary>
|
|||
public OpenIddictApplicationDescriptor Descriptor { get; set; } = new(); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each validated registration request
|
|||
/// to allow the user code to decide how the request should be handled.
|
|||
/// </summary>
|
|||
public sealed class HandleRegistrationRequestContext : BaseValidatingContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="HandleRegistrationRequestContext"/> class.
|
|||
/// </summary>
|
|||
public HandleRegistrationRequestContext(OpenIddictServerTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the request.
|
|||
/// </summary>
|
|||
public OpenIddictRequest Request |
|||
{ |
|||
get => Transaction.Request!; |
|||
set => Transaction.Request = value; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets the type of the registration operation, resolved from the HTTP method.
|
|||
/// </summary>
|
|||
public OpenIddictServerRegistrationRequestType RequestType |
|||
=> GetRegistrationRequestType(Transaction.RequestMethod); |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the application read, updated or deleted by this request, if applicable.
|
|||
/// </summary>
|
|||
public object? Application { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the descriptor representing the client application that will be created or updated.
|
|||
/// </summary>
|
|||
public OpenIddictApplicationDescriptor Descriptor { get; set; } = new(); |
|||
|
|||
/// <summary>
|
|||
/// Gets the additional parameters returned to the client application.
|
|||
/// </summary>
|
|||
public Dictionary<string, OpenIddictParameter> Parameters { get; } = new(StringComparer.Ordinal); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called before the registration response is returned to the caller.
|
|||
/// </summary>
|
|||
public sealed class ApplyRegistrationResponseContext : BaseRequestContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="ApplyRegistrationResponseContext"/> class.
|
|||
/// </summary>
|
|||
public ApplyRegistrationResponseContext(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 type of the registration operation, resolved from the HTTP method.
|
|||
/// </summary>
|
|||
public OpenIddictServerRegistrationRequestType RequestType |
|||
=> GetRegistrationRequestType(Transaction.RequestMethod); |
|||
|
|||
/// <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; |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,38 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Server; |
|||
|
|||
/// <summary>
|
|||
/// Represents the type of an operation performed using the dynamic client registration endpoint.
|
|||
/// </summary>
|
|||
public enum OpenIddictServerRegistrationRequestType |
|||
{ |
|||
/// <summary>
|
|||
/// Unknown operation (e.g unsupported HTTP method).
|
|||
/// </summary>
|
|||
Unknown = 0, |
|||
|
|||
/// <summary>
|
|||
/// Client registration request (RFC 7591, HTTP POST).
|
|||
/// </summary>
|
|||
Registration = 1, |
|||
|
|||
/// <summary>
|
|||
/// Client read request (RFC 7592, HTTP GET).
|
|||
/// </summary>
|
|||
Read = 2, |
|||
|
|||
/// <summary>
|
|||
/// Client update request (RFC 7592, HTTP PUT).
|
|||
/// </summary>
|
|||
Update = 3, |
|||
|
|||
/// <summary>
|
|||
/// Client delete request (RFC 7592, HTTP DELETE).
|
|||
/// </summary>
|
|||
Deletion = 4 |
|||
} |
|||
@ -0,0 +1,197 @@ |
|||
/* |
|||
* 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.Cryptography; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using Microsoft.IdentityModel.Tokens; |
|||
using Xunit; |
|||
|
|||
namespace OpenIddict.Server.Tests; |
|||
|
|||
public class OpenIddictServerRegistrationTests |
|||
{ |
|||
[Fact] |
|||
public void SetRegistrationEndpointUris_AddsUris() |
|||
{ |
|||
// Arrange
|
|||
var services = new ServiceCollection().AddOptions(); |
|||
var builder = new OpenIddictServerBuilder(services); |
|||
|
|||
// Act
|
|||
builder.SetRegistrationEndpointUris("http://localhost/connect/register"); |
|||
|
|||
// Assert
|
|||
Assert.Contains(new Uri("http://localhost/connect/register"), GetOptions(services).RegistrationEndpointUris); |
|||
} |
|||
|
|||
[Fact] |
|||
public void SetRegistrationEndpointUris_ThrowsAnExceptionForUriStartingWithTilde() |
|||
{ |
|||
// Arrange
|
|||
var builder = new OpenIddictServerBuilder(new ServiceCollection()); |
|||
|
|||
// Act and assert
|
|||
var exception = Assert.Throws<ArgumentException>(() => builder.SetRegistrationEndpointUris("~/connect/register")); |
|||
Assert.Equal("uris", exception.ParamName); |
|||
} |
|||
|
|||
[Fact] |
|||
public void RegistrationMethods_UpdateTheOptions() |
|||
{ |
|||
// Arrange
|
|||
var services = new ServiceCollection().AddOptions(); |
|||
var builder = new OpenIddictServerBuilder(services); |
|||
var key = new RsaSecurityKey(RSA.Create(2048)); |
|||
|
|||
// Act
|
|||
builder.EnableDynamicClientRegistration() |
|||
.AllowAnonymousClientRegistration() |
|||
.SetInitialAccessTokenScopes("dcr") |
|||
.SetRegistrationAccessTokenLifetime(TimeSpan.FromDays(1)) |
|||
.RequireSoftwareStatement() |
|||
.AddSoftwareStatementSigningKey(key, "https://issuer.example.com/"); |
|||
|
|||
var options = GetOptions(services); |
|||
|
|||
// Assert
|
|||
Assert.True(options.EnableDynamicClientRegistration); |
|||
Assert.True(options.AllowAnonymousClientRegistration); |
|||
Assert.Equal(["dcr"], options.InitialAccessTokenScopes); |
|||
Assert.Equal(TimeSpan.FromDays(1), options.RegistrationAccessTokenLifetime); |
|||
Assert.True(options.RequireSoftwareStatement); |
|||
Assert.Same(key, Assert.Single(options.SoftwareStatementSigningKeys)); |
|||
Assert.Equal(["https://issuer.example.com/"], options.SoftwareStatementIssuers); |
|||
} |
|||
|
|||
[Fact] |
|||
public void SetInitialAccessTokenScopes_ThrowsAnExceptionForEmptyScope() |
|||
{ |
|||
// Arrange
|
|||
var builder = new OpenIddictServerBuilder(new ServiceCollection()); |
|||
|
|||
// Act and assert
|
|||
var exception = Assert.Throws<ArgumentException>(() => builder.SetInitialAccessTokenScopes(string.Empty)); |
|||
Assert.Equal("scopes", exception.ParamName); |
|||
} |
|||
|
|||
[Fact] |
|||
public void AddSoftwareStatementSigningKey_ThrowsAnExceptionForNullKey() |
|||
{ |
|||
// Arrange
|
|||
var builder = new OpenIddictServerBuilder(new ServiceCollection()); |
|||
|
|||
// Act and assert
|
|||
var exception = Assert.Throws<ArgumentNullException>(() => builder.AddSoftwareStatementSigningKey(null!)); |
|||
Assert.Equal("key", exception.ParamName); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Validate_ReturnsAnErrorWhenRegistrationEndpointIsMissing() |
|||
{ |
|||
// Arrange
|
|||
var options = CreateBaseOptions(); |
|||
options.EnableDynamicClientRegistration = true; |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.Contains(SR.GetResourceString(SR.ID0800), result.Failures!, StringComparer.Ordinal); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Validate_ReturnsAnErrorWhenDynamicClientRegistrationIsDisabled() |
|||
{ |
|||
// Arrange
|
|||
var options = CreateBaseOptions(); |
|||
options.RegistrationEndpointUris.Add(new Uri("connect/register", UriKind.Relative)); |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.Contains(SR.GetResourceString(SR.ID0801), result.Failures!, StringComparer.Ordinal); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(true, false)] |
|||
[InlineData(false, true)] |
|||
public void Validate_ReturnsAnErrorWhenIncompatibleSettingsAreUsed(bool degraded, bool storage) |
|||
{ |
|||
// Arrange
|
|||
var options = CreateRegistrationOptions(); |
|||
options.EnableDegradedMode = degraded; |
|||
options.DisableTokenStorage = storage; |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.Contains(SR.GetResourceString(SR.ID0802), result.Failures!, StringComparer.Ordinal); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Validate_ReturnsAnErrorWhenNoInitialAccessTokenScopeIsConfigured() |
|||
{ |
|||
// Arrange
|
|||
var options = CreateRegistrationOptions(); |
|||
options.InitialAccessTokenScopes.Clear(); |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.Contains(SR.GetResourceString(SR.ID0803), result.Failures!, StringComparer.Ordinal); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Validate_DoesNotRequireInitialAccessTokenScopesForAnonymousRegistration() |
|||
{ |
|||
// Arrange
|
|||
var options = CreateRegistrationOptions(); |
|||
options.InitialAccessTokenScopes.Clear(); |
|||
options.AllowAnonymousClientRegistration = true; |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.DoesNotContain(SR.GetResourceString(SR.ID0803), result.Failures ?? [], StringComparer.Ordinal); |
|||
} |
|||
|
|||
[Fact] |
|||
public void Validate_ReturnsAnErrorWhenSoftwareStatementsAreRequiredWithoutSigningKeys() |
|||
{ |
|||
// Arrange
|
|||
var options = CreateRegistrationOptions(); |
|||
options.RequireSoftwareStatement = true; |
|||
|
|||
// Act
|
|||
var result = Validate(options); |
|||
|
|||
// Assert
|
|||
Assert.Contains(SR.GetResourceString(SR.ID0804), result.Failures!, StringComparer.Ordinal); |
|||
} |
|||
|
|||
private static OpenIddictServerOptions CreateBaseOptions() => new() { TimeProvider = TimeProvider.System }; |
|||
|
|||
private static OpenIddictServerOptions CreateRegistrationOptions() |
|||
{ |
|||
var options = CreateBaseOptions(); |
|||
options.EnableDynamicClientRegistration = true; |
|||
options.RegistrationEndpointUris.Add(new Uri("connect/register", UriKind.Relative)); |
|||
options.InitialAccessTokenScopes.Add("dcr"); |
|||
|
|||
return options; |
|||
} |
|||
|
|||
private static ValidateOptionsResult Validate(OpenIddictServerOptions options) |
|||
=> new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()).Validate(name: null, options); |
|||
|
|||
private static OpenIddictServerOptions GetOptions(IServiceCollection services) |
|||
=> services.BuildServiceProvider().GetRequiredService<IOptions<OpenIddictServerOptions>>().Value; |
|||
} |
|||
Loading…
Reference in new issue