Browse Source
- OpenIddictClientService.RegisterAsync (RFC 7591) and GetRegistrationAsync, UpdateRegistrationAsync, DeleteRegistrationAsync (RFC 7592), with registration request/response events and error mapping. - System.Net.Http integration sending JSON payloads with bearer initial/registration access tokens. - Discovery extraction of the registration_endpoint metadata.pull/2549/head
11 changed files with 1288 additions and 4 deletions
@ -0,0 +1,160 @@ |
|||
/* |
|||
* 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.Net.Http; |
|||
using System.Net.Http.Headers; |
|||
using System.Text.Json; |
|||
using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpConstants; |
|||
|
|||
namespace OpenIddict.Client.SystemNetHttp; |
|||
|
|||
public static partial class OpenIddictClientSystemNetHttpHandlers |
|||
{ |
|||
public static class Registration |
|||
{ |
|||
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } = |
|||
[ |
|||
/* |
|||
* Registration request processing: |
|||
*/ |
|||
CreateHttpClient<PrepareRegistrationRequestContext>.Descriptor, |
|||
PrepareRegistrationHttpRequest.Descriptor, |
|||
AttachHttpVersion<PrepareRegistrationRequestContext>.Descriptor, |
|||
AttachJsonAcceptHeaders<PrepareRegistrationRequestContext>.Descriptor, |
|||
AttachUserAgentHeader<PrepareRegistrationRequestContext>.Descriptor, |
|||
AttachFromHeader<PrepareRegistrationRequestContext>.Descriptor, |
|||
AttachBearerAccessToken.Descriptor, |
|||
AttachJsonHttpParameters.Descriptor, |
|||
SendHttpRequest<ApplyRegistrationRequestContext>.Descriptor, |
|||
DisposeHttpRequest<ApplyRegistrationRequestContext>.Descriptor, |
|||
|
|||
/* |
|||
* Registration response processing: |
|||
*/ |
|||
DecompressResponseContent<ExtractRegistrationResponseContext>.Descriptor, |
|||
ExtractJsonHttpResponse<ExtractRegistrationResponseContext>.Descriptor, |
|||
ExtractWwwAuthenticateHeader<ExtractRegistrationResponseContext>.Descriptor, |
|||
ExtractEmptyHttpResponse<ExtractRegistrationResponseContext>.Descriptor, |
|||
ValidateHttpResponse<ExtractRegistrationResponseContext>.Descriptor, |
|||
DisposeHttpResponse<ExtractRegistrationResponseContext>.Descriptor |
|||
]; |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for preparing an HTTP request message using the method attached to the context.
|
|||
/// </summary>
|
|||
public sealed class PrepareRegistrationHttpRequest : IOpenIddictClientHandler<PrepareRegistrationRequestContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictClientHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>() |
|||
.AddFilter<RequireHttpUri>() |
|||
.UseSingletonHandler<PrepareRegistrationHttpRequest>() |
|||
.SetOrder(PreparePostHttpRequest<PrepareRegistrationRequestContext>.Descriptor.Order) |
|||
.SetType(OpenIddictClientHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(PrepareRegistrationRequestContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
// Store the HttpRequestMessage in the transaction properties.
|
|||
context.Transaction.SetProperty(typeof(HttpRequestMessage).FullName!, |
|||
new HttpRequestMessage(new HttpMethod(context.RequestMethod), context.RemoteUri)); |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for attaching the initial access token or
|
|||
/// the registration access token to the standard HTTP Authorization header.
|
|||
/// </summary>
|
|||
public sealed class AttachBearerAccessToken : IOpenIddictClientHandler<PrepareRegistrationRequestContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictClientHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>() |
|||
.AddFilter<RequireHttpUri>() |
|||
.UseSingletonHandler<AttachBearerAccessToken>() |
|||
.SetOrder(AttachJsonHttpParameters.Descriptor.Order - 500) |
|||
.SetType(OpenIddictClientHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(PrepareRegistrationRequestContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
|
|||
// this may indicate that the request was incorrectly processed by another client stack.
|
|||
var request = context.Transaction.GetHttpRequestMessage() |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); |
|||
|
|||
// Note: don't overwrite the authorization header if one was already set by another handler.
|
|||
if (request.Headers.Authorization is null && !string.IsNullOrEmpty(context.AccessToken)) |
|||
{ |
|||
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.AccessToken); |
|||
} |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for attaching the client metadata to the JSON payload
|
|||
/// of POST and PUT requests (RFC 7591, section 3.1 and RFC 7592, section 2.2).
|
|||
/// </summary>
|
|||
public sealed class AttachJsonHttpParameters : IOpenIddictClientHandler<PrepareRegistrationRequestContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictClientHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictClientHandlerDescriptor.CreateBuilder<PrepareRegistrationRequestContext>() |
|||
.AddFilter<RequireHttpUri>() |
|||
.UseSingletonHandler<AttachJsonHttpParameters>() |
|||
.SetOrder(AttachHttpParameters<PrepareRegistrationRequestContext>.Descriptor.Order) |
|||
.SetType(OpenIddictClientHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(PrepareRegistrationRequestContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008)); |
|||
|
|||
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
|
|||
// this may indicate that the request was incorrectly processed by another client stack.
|
|||
var request = context.Transaction.GetHttpRequestMessage() |
|||
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); |
|||
|
|||
if (request.Method != HttpMethod.Post && request.Method != HttpMethod.Put) |
|||
{ |
|||
return ValueTask.CompletedTask; |
|||
} |
|||
|
|||
using var stream = new MemoryStream(); |
|||
using (var writer = new Utf8JsonWriter(stream)) |
|||
{ |
|||
context.Transaction.Request.WriteTo(writer); |
|||
} |
|||
|
|||
request.Content = new ByteArrayContent(stream.ToArray()); |
|||
request.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypes.Json) { CharSet = "utf-8" }; |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,122 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Client; |
|||
|
|||
public static partial class OpenIddictClientEvents |
|||
{ |
|||
/// <summary>
|
|||
/// Represents an abstract base class used by the dynamic client registration events (RFC 7591 and RFC 7592).
|
|||
/// </summary>
|
|||
public abstract class BaseRegistrationContext : BaseExternalContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="BaseRegistrationContext"/> class.
|
|||
/// </summary>
|
|||
protected BaseRegistrationContext(OpenIddictClientTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the request.
|
|||
/// </summary>
|
|||
public OpenIddictRequest Request |
|||
{ |
|||
get => Transaction.Request!; |
|||
set => Transaction.Request = value; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the HTTP method used to send the request: POST for registration requests (RFC 7591)
|
|||
/// and GET, PUT or DELETE for read, update and delete requests (RFC 7592).
|
|||
/// </summary>
|
|||
public string RequestMethod { get; set; } = "POST"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the bearer token attached to the request (i.e the initial access
|
|||
/// token for registration requests or the registration access token), if applicable.
|
|||
/// </summary>
|
|||
public string? AccessToken { get; set; } |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each request to the registration endpoint
|
|||
/// to give the user code a chance to add metadata to the registration request.
|
|||
/// </summary>
|
|||
public sealed class PrepareRegistrationRequestContext : BaseRegistrationContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="PrepareRegistrationRequestContext"/> class.
|
|||
/// </summary>
|
|||
public PrepareRegistrationRequestContext(OpenIddictClientTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each request to the registration endpoint
|
|||
/// to send the registration request to the remote authorization server.
|
|||
/// </summary>
|
|||
public sealed class ApplyRegistrationRequestContext : BaseRegistrationContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="ApplyRegistrationRequestContext"/> class.
|
|||
/// </summary>
|
|||
public ApplyRegistrationRequestContext(OpenIddictClientTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each registration response
|
|||
/// to extract the response parameters from the server response.
|
|||
/// </summary>
|
|||
public sealed class ExtractRegistrationResponseContext : BaseRegistrationContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="ExtractRegistrationResponseContext"/> class.
|
|||
/// </summary>
|
|||
public ExtractRegistrationResponseContext(OpenIddictClientTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the response, or <see langword="null"/> if it wasn't extracted yet.
|
|||
/// </summary>
|
|||
public OpenIddictResponse? Response |
|||
{ |
|||
get => Transaction.Response; |
|||
set => Transaction.Response = value; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents an event called for each registration response.
|
|||
/// </summary>
|
|||
public sealed class HandleRegistrationResponseContext : BaseRegistrationContext |
|||
{ |
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="HandleRegistrationResponseContext"/> class.
|
|||
/// </summary>
|
|||
public HandleRegistrationResponseContext(OpenIddictClientTransaction transaction) |
|||
: base(transaction) |
|||
{ |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the response.
|
|||
/// </summary>
|
|||
public OpenIddictResponse Response |
|||
{ |
|||
get => Transaction.Response!; |
|||
set => Transaction.Response = value; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,129 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Collections.Immutable; |
|||
using System.Text.Json; |
|||
using Microsoft.Extensions.Logging; |
|||
|
|||
namespace OpenIddict.Client; |
|||
|
|||
public static partial class OpenIddictClientHandlers |
|||
{ |
|||
public static class Registration |
|||
{ |
|||
public static ImmutableArray<OpenIddictClientHandlerDescriptor> DefaultHandlers { get; } = |
|||
[ |
|||
/* |
|||
* Registration response handling: |
|||
*/ |
|||
ValidateWellKnownParameters.Descriptor, |
|||
HandleErrorResponse.Descriptor |
|||
]; |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for validating the well-known parameters contained in the registration response.
|
|||
/// </summary>
|
|||
public sealed class ValidateWellKnownParameters : IOpenIddictClientHandler<HandleRegistrationResponseContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictClientHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleRegistrationResponseContext>() |
|||
.UseSingletonHandler<ValidateWellKnownParameters>() |
|||
.SetOrder(int.MinValue + 100_000) |
|||
.SetType(OpenIddictClientHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(HandleRegistrationResponseContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
foreach (var parameter in context.Response.GetParameters()) |
|||
{ |
|||
if (!ValidateParameterType(parameter.Key, parameter.Value)) |
|||
{ |
|||
context.Reject( |
|||
error: Errors.ServerError, |
|||
description: SR.FormatID2107(parameter.Key), |
|||
uri: SR.FormatID8000(SR.ID2107)); |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
return ValueTask.CompletedTask; |
|||
|
|||
// See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.1 for more information.
|
|||
static bool ValidateParameterType(string name, OpenIddictParameter value) => name switch |
|||
{ |
|||
// The following parameters MUST be formatted as unique strings:
|
|||
Parameters.Error or Parameters.ErrorDescription or Parameters.ErrorUri or |
|||
ClientMetadata.ClientId or ClientMetadata.ClientSecret or |
|||
ClientMetadata.RegistrationAccessToken or ClientMetadata.RegistrationClientUri |
|||
=> ((JsonElement) value).ValueKind is JsonValueKind.String, |
|||
|
|||
// The following parameters MUST be formatted as numeric dates:
|
|||
ClientMetadata.ClientIdIssuedAt or ClientMetadata.ClientSecretExpiresAt |
|||
=> ((JsonElement) value).ValueKind is JsonValueKind.Number, |
|||
|
|||
// Other metadata can be of any type.
|
|||
_ => true |
|||
}; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Contains the logic responsible for surfacing potential errors from the registration response.
|
|||
/// </summary>
|
|||
public sealed class HandleErrorResponse : IOpenIddictClientHandler<HandleRegistrationResponseContext> |
|||
{ |
|||
/// <summary>
|
|||
/// Gets the default descriptor definition assigned to this handler.
|
|||
/// </summary>
|
|||
public static OpenIddictClientHandlerDescriptor Descriptor { get; } |
|||
= OpenIddictClientHandlerDescriptor.CreateBuilder<HandleRegistrationResponseContext>() |
|||
.UseSingletonHandler<HandleErrorResponse>() |
|||
.SetOrder(ValidateWellKnownParameters.Descriptor.Order + 1_000) |
|||
.SetType(OpenIddictClientHandlerType.BuiltIn) |
|||
.Build(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask HandleAsync(HandleRegistrationResponseContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
if (!string.IsNullOrEmpty(context.Response.Error)) |
|||
{ |
|||
context.Logger.LogInformation(6612, SR.GetResourceString(SR.ID6612), context.Response); |
|||
|
|||
// Note: the standard registration errors are preserved to allow the caller to determine
|
|||
// why the registration was rejected (e.g because a redirect URI was not accepted).
|
|||
//
|
|||
// See https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2 for more information.
|
|||
context.Reject( |
|||
error: context.Response.Error switch |
|||
{ |
|||
Errors.InvalidClientMetadata or Errors.InvalidRedirectUri or |
|||
Errors.InvalidSoftwareStatement or Errors.UnapprovedSoftwareStatement or |
|||
Errors.InvalidToken or Errors.InsufficientScope or |
|||
Errors.InsufficientAccess or Errors.InvalidRequest |
|||
=> context.Response.Error, |
|||
|
|||
_ => Errors.ServerError |
|||
}, |
|||
description: SR.GetResourceString(SR.ID2415), |
|||
uri: SR.FormatID8000(SR.ID2415)); |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
|
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,349 @@ |
|||
using System.Collections.Immutable; |
|||
using System.Net.Http; |
|||
using System.Text.Json; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using OpenIddict.Client.SystemNetHttp; |
|||
using Xunit; |
|||
using static OpenIddict.Client.OpenIddictClientEvents; |
|||
using static OpenIddict.Client.OpenIddictClientModels; |
|||
|
|||
namespace OpenIddict.Client.Tests; |
|||
|
|||
public class OpenIddictClientHandlersRegistrationTests |
|||
{ |
|||
[Fact] |
|||
public async Task ExtractRegistrationEndpoint_EndpointIsExtracted() |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>().CurrentValue; |
|||
|
|||
var context = new HandleConfigurationResponseContext(CreateTransaction(provider)) |
|||
{ |
|||
Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>( |
|||
"""{ "registration_endpoint": "https://www.contoso.com/connect/register" }"""))
|
|||
}; |
|||
|
|||
// Act
|
|||
await new OpenIddictClientHandlers.Discovery.ExtractRegistrationEndpoint().HandleAsync(context); |
|||
|
|||
// Assert
|
|||
Assert.False(context.IsRejected); |
|||
Assert.Equal(new Uri("https://www.contoso.com/connect/register"), context.Configuration.RegistrationEndpoint); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ExtractRegistrationEndpoint_InvalidEndpointCausesAnError() |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
|
|||
var context = new HandleConfigurationResponseContext(CreateTransaction(provider)) |
|||
{ |
|||
Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>( |
|||
"""{ "registration_endpoint": "/connect/register" }""")) |
|||
}; |
|||
|
|||
// Act
|
|||
await new OpenIddictClientHandlers.Discovery.ExtractRegistrationEndpoint().HandleAsync(context); |
|||
|
|||
// Assert
|
|||
Assert.True(context.IsRejected); |
|||
Assert.Equal(SR.FormatID2100(Metadata.RegistrationEndpoint), context.ErrorDescription); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("""{ "client_id": 42 }""", ClientMetadata.ClientId)] |
|||
[InlineData("""{ "client_id": "Fabrikam", "client_id_issued_at": "now" }""", ClientMetadata.ClientIdIssuedAt)] |
|||
[InlineData("""{ "client_id": "Fabrikam", "registration_access_token": [ "token" ] }""", ClientMetadata.RegistrationAccessToken)]
|
|||
public async Task ValidateWellKnownParameters_InvalidParameterTypeCausesAnError(string payload, string name) |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
var context = new HandleRegistrationResponseContext(CreateTransaction(provider)) |
|||
{ |
|||
Request = new OpenIddictRequest(), |
|||
Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>(payload)) |
|||
}; |
|||
|
|||
// Act
|
|||
await new OpenIddictClientHandlers.Registration.ValidateWellKnownParameters().HandleAsync(context); |
|||
|
|||
// Assert
|
|||
Assert.True(context.IsRejected); |
|||
Assert.Equal(SR.FormatID2107(name), context.ErrorDescription); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(Errors.InvalidRedirectUri, Errors.InvalidRedirectUri)] |
|||
[InlineData(Errors.InvalidClientMetadata, Errors.InvalidClientMetadata)] |
|||
[InlineData(Errors.UnapprovedSoftwareStatement, Errors.UnapprovedSoftwareStatement)] |
|||
[InlineData(Errors.InvalidToken, Errors.InvalidToken)] |
|||
[InlineData("custom_error", Errors.ServerError)] |
|||
public async Task HandleErrorResponse_ErrorsAreMapped(string error, string expected) |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
var context = new HandleRegistrationResponseContext(CreateTransaction(provider)) |
|||
{ |
|||
Request = new OpenIddictRequest(), |
|||
Response = new OpenIddictResponse { Error = error } |
|||
}; |
|||
|
|||
// Act
|
|||
await new OpenIddictClientHandlers.Registration.HandleErrorResponse().HandleAsync(context); |
|||
|
|||
// Assert
|
|||
Assert.True(context.IsRejected); |
|||
Assert.Equal(expected, context.Error); |
|||
Assert.Equal(SR.GetResourceString(SR.ID2415), context.ErrorDescription); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("POST", true)] |
|||
[InlineData("PUT", true)] |
|||
[InlineData("GET", false)] |
|||
[InlineData("DELETE", false)] |
|||
public async Task SystemNetHttpHandlers_RequestIsCorrectlyPrepared(string method, bool payload) |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
var context = new PrepareRegistrationRequestContext(CreateTransaction(provider)) |
|||
{ |
|||
AccessToken = "registration-token", |
|||
RemoteUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam"), |
|||
Request = new OpenIddictRequest |
|||
{ |
|||
ClientId = "Fabrikam", |
|||
["redirect_uris"] = new OpenIddictParameter(ImmutableArray.Create<string?>("https://www.fabrikam.com/callback")) |
|||
}, |
|||
RequestMethod = method |
|||
}; |
|||
|
|||
// Act
|
|||
await new OpenIddictClientSystemNetHttpHandlers.Registration.PrepareRegistrationHttpRequest().HandleAsync(context); |
|||
await new OpenIddictClientSystemNetHttpHandlers.Registration.AttachBearerAccessToken().HandleAsync(context); |
|||
await new OpenIddictClientSystemNetHttpHandlers.Registration.AttachJsonHttpParameters().HandleAsync(context); |
|||
|
|||
// Assert
|
|||
using var request = context.Transaction.GetProperty<HttpRequestMessage>(typeof(HttpRequestMessage).FullName!)!; |
|||
|
|||
Assert.Equal(method, request.Method.Method); |
|||
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme); |
|||
Assert.Equal("registration-token", request.Headers.Authorization?.Parameter); |
|||
|
|||
if (payload) |
|||
{ |
|||
Assert.NotNull(request.Content); |
|||
Assert.Equal("application/json", request.Content.Headers.ContentType?.MediaType); |
|||
|
|||
using var document = JsonDocument.Parse(await request.Content.ReadAsStringAsync()); |
|||
Assert.Equal("Fabrikam", document.RootElement.GetProperty("client_id").GetString()); |
|||
Assert.Equal("https://www.fabrikam.com/callback", |
|||
document.RootElement.GetProperty("redirect_uris")[0].GetString()); |
|||
} |
|||
|
|||
else |
|||
{ |
|||
Assert.Null(request.Content); |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task RegisterAsync_RegistrationEndpointIsResolvedFromTheServerConfiguration() |
|||
{ |
|||
// Arrange
|
|||
BaseRegistrationContext? sent = null; |
|||
|
|||
using var provider = CreateProvider(options => |
|||
{ |
|||
options.AddEventHandler<ApplyRegistrationRequestContext>(builder => builder.UseInlineHandler(context => |
|||
{ |
|||
sent = context; |
|||
return ValueTask.CompletedTask; |
|||
})); |
|||
|
|||
options.AddEventHandler<ExtractRegistrationResponseContext>(builder => builder.UseInlineHandler(context => |
|||
{ |
|||
context.Response = new OpenIddictResponse(JsonSerializer.Deserialize<JsonElement>("""
|
|||
{ |
|||
"client_id": "Fabrikam", |
|||
"client_secret": "secret", |
|||
"client_id_issued_at": 1700000000, |
|||
"client_secret_expires_at": 0, |
|||
"registration_access_token": "registration-token", |
|||
"registration_client_uri": "https://www.contoso.com/connect/register?client_id=Fabrikam" |
|||
} |
|||
"""));
|
|||
|
|||
return ValueTask.CompletedTask; |
|||
})); |
|||
}); |
|||
|
|||
var service = provider.GetRequiredService<OpenIddictClientService>(); |
|||
|
|||
// Act
|
|||
var result = await service.RegisterAsync(new ClientRegistrationRequest |
|||
{ |
|||
InitialAccessToken = "initial-token", |
|||
Metadata = new(StringComparer.Ordinal) |
|||
{ |
|||
[ClientMetadata.GrantTypes] = new OpenIddictParameter(ImmutableArray.Create<string?>(GrantTypes.ClientCredentials)) |
|||
} |
|||
}); |
|||
|
|||
// Assert
|
|||
Assert.NotNull(sent); |
|||
Assert.Equal("POST", sent.RequestMethod); |
|||
Assert.Equal("initial-token", sent.AccessToken); |
|||
Assert.Equal(new Uri("https://www.contoso.com/connect/register"), sent.RemoteUri); |
|||
Assert.Equal(GrantTypes.ClientCredentials, ((ImmutableArray<string?>?) sent.Request[ClientMetadata.GrantTypes])?[0]); |
|||
|
|||
Assert.Equal("Fabrikam", result.ClientId); |
|||
Assert.Equal("secret", result.ClientSecret); |
|||
Assert.Null(result.ClientSecretExpiresAt); |
|||
Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1700000000), result.ClientIdIssuedAt); |
|||
Assert.Equal("registration-token", result.RegistrationAccessToken); |
|||
Assert.Equal(new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam"), result.RegistrationClientUri); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task RegisterAsync_ThrowsAnExceptionWhenNoRegistrationEndpointIsAvailable() |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(configuration: new OpenIddictConfiguration |
|||
{ |
|||
Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute) |
|||
}); |
|||
|
|||
var service = provider.GetRequiredService<OpenIddictClientService>(); |
|||
|
|||
// Act and assert
|
|||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => |
|||
await service.RegisterAsync(new ClientRegistrationRequest())); |
|||
|
|||
Assert.Equal(SR.GetResourceString(SR.ID0809), exception.Message); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("GET")] |
|||
[InlineData("PUT")] |
|||
[InlineData("DELETE")] |
|||
public async Task ClientConfigurationMethods_RequestsAreSentToTheClientConfigurationEndpoint(string method) |
|||
{ |
|||
// Arrange
|
|||
BaseRegistrationContext? sent = null; |
|||
|
|||
using var provider = CreateProvider(options => |
|||
{ |
|||
options.AddEventHandler<ApplyRegistrationRequestContext>(builder => builder.UseInlineHandler(context => |
|||
{ |
|||
sent = context; |
|||
return ValueTask.CompletedTask; |
|||
})); |
|||
|
|||
options.AddEventHandler<ExtractRegistrationResponseContext>(builder => builder.UseInlineHandler(context => |
|||
{ |
|||
context.Response = new OpenIddictResponse(); |
|||
return ValueTask.CompletedTask; |
|||
})); |
|||
}); |
|||
|
|||
var service = provider.GetRequiredService<OpenIddictClientService>(); |
|||
var request = new ClientConfigurationRequest |
|||
{ |
|||
Metadata = new(StringComparer.Ordinal) |
|||
{ |
|||
[ClientMetadata.ClientName] = "Updated" |
|||
}, |
|||
RegistrationAccessToken = "registration-token", |
|||
RegistrationClientUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam") |
|||
}; |
|||
|
|||
// Act
|
|||
var result = method switch |
|||
{ |
|||
"GET" => await service.GetRegistrationAsync(request), |
|||
"PUT" => await service.UpdateRegistrationAsync(request), |
|||
_ => await service.DeleteRegistrationAsync(request) |
|||
}; |
|||
|
|||
// Assert
|
|||
Assert.NotNull(sent); |
|||
Assert.Equal(method, sent.RequestMethod); |
|||
Assert.Equal("registration-token", sent.AccessToken); |
|||
Assert.Equal(request.RegistrationClientUri, sent.RemoteUri); |
|||
Assert.NotNull(result.RegistrationResponse); |
|||
|
|||
if (method is "PUT") |
|||
{ |
|||
Assert.Equal("Fabrikam", sent.Request.ClientId); |
|||
Assert.Equal("Updated", (string?) sent.Request[ClientMetadata.ClientName]); |
|||
} |
|||
|
|||
else |
|||
{ |
|||
Assert.Equal(0, sent.Request.Count); |
|||
} |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ClientConfigurationMethods_ThrowAnExceptionForMissingRegistrationAccessToken() |
|||
{ |
|||
// Arrange
|
|||
using var provider = CreateProvider(); |
|||
var service = provider.GetRequiredService<OpenIddictClientService>(); |
|||
|
|||
// Act and assert
|
|||
await Assert.ThrowsAsync<ArgumentException>(async () => await service.GetRegistrationAsync(new ClientConfigurationRequest |
|||
{ |
|||
RegistrationAccessToken = string.Empty, |
|||
RegistrationClientUri = new Uri("https://www.contoso.com/connect/register?client_id=Fabrikam") |
|||
})); |
|||
} |
|||
|
|||
private static ServiceProvider CreateProvider( |
|||
Action<OpenIddictClientBuilder>? configure = null, OpenIddictConfiguration? configuration = null) |
|||
{ |
|||
var services = new ServiceCollection(); |
|||
|
|||
services.AddOpenIddict() |
|||
.AddClient(options => |
|||
{ |
|||
options.AllowClientCredentialsFlow(); |
|||
|
|||
options.AddEphemeralEncryptionKey() |
|||
.AddEphemeralSigningKey(); |
|||
|
|||
options.AddRegistration(new OpenIddictClientRegistration |
|||
{ |
|||
ClientId = "Fabrikam", |
|||
Configuration = configuration ?? new OpenIddictConfiguration |
|||
{ |
|||
Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute), |
|||
RegistrationEndpoint = new Uri("https://www.contoso.com/connect/register", UriKind.Absolute) |
|||
}, |
|||
Issuer = new Uri("https://www.contoso.com/", UriKind.Absolute) |
|||
}); |
|||
|
|||
configure?.Invoke(options); |
|||
}); |
|||
|
|||
return services.BuildServiceProvider(); |
|||
} |
|||
|
|||
private static OpenIddictClientTransaction CreateTransaction(IServiceProvider provider) |
|||
{ |
|||
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>().CurrentValue; |
|||
|
|||
return new OpenIddictClientTransaction |
|||
{ |
|||
CancellationToken = CancellationToken.None, |
|||
Configuration = new OpenIddictConfiguration(), |
|||
Options = options, |
|||
Registration = options.Registrations[0], |
|||
ServiceProvider = provider |
|||
}; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue