diff --git a/Directory.Build.props b/Directory.Build.props index 213a49ea..010570cd 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -106,7 +106,6 @@ - net6.0; net8.0; net9.0 @@ -137,8 +136,6 @@ - net6.0-windows7.0; - net6.0-windows10.0.17763; net8.0-windows7.0; net8.0-windows10.0.17763; net9.0-windows7.0; diff --git a/Directory.Build.targets b/Directory.Build.targets index 46dfd60b..fe5cadfe 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -15,212 +15,124 @@ false - - 21.0 - - 12.2 - - 15.0 - - 12.0 - - 7.0 - - - + annotations - - $(DefineConstants);SUPPORTS_NAMED_PIPE_CONSTRUCTOR_WITH_ACL - - - - $(DefineConstants);SUPPORTS_ECDSA - - - - $(DefineConstants);SUPPORTS_CERTIFICATE_GENERATION - $(DefineConstants);SUPPORTS_EPHEMERAL_KEY_SETS - $(DefineConstants);SUPPORTS_KEY_DERIVATION_WITH_SPECIFIED_HASH_ALGORITHM - $(DefineConstants);SUPPORTS_RSA_KEY_CREATION_WITH_SPECIFIED_SIZE - $(DefineConstants);SUPPORTS_TOHASHSET_LINQ_EXTENSION - - - - $(DefineConstants);SUPPORTS_BROTLI_COMPRESSION - $(DefineConstants);SUPPORTS_CURRENT_USER_ONLY_PIPE_OPTION - $(DefineConstants);SUPPORTS_STATIC_RANDOM_NUMBER_GENERATOR_METHODS - $(DefineConstants);SUPPORTS_STREAM_MEMORY_METHODS - $(DefineConstants);SUPPORTS_TIME_CONSTANT_COMPARISONS + + 21.0 + 12.2 + 15.0 + 12.0 + 7.0 - - $(DefineConstants);SUPPORTS_WEB_INTEGRATION_IN_GENERIC_HOST - $(DefineConstants);SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER + + $(DefineConstants);SUPPORTS_NAMED_PIPE_CONSTRUCTOR_WITH_ACL - + + $(DefineConstants);SUPPORTS_APPLICATION_CONFIGURATION_INITIALIZATION + $(DefineConstants);SUPPORTS_AUTHENTICATION_HANDLER_SELECTION_FALLBACK $(DefineConstants);SUPPORTS_AUTHORIZATION_MIDDLEWARE - $(DefineConstants);SUPPORTS_ENDPOINT_ROUTING - $(DefineConstants);SUPPORTS_HOST_APPLICATION_LIFETIME - $(DefineConstants);SUPPORTS_HOST_ENVIRONMENT - $(DefineConstants);SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION - $(DefineConstants);SUPPORTS_INTEGER32_RANDOM_NUMBER_GENERATOR_METHODS - - - $(DefineConstants);SUPPORTS_BCL_ASYNC_ENUMERABLE + $(DefineConstants);SUPPORTS_BULK_DBSET_OPERATIONS $(DefineConstants);SUPPORTS_DBSET_VALUETASK_FINDASYNC - - - + $(DefineConstants);SUPPORTS_ENDPOINT_ROUTING $(DefineConstants);SUPPORTS_ENVIRONMENT_PROCESS_PATH $(DefineConstants);SUPPORTS_HEXADECIMAL_STRING_CONVERSION + $(DefineConstants);SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION $(DefineConstants);SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION_POLICY + $(DefineConstants);SUPPORTS_HTTP_CLIENT_RESILIENCE + $(DefineConstants);SUPPORTS_INT32_RANDOM_NUMBER_GENERATOR_METHODS $(DefineConstants);SUPPORTS_MULTIPLE_VALUES_IN_QUERYHELPERS $(DefineConstants);SUPPORTS_NAMED_PIPE_STATIC_FACTORY_WITH_ACL $(DefineConstants);SUPPORTS_ONE_SHOT_HASHING_METHODS + $(DefineConstants);SUPPORTS_ONE_SHOT_RANDOM_NUMBER_GENERATOR_METHODS $(DefineConstants);SUPPORTS_OPERATING_SYSTEM_VERSIONS_COMPARISON $(DefineConstants);SUPPORTS_PEM_ENCODED_KEY_IMPORT + $(DefineConstants);SUPPORTS_REDIRECTION_ON_SIGN_IN + $(DefineConstants);SUPPORTS_TASK_WAIT_ASYNC $(DefineConstants);SUPPORTS_TEXT_ELEMENT_ENUMERATOR + $(DefineConstants);SUPPORTS_TIME_PROVIDER $(DefineConstants);SUPPORTS_WINFORMS_TASK_DIALOG + $(DefineConstants);SUPPORTS_ZLIB_COMPRESSION - $(DefineConstants);SUPPORTS_APPLICATION_CONFIGURATION_INITIALIZATION - $(DefineConstants);SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION - $(DefineConstants);SUPPORTS_JSON_NODES - $(DefineConstants);SUPPORTS_ONE_SHOT_RANDOM_NUMBER_GENERATOR_METHODS - $(DefineConstants);SUPPORTS_TASK_WAIT_ASYNC - $(DefineConstants);SUPPORTS_ZLIB_COMPRESSION + Condition=" ('$(TargetFrameworkIdentifier)' == '.NETCoreApp') Or + ('$(TargetFrameworkIdentifier)' == '.NETFramework' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), '4.7.2'))) Or + ('$(TargetFrameworkIdentifier)' == '.NETStandard') "> + $(DefineConstants);SUPPORTS_ECDSA - $(DefineConstants);SUPPORTS_AUTHENTICATION_HANDLER_SELECTION_FALLBACK - $(DefineConstants);SUPPORTS_BULK_DBSET_OPERATIONS - $(DefineConstants);SUPPORTS_REDIRECTION_ON_SIGN_IN + Condition=" ('$(TargetFrameworkIdentifier)' == '.NETCoreApp') Or + ('$(TargetFrameworkIdentifier)' == '.NETFramework' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), '4.7.2'))) Or + ('$(TargetFrameworkIdentifier)' == '.NETStandard' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), '2.1'))) "> + $(DefineConstants);SUPPORTS_CERTIFICATE_GENERATION + $(DefineConstants);SUPPORTS_EPHEMERAL_KEY_SETS + $(DefineConstants);SUPPORTS_KEY_DERIVATION_WITH_SPECIFIED_HASH_ALGORITHM + $(DefineConstants);SUPPORTS_RSA_KEY_CREATION_WITH_SPECIFIED_SIZE + $(DefineConstants);SUPPORTS_TOHASHSET_LINQ_EXTENSION - $(DefineConstants);SUPPORTS_HTTP_CLIENT_RESILIENCE - $(DefineConstants);SUPPORTS_TIME_PROVIDER + Condition=" ('$(TargetFrameworkIdentifier)' == '.NETCoreApp') Or + ('$(TargetFrameworkIdentifier)' == '.NETStandard' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), '2.1'))) "> + $(DefineConstants);SUPPORTS_BROTLI_COMPRESSION + $(DefineConstants);SUPPORTS_CURRENT_USER_ONLY_PIPE_OPTION + $(DefineConstants);SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER + $(DefineConstants);SUPPORTS_STATIC_RANDOM_NUMBER_GENERATOR_METHODS + $(DefineConstants);SUPPORTS_STREAM_MEMORY_METHODS + $(DefineConstants);SUPPORTS_TIME_CONSTANT_COMPARISONS + $(DefineConstants);SUPPORTS_WEB_INTEGRATION_IN_GENERIC_HOST + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), '9.0')) "> $(DefineConstants);SUPPORTS_CERTIFICATE_LOADER + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' And '$(TargetPlatformIdentifier)' == 'Android' "> $(DefineConstants);SUPPORTS_ANDROID $(DefineConstants);SUPPORTS_ANDROIDX_BROWSER + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' And ('$(TargetPlatformIdentifier)' == 'iOS' Or + '$(TargetPlatformIdentifier)' == 'MacCatalyst') "> $(DefineConstants);SUPPORTS_UIKIT + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' And '$(TargetPlatformIdentifier)' == 'macOS' "> $(DefineConstants);SUPPORTS_APPKIT + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' And ('$(TargetPlatformIdentifier)' == 'iOS' Or + '$(TargetPlatformIdentifier)' == 'MacCatalyst' Or + '$(TargetPlatformIdentifier)' == 'macOS') "> $(DefineConstants);SUPPORTS_AUTHENTICATION_SERVICES $(DefineConstants);SUPPORTS_FOUNDATION - $(DefineConstants);SUPPORTS_PRESENTATION_CONTEXT_PROVIDER - - - @@ -280,8 +192,6 @@ --> + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCore' And '$(TargetPlatformIdentifier)' == 'UAP' " /> diff --git a/Directory.Packages.props b/Directory.Packages.props index 01742c8d..e5344876 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,186 +3,70 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - + + + + + - - - - + + + + - + - - - - + + + + @@ -191,22 +75,21 @@ - - - - - + + + + + - - - - + + + - + @@ -214,53 +97,7 @@ Note: OpenIddict uses PolySharp to dynamically generate polyfills for types that are not available on some of the targeted TFMs (e.g Index, Range or nullable attributes on .NET Framework/.NET Standard). --> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - + + + @@ -308,7 +145,7 @@ Note: OpenIddict uses PolySharp to dynamically generate polyfills for types that are not available on some of the targeted TFMs (e.g Index, Range or nullable attributes on .NET Framework/.NET Standard). --> - + - - - - + + + + @@ -357,20 +194,19 @@ - - - - - - - + + + + + + - + - - - - + + + + - + - + - + diff --git a/eng/AfterTargetFrameworkInference.targets b/eng/AfterTargetFrameworkInference.targets index 0619f910..a41a2f93 100644 --- a/eng/AfterTargetFrameworkInference.targets +++ b/eng/AfterTargetFrameworkInference.targets @@ -6,9 +6,7 @@ --> + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCore' And '$(TargetPlatformIdentifier)' == 'UAP' "> $(MSBuildThisFileDirectory)msbuild\uwp\Microsoft.Windows.UI.Xaml.CSharp.targets diff --git a/gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs b/gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs index fb642c88..db688794 100644 --- a/gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs +++ b/gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs @@ -8,40 +8,37 @@ using Scriban; namespace OpenIddict.Client.WebIntegration.Generators; [Generator] -public sealed class OpenIddictClientWebIntegrationGenerator : ISourceGenerator +public sealed class OpenIddictClientWebIntegrationGenerator : IIncrementalGenerator { - public void Execute(GeneratorExecutionContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - var file = context.AdditionalFiles.Select(file => file.Path) - .Where(path => string.Equals(Path.GetFileName(path), "OpenIddictClientWebIntegrationProviders.xml")) - .SingleOrDefault(); + var files = context.AdditionalTextsProvider.Where(static file => + string.Equals(Path.GetFileName(file.Path), "OpenIddictClientWebIntegrationProviders.xml")); - if (string.IsNullOrEmpty(file)) + context.RegisterSourceOutput(files, static (context, file) => { - return; - } - - var document = XDocument.Load(file, LoadOptions.None); + var document = XDocument.Load(file.Path, LoadOptions.None); - context.AddSource( - "OpenIddictClientWebIntegrationBuilder.generated.cs", - SourceText.From(GenerateBuilderMethods(document), Encoding.UTF8)); + context.AddSource( + "OpenIddictClientWebIntegrationBuilder.generated.cs", + SourceText.From(GenerateBuilderMethods(document), Encoding.UTF8)); - context.AddSource( - "OpenIddictClientWebIntegrationConfiguration.generated.cs", - SourceText.From(GenerateConfigurationClasses(document), Encoding.UTF8)); + context.AddSource( + "OpenIddictClientWebIntegrationConfiguration.generated.cs", + SourceText.From(GenerateConfigurationClasses(document), Encoding.UTF8)); - context.AddSource( - "OpenIddictClientWebIntegrationConstants.generated.cs", - SourceText.From(GenerateConstants(document), Encoding.UTF8)); + context.AddSource( + "OpenIddictClientWebIntegrationConstants.generated.cs", + SourceText.From(GenerateConstants(document), Encoding.UTF8)); - context.AddSource( - "OpenIddictClientWebIntegrationHelpers.generated.cs", - SourceText.From(GenerateHelpers(document), Encoding.UTF8)); + context.AddSource( + "OpenIddictClientWebIntegrationHelpers.generated.cs", + SourceText.From(GenerateHelpers(document), Encoding.UTF8)); - context.AddSource( - "OpenIddictClientWebIntegrationSettings.generated.cs", - SourceText.From(GenerateSettings(document), Encoding.UTF8)); + context.AddSource( + "OpenIddictClientWebIntegrationSettings.generated.cs", + SourceText.From(GenerateSettings(document), Encoding.UTF8)); + }); static string GenerateBuilderMethods(XDocument document) { diff --git a/global.json b/global.json index 46ca446b..1079c586 100644 --- a/global.json +++ b/global.json @@ -1,17 +1,16 @@ { "sdk": { - "version": "9.0.200", + "version": "9.0.201", "allowPrerelease": true, "rollForward": "major" }, "tools": { - "dotnet": "9.0.200", + "dotnet": "9.0.201", "runtimes": { "aspnetcore": [ - "6.0.36", - "8.0.13" + "8.0.14" ] } }, diff --git a/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config b/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config index 3de2282b..4d8a81c1 100644 --- a/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config +++ b/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config @@ -42,8 +42,8 @@ - - + + @@ -66,8 +66,8 @@ - - + + @@ -78,8 +78,8 @@ - - + + @@ -90,8 +90,8 @@ - - + + @@ -132,8 +132,8 @@ - - + + @@ -190,6 +190,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs b/sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs index 4e5e5bdf..7244449f 100644 --- a/sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs +++ b/sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs @@ -62,7 +62,7 @@ public class AuthorizationController : Controller // If the user principal can't be extracted or the cookie is too old, redirect the user to the login page. var result = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie); if (result?.Identity == null || (request.MaxAge != null && result.Properties?.IssuedUtc != null && - DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))) + TimeProvider.System.GetUtcNow() - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))) { // For applications that want to allow the client to select the external authentication provider // that will be used to authenticate the user, the identity_provider parameter can be used for that. diff --git a/sandbox/OpenIddict.Sandbox.AspNet.Server/Web.config b/sandbox/OpenIddict.Sandbox.AspNet.Server/Web.config index 514602c6..0d83dfde 100644 --- a/sandbox/OpenIddict.Sandbox.AspNet.Server/Web.config +++ b/sandbox/OpenIddict.Sandbox.AspNet.Server/Web.config @@ -48,8 +48,8 @@ - - + + @@ -90,8 +90,8 @@ - - + + @@ -102,8 +102,8 @@ - - + + @@ -114,8 +114,8 @@ - - + + @@ -202,6 +202,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj b/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj index 45bd16fc..1a869b67 100644 --- a/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj +++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj @@ -16,10 +16,7 @@ - + diff --git a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs index d3ee0f81..9bc8de93 100644 --- a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs +++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs @@ -78,7 +78,7 @@ public class AuthorizationController : Controller var result = await HttpContext.AuthenticateAsync(); if (result == null || !result.Succeeded || request.HasPromptValue(PromptValues.Login) || (request.MaxAge != null && result.Properties?.IssuedUtc != null && - DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))) + TimeProvider.System.GetUtcNow() - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))) { // If the client application requested promptless authentication, // return an error indicating that the user is not logged in. diff --git a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj index 6ea1a61e..435a5656 100644 --- a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj +++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj @@ -19,10 +19,7 @@ - + diff --git a/sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs b/sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs index a07f2b37..9c810a40 100644 --- a/sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs +++ b/sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs @@ -6,10 +6,6 @@ using Spectre.Console; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Abstractions.OpenIddictExceptions; -#if !SUPPORTS_HOST_APPLICATION_LIFETIME -using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime; -#endif - namespace OpenIddict.Sandbox.Console.Client; public class InteractiveService : BackgroundService diff --git a/sandbox/OpenIddict.Sandbox.Console.Client/OpenIddict.Sandbox.Console.Client.csproj b/sandbox/OpenIddict.Sandbox.Console.Client/OpenIddict.Sandbox.Console.Client.csproj index f1cea6a8..cf5219b1 100644 --- a/sandbox/OpenIddict.Sandbox.Console.Client/OpenIddict.Sandbox.Console.Client.csproj +++ b/sandbox/OpenIddict.Sandbox.Console.Client/OpenIddict.Sandbox.Console.Client.csproj @@ -18,8 +18,4 @@ - - - - diff --git a/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs b/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs index 12dab54e..6f6cba14 100644 --- a/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs +++ b/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs @@ -6,116 +6,106 @@ using OpenIddict.Client; using OpenIddict.Sandbox.Console.Client; using static OpenIddict.Abstractions.OpenIddictConstants; -var host = new HostBuilder() - // Note: applications for which a single instance is preferred can reference - // the Dapplo.Microsoft.Extensions.Hosting.AppServices package and call this - // method to automatically close extra instances based on the specified identifier: - // - // .ConfigureSingleInstance(options => options.MutexId = "{802A478D-00E8-4DAE-9A27-27B31A47CB39}") - // - .ConfigureLogging(options => options.AddDebug()) - .ConfigureServices(services => +var builder = Host.CreateApplicationBuilder(); + +builder.Logging.ClearProviders(); +builder.Logging.AddDebug(); + +builder.Services.AddDbContext(options => +{ + options.UseSqlite($"Filename={Path.Combine(Path.GetTempPath(), "openiddict-sandbox-console-client.sqlite3")}"); + options.UseOpenIddict(); +}); + +builder.Services.AddOpenIddict() + + // Register the OpenIddict core components. + .AddCore(options => + { + // Configure OpenIddict to use the Entity Framework Core stores and models. + // Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities. + options.UseEntityFrameworkCore() + .UseDbContext(); + }) + + // Register the OpenIddict client components. + .AddClient(options => { - services.AddDbContext(options => + // Note: this sample enables all the supported flows but + // you can restrict the list of enabled flows if necessary. + options.AllowAuthorizationCodeFlow() + .AllowClientCredentialsFlow() + .AllowDeviceAuthorizationFlow() + .AllowHybridFlow() + .AllowImplicitFlow() + .AllowNoneFlow() + .AllowPasswordFlow() + .AllowRefreshTokenFlow(); + + // Register the signing and encryption credentials used to protect + // sensitive data like the state tokens produced by OpenIddict. + options.AddDevelopmentEncryptionCertificate() + .AddDevelopmentSigningCertificate(); + + // Add the operating system integration. + options.UseSystemIntegration() + .DisableActivationHandling() + .DisableActivationRedirection() + .DisablePipeServer() + .EnableEmbeddedWebServer() + .UseSystemBrowser() + .SetApplicationDiscriminator("0XP3WQ07VVMCVBJ") + .SetAllowedEmbeddedWebServerPorts(49152, 49153, 49154); + + // Register the System.Net.Http integration and use the identity of the current + // assembly as a more specific user agent, which can be useful when dealing with + // providers that use the user agent as a way to throttle requests (e.g Reddit). + options.UseSystemNetHttp() + .SetProductInformation(typeof(Program).Assembly); + + // Add a client registration matching the client application definition in the server project. + options.AddRegistration(new OpenIddictClientRegistration { - options.UseSqlite($"Filename={Path.Combine(Path.GetTempPath(), "openiddict-sandbox-console-client.sqlite3")}"); - options.UseOpenIddict(); - }); + Issuer = new Uri("https://localhost:44395/", UriKind.Absolute), + ProviderName = "Local", + ProviderDisplayName = "Local authorization server", - services.AddOpenIddict() - - // Register the OpenIddict core components. - .AddCore(options => - { - // Configure OpenIddict to use the Entity Framework Core stores and models. - // Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities. - options.UseEntityFrameworkCore() - .UseDbContext(); - }) - - // Register the OpenIddict client components. - .AddClient(options => - { - // Note: this sample enables all the supported flows but - // you can restrict the list of enabled flows if necessary. - options.AllowAuthorizationCodeFlow() - .AllowClientCredentialsFlow() - .AllowDeviceAuthorizationFlow() - .AllowHybridFlow() - .AllowImplicitFlow() - .AllowNoneFlow() - .AllowPasswordFlow() - .AllowRefreshTokenFlow(); - - // Register the signing and encryption credentials used to protect - // sensitive data like the state tokens produced by OpenIddict. - options.AddDevelopmentEncryptionCertificate() - .AddDevelopmentSigningCertificate(); - - // Add the operating system integration. - options.UseSystemIntegration() - .DisableActivationHandling() - .DisableActivationRedirection() - .DisablePipeServer() - .EnableEmbeddedWebServer() - .UseSystemBrowser() - .SetApplicationDiscriminator("0XP3WQ07VVMCVBJ") - .SetAllowedEmbeddedWebServerPorts(49152, 49153, 49154); - - // Register the System.Net.Http integration and use the identity of the current - // assembly as a more specific user agent, which can be useful when dealing with - // providers that use the user agent as a way to throttle requests (e.g Reddit). - options.UseSystemNetHttp() - .SetProductInformation(typeof(Program).Assembly); - - // Add a client registration matching the client application definition in the server project. - options.AddRegistration(new OpenIddictClientRegistration - { - Issuer = new Uri("https://localhost:44395/", UriKind.Absolute), - ProviderName = "Local", - ProviderDisplayName = "Local authorization server", - - ClientId = "console", - - PostLogoutRedirectUri = new Uri("callback/logout/local", UriKind.Relative), - RedirectUri = new Uri("callback/login/local", UriKind.Relative), - - Scopes = { Scopes.Email, Scopes.Profile, Scopes.OfflineAccess, "demo_api" } - }); - - // Register the Web providers integrations. - // - // Note: to mitigate mix-up attacks, it's recommended to use a unique redirection endpoint - // address per provider, unless all the registered providers support returning an "iss" - // parameter containing their URL as part of authorization responses. For more information, - // see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-4.4. - options.UseWebProviders() - .AddGitHub(options => - { - options.SetClientId("992372d088f8676a7945") - .SetClientSecret("1f18c22f766e44d7bd4ea4a6510b9e337d48ab38") - .SetRedirectUri("callback/login/github"); - }) - .AddTwitter(options => - { - options.SetClientId("bXgwc0U3N3A3YWNuaWVsdlRmRWE6MTpjaQ") - .SetRedirectUri("callback/login/twitter"); - }); - }); - - // Register the worker responsible for creating the database used to store tokens - // and adding the registry entries required to register the custom URI scheme. - // - // Note: in a real world application, this step should be part of a setup script. - services.AddHostedService(); + ClientId = "console", - // Register the background service responsible for handling the console interactions. - services.AddHostedService(); + PostLogoutRedirectUri = new Uri("callback/logout/local", UriKind.Relative), + RedirectUri = new Uri("callback/login/local", UriKind.Relative), - // Prevent the console lifetime manager from writing status messages to the output stream. - services.Configure(options => options.SuppressStatusMessages = true); - }) - .UseConsoleLifetime() - .Build(); + Scopes = { Scopes.Email, Scopes.Profile, Scopes.OfflineAccess, "demo_api" } + }); -await host.RunAsync(); \ No newline at end of file + // Register the Web providers integrations. + // + // Note: to mitigate mix-up attacks, it's recommended to use a unique redirection endpoint + // address per provider, unless all the registered providers support returning an "iss" + // parameter containing their URL as part of authorization responses. For more information, + // see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-4.4. + options.UseWebProviders() + .AddGitHub(options => + { + options.SetClientId("992372d088f8676a7945") + .SetClientSecret("1f18c22f766e44d7bd4ea4a6510b9e337d48ab38") + .SetRedirectUri("callback/login/github"); + }) + .AddTwitter(options => + { + options.SetClientId("bXgwc0U3N3A3YWNuaWVsdlRmRWE6MTpjaQ") + .SetRedirectUri("callback/login/twitter"); + }); + }); + +// Register the worker responsible for creating the database used to store tokens +// and adding the registry entries required to register the custom URI scheme. +// +// Note: in a real world application, this step should be part of a setup script. +builder.Services.AddHostedService(); + +// Register the background service responsible for handling the console interactions. +builder.Services.AddHostedService(); + +var app = builder.Build(); +await app.RunAsync(); diff --git a/sandbox/OpenIddict.Sandbox.Maui.Client/OpenIddict.Sandbox.Maui.Client.csproj b/sandbox/OpenIddict.Sandbox.Maui.Client/OpenIddict.Sandbox.Maui.Client.csproj index 1eeedb4a..8d55d7e1 100644 --- a/sandbox/OpenIddict.Sandbox.Maui.Client/OpenIddict.Sandbox.Maui.Client.csproj +++ b/sandbox/OpenIddict.Sandbox.Maui.Client/OpenIddict.Sandbox.Maui.Client.csproj @@ -27,7 +27,6 @@ - diff --git a/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj b/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj index 13981f23..72076a39 100644 --- a/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj +++ b/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj @@ -9,8 +9,7 @@ - + diff --git a/shared/OpenIddict.Extensions/OpenIddictHelpers.cs b/shared/OpenIddict.Extensions/OpenIddictHelpers.cs index 0133d08c..ef6902e1 100644 --- a/shared/OpenIddict.Extensions/OpenIddictHelpers.cs +++ b/shared/OpenIddict.Extensions/OpenIddictHelpers.cs @@ -855,7 +855,7 @@ internal static class OpenIddictHelpers // Pick a character in the specified charset by generating a random index. builder.Append(charset[index: algorithm switch { -#if SUPPORTS_INTEGER32_RANDOM_NUMBER_GENERATOR_METHODS +#if SUPPORTS_INT32_RANDOM_NUMBER_GENERATOR_METHODS // If no custom random number generator was registered, use // the static GetInt32() API on platforms that support it. null => RandomNumberGenerator.GetInt32(0, charset.Length), diff --git a/src/OpenIddict.Abstractions/OpenIddict.Abstractions.csproj b/src/OpenIddict.Abstractions/OpenIddict.Abstractions.csproj index e37692f0..a3cc3048 100644 --- a/src/OpenIddict.Abstractions/OpenIddict.Abstractions.csproj +++ b/src/OpenIddict.Abstractions/OpenIddict.Abstractions.csproj @@ -26,8 +26,7 @@ + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index d1659638..019f7ca3 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -496,7 +496,7 @@ This may indicate that the event handler responsible for processing OpenID Conne The ASP.NET Core HTTP request cannot be resolved. - Only strings, booleans, integers, arrays of strings and instances of type 'OpenIddictParameter' or 'JsonElement' can be returned as custom parameters. On .NET 6.0 and higher, instances of type 'JsonNode' (i.e 'JsonArray', 'JsonObject' and 'JsonValue') are also supported. + Only strings, booleans, integers, arrays of strings and instances of type 'OpenIddictParameter', 'JsonElement' or derived from 'JsonNode' can be returned as custom parameters. A distributed cache instance must be registered when enabling request caching. diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs index 76fb40cc..f0fa2dfc 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs @@ -10,13 +10,10 @@ using System.Diagnostics; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using Microsoft.Extensions.Primitives; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Abstractions; /// @@ -69,7 +66,6 @@ public class OpenIddictMessage } } -#if SUPPORTS_JSON_NODES /// /// Initializes a new OpenIddict message. /// @@ -100,7 +96,6 @@ public class OpenIddictMessage AddParameter(parameter.Key, parameter.Value); } } -#endif /// /// Initializes a new OpenIddict message. diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs index d6be1a7e..0caf8ef5 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs @@ -9,10 +9,7 @@ using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Text.Json; - -#if SUPPORTS_JSON_NODES using System.Text.Json.Nodes; -#endif namespace OpenIddict.Abstractions; @@ -40,13 +37,11 @@ public readonly struct OpenIddictParameter : IEquatable /// The parameter value. public OpenIddictParameter(JsonElement value) => Value = value; -#if SUPPORTS_JSON_NODES /// /// Initializes a new parameter using the specified value. /// /// The parameter value. public OpenIddictParameter(JsonNode? value) => Value = value; -#endif /// /// Initializes a new parameter using the specified value. @@ -103,7 +98,6 @@ public readonly struct OpenIddictParameter : IEquatable JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element => Count(element), -#if SUPPORTS_JSON_NODES // If the parameter is a JsonArray, return its length. JsonArray value => value.Count, @@ -128,7 +122,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element => Count(element), -#endif + // Otherwise, return 0. _ => 0 }; @@ -232,7 +226,6 @@ public readonly struct OpenIddictParameter : IEquatable (string left, JsonElement { ValueKind: JsonValueKind.String } right) => string.Equals(left, right.GetString(), StringComparison.Ordinal), -#if SUPPORTS_JSON_NODES // When one of the parameters is a JsonValue, try to compare their underlying values // if the wrapped type is a common CLR primitive type to avoid the less efficient // JsonElement-based comparison, that requires doing a full JSON serialization. @@ -250,17 +243,11 @@ public readonly struct OpenIddictParameter : IEquatable (string left, JsonValue right) when right.TryGetValue(out string? result) => string.Equals(left, result, StringComparison.Ordinal), -#endif + // Otherwise, serialize both values to JsonElement and compare them. -#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION var (left, right) => DeepEquals( JsonSerializer.SerializeToElement(left, left.GetType()), JsonSerializer.SerializeToElement(right, right.GetType())) -#else - var (left, right) => DeepEquals( - JsonSerializer.Deserialize(JsonSerializer.Serialize(left, left.GetType())), - JsonSerializer.Deserialize(JsonSerializer.Serialize(right, right.GetType()))) -#endif }; static bool DeepEquals(JsonElement left, JsonElement right) @@ -358,7 +345,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement, compute its hash code. JsonElement value => GetHashCodeFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonValue wrapping a JsonElement, // apply the same logic as with direct JsonElement instances. JsonValue value when value.TryGetValue(out JsonElement element) @@ -379,7 +365,7 @@ public readonly struct OpenIddictParameter : IEquatable // and apply the same logic as with non-wrapped JsonElement instances. JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => GetHashCodeFromJsonElement(element), -#endif + // Otherwise, use the default hash code method. var value => value.GetHashCode() }; @@ -479,7 +465,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement representing an object, return the requested item. JsonElement { ValueKind: JsonValueKind.Object } value => GetParametersFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonObject, return the requested item. JsonObject value => GetParametersFromJsonNode(value), @@ -489,7 +474,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement { ValueKind: JsonValueKind.Object } element => GetParametersFromJsonElement(element), -#endif + _ => ImmutableDictionary.Create(StringComparer.Ordinal) }; @@ -505,8 +490,6 @@ public readonly struct OpenIddictParameter : IEquatable return parameters; } -#if SUPPORTS_JSON_NODES - static IReadOnlyDictionary GetParametersFromJsonNode(JsonObject node) { var parameters = new Dictionary(node.Count, StringComparer.Ordinal); @@ -518,7 +501,6 @@ public readonly struct OpenIddictParameter : IEquatable return parameters; } -#endif } /// @@ -536,7 +518,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement representing an array, return its children. JsonElement { ValueKind: JsonValueKind.Array } value => GetParametersFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonArray, return its children. JsonArray value => GetParametersFromJsonNode(value), @@ -546,7 +527,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement { ValueKind: JsonValueKind.Array } element => GetParametersFromJsonElement(element), -#endif + _ => ImmutableList.Create() }; @@ -575,7 +556,6 @@ public readonly struct OpenIddictParameter : IEquatable return parameters; } -#if SUPPORTS_JSON_NODES static IReadOnlyList GetParametersFromJsonNode(JsonArray node) { var parameters = new OpenIddictParameter[node.Count]; @@ -587,7 +567,6 @@ public readonly struct OpenIddictParameter : IEquatable return parameters; } -#endif } /// @@ -609,7 +588,6 @@ public readonly struct OpenIddictParameter : IEquatable JsonElement value => value.ToString(), -#if SUPPORTS_JSON_NODES JsonValue value when value.TryGetValue(out JsonElement element) => element.ValueKind switch { @@ -638,7 +616,7 @@ public readonly struct OpenIddictParameter : IEquatable _ => element.ToString() }, -#endif + _ => string.Empty }; @@ -661,7 +639,6 @@ public readonly struct OpenIddictParameter : IEquatable JsonElement { ValueKind: JsonValueKind.Object } element => element.TryGetProperty(name, out JsonElement property) ? new(property) : null, -#if SUPPORTS_JSON_NODES // When the parameter is a JsonObject, return the requested item. JsonObject node => node.TryGetPropertyValue(name, out JsonNode? property) ? new(property) : null, @@ -671,7 +648,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode node when JsonSerializer.SerializeToElement(node) is JsonElement { ValueKind: JsonValueKind.Object } element => element.TryGetProperty(name, out JsonElement property) ? new(property) : null, -#endif + _ => (OpenIddictParameter?) null }; @@ -701,7 +678,6 @@ public readonly struct OpenIddictParameter : IEquatable JsonElement { ValueKind: JsonValueKind.Array } element => index < element.GetArrayLength() ? new(element[index]) : null, -#if SUPPORTS_JSON_NODES // When the parameter is a JsonArray, return the requested item. JsonArray node => index < node.Count ? new(node[index]) : null, @@ -711,7 +687,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode node when JsonSerializer.SerializeToElement(node) is JsonElement { ValueKind: JsonValueKind.Array } element => index < element.GetArrayLength() ? new(element) : null, -#endif + _ => (OpenIddictParameter?) null }; @@ -765,11 +741,9 @@ public readonly struct OpenIddictParameter : IEquatable value.WriteTo(writer); break; -#if SUPPORTS_JSON_NODES case JsonNode value: value.WriteTo(writer); break; -#endif } } @@ -818,7 +792,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement, try to convert it if it's of a supported type. JsonElement value => ConvertFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonValue wrapping a JsonElement, // apply the same logic as with direct JsonElement instances. JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element), @@ -835,7 +808,7 @@ public readonly struct OpenIddictParameter : IEquatable // and apply the same logic as with non-wrapped JsonElement instances. JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => ConvertFromJsonElement(element), -#endif + // If the parameter is of a different type, return null to indicate the conversion failed. _ => null }; @@ -868,10 +841,9 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is already a JsonElement, return it as-is. JsonElement value => value, -#if SUPPORTS_JSON_NODES // When the parameter is JsonNode, serialize it as a JsonElement. JsonNode value => JsonSerializer.SerializeToElement(value), -#endif + // When the parameter is a string starting with '{' or '[' (which would correspond // to a JSON object or array), try to deserialize it to get a JsonElement instance. string { Length: > 0 } value when value[0] is '{' or '[' => @@ -879,11 +851,7 @@ public readonly struct OpenIddictParameter : IEquatable DeserializeElement(JsonSerializer.Serialize(value)) ?? default, // Otherwise, serialize it to get a JsonElement instance. -#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION object value => JsonSerializer.SerializeToElement(value, value.GetType()) -#else - object value => DeserializeElement(JsonSerializer.Serialize(value)) ?? default -#endif }; static JsonElement? DeserializeElement(string value) @@ -901,7 +869,6 @@ public readonly struct OpenIddictParameter : IEquatable } } -#if SUPPORTS_JSON_NODES /// /// Converts an instance to a . /// @@ -989,7 +956,6 @@ public readonly struct OpenIddictParameter : IEquatable /// The converted value. public static explicit operator JsonValue?(OpenIddictParameter? parameter) => ((JsonNode?) parameter) as JsonValue; -#endif /// /// Converts an instance to a long integer. @@ -1021,7 +987,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement, try to convert it if it's of a supported type. JsonElement value => ConvertFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonValue wrapping a JsonElement, // apply the same logic as with direct JsonElement instances. JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element), @@ -1040,7 +1005,7 @@ public readonly struct OpenIddictParameter : IEquatable // and apply the same logic as with non-wrapped JsonElement instances. JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => ConvertFromJsonElement(element), -#endif + // If the parameter is of a different type, return null to indicate the conversion failed. _ => null }; @@ -1086,7 +1051,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement, try to convert it if it's of a supported type. JsonElement value => ConvertFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonValue wrapping a JsonElement, // apply the same logic as with direct JsonElement instances. JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element), @@ -1106,7 +1070,7 @@ public readonly struct OpenIddictParameter : IEquatable // and apply the same logic as with non-wrapped JsonElement instances. JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => ConvertFromJsonElement(element), -#endif + // If the parameter is of a different type, return null to indicate the conversion failed. _ => null }; @@ -1157,7 +1121,6 @@ public readonly struct OpenIddictParameter : IEquatable // When the parameter is a JsonElement, try to convert it if it's of a supported type. JsonElement value => ConvertFromJsonElement(value), -#if SUPPORTS_JSON_NODES // When the parameter is a JsonValue wrapping a JsonElement, // apply the same logic as with direct JsonElement instances. JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element), @@ -1181,7 +1144,7 @@ public readonly struct OpenIddictParameter : IEquatable // and apply the same logic as with non-wrapped JsonElement instances. JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => ConvertFromJsonElement(element), -#endif + // If the parameter is of a different type, return null to indicate the conversion failed. _ => null }; @@ -1258,14 +1221,12 @@ public readonly struct OpenIddictParameter : IEquatable /// An instance. public static implicit operator OpenIddictParameter(JsonElement value) => new(value); -#if SUPPORTS_JSON_NODES /// /// Converts a to an instance. /// /// The value to convert /// An instance. public static implicit operator OpenIddictParameter(JsonNode? value) => new(value); -#endif /// /// Converts a long integer to an instance. @@ -1311,7 +1272,6 @@ public readonly struct OpenIddictParameter : IEquatable JsonElement value => IsEmptyJsonElement(value), -#if SUPPORTS_JSON_NODES JsonArray value => value.Count is 0, JsonObject value => value.Count is 0, @@ -1323,7 +1283,7 @@ public readonly struct OpenIddictParameter : IEquatable JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element => IsEmptyJsonElement(element), -#endif + _ => false }; diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs index e6befbf8..08ba62e3 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs @@ -8,13 +8,10 @@ using System.Collections.Specialized; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using Microsoft.Extensions.Primitives; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Abstractions; /// @@ -47,7 +44,6 @@ public class OpenIddictRequest : OpenIddictMessage { } -#if SUPPORTS_JSON_NODES /// /// Initializes a new OpenIddict request. /// @@ -57,7 +53,6 @@ public class OpenIddictRequest : OpenIddictMessage : base(parameters) { } -#endif /// /// Initializes a new OpenIddict request. diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs index 70431cc2..6a27bad4 100644 --- a/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs +++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictResponse.cs @@ -7,13 +7,10 @@ using System.Collections.Specialized; using System.Diagnostics; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using Microsoft.Extensions.Primitives; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Abstractions; /// @@ -46,7 +43,6 @@ public class OpenIddictResponse : OpenIddictMessage { } -#if SUPPORTS_JSON_NODES /// /// Initializes a new OpenIddict response. /// @@ -56,7 +52,6 @@ public class OpenIddictResponse : OpenIddictMessage : base(parameters) { } -#endif /// /// Initializes a new OpenIddict response. diff --git a/src/OpenIddict.Client.AspNetCore/OpenIddict.Client.AspNetCore.csproj b/src/OpenIddict.Client.AspNetCore/OpenIddict.Client.AspNetCore.csproj index 03f55a73..2ab3bac0 100644 --- a/src/OpenIddict.Client.AspNetCore/OpenIddict.Client.AspNetCore.csproj +++ b/src/OpenIddict.Client.AspNetCore/OpenIddict.Client.AspNetCore.csproj @@ -13,15 +13,11 @@ - + - + diff --git a/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs b/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs index 3af8188c..cc84deb2 100644 --- a/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs +++ b/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs @@ -11,6 +11,7 @@ using System.Diagnostics; using System.Security.Claims; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http.Extensions; @@ -21,10 +22,6 @@ using Microsoft.Net.Http.Headers; using OpenIddict.Extensions; using Properties = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Properties; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Client.AspNetCore; [EditorBrowsable(EditorBrowsableState.Never)] @@ -625,15 +622,13 @@ public static partial class OpenIddictClientAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), -#if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), -#endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } @@ -948,15 +943,13 @@ public static partial class OpenIddictClientAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), -#if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), -#endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } diff --git a/src/OpenIddict.Client.DataProtection/OpenIddict.Client.DataProtection.csproj b/src/OpenIddict.Client.DataProtection/OpenIddict.Client.DataProtection.csproj index 992dcebb..e83934fb 100644 --- a/src/OpenIddict.Client.DataProtection/OpenIddict.Client.DataProtection.csproj +++ b/src/OpenIddict.Client.DataProtection/OpenIddict.Client.DataProtection.csproj @@ -17,15 +17,12 @@ - + + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddict.Client.SystemIntegration.csproj b/src/OpenIddict.Client.SystemIntegration/OpenIddict.Client.SystemIntegration.csproj index 3dc2e53d..4b6dd407 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddict.Client.SystemIntegration.csproj +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddict.Client.SystemIntegration.csproj @@ -36,23 +36,15 @@ - + - + - + diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs index 247beddf..e8301f3c 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs @@ -17,10 +17,6 @@ using Microsoft.IdentityModel.Tokens; using OpenIddict.Extensions; using static OpenIddict.Client.SystemIntegration.OpenIddictClientSystemIntegrationAuthenticationMode; -#if !SUPPORTS_HOST_ENVIRONMENT -using IHostEnvironment = Microsoft.Extensions.Hosting.IHostingEnvironment; -#endif - namespace OpenIddict.Client.SystemIntegration; /// diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationExtensions.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationExtensions.cs index 0e4981af..a64bdb38 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationExtensions.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationExtensions.cs @@ -117,11 +117,12 @@ public static class OpenIddictClientSystemIntegrationExtensions // Note: the order used here is not important, as the actual order is set in the options. builder.Services.TryAdd(OpenIddictClientSystemIntegrationHandlers.DefaultHandlers.Select(descriptor => descriptor.ServiceDescriptor)); - // Register the option initializer and the background service used by the OpenIddict client system integration services. - // Note: TryAddEnumerable() is used here to ensure the initializers and the background service are only registered once. - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); + // Register the background services used by the OpenIddict client system integration services. + builder.Services.AddHostedService(); + builder.Services.AddHostedService(); + // Register the option initializer used by the OpenIddict client system integration services. + // Note: TryAddEnumerable() is used here to ensure the initializers are only registered once. builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< IConfigureOptions, OpenIddictClientSystemIntegrationConfiguration>()); diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs index a77e63ab..ee71bd28 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs @@ -137,7 +137,6 @@ public static partial class OpenIddictClientSystemIntegrationHandlers using var session = CreateASWebAuthenticationSession(); -#if SUPPORTS_PRESENTATION_CONTEXT_PROVIDER // On iOS 13.0 and higher, a presentation context provider returning the UI window to // which the Safari web view will be attached MUST be provided (otherwise, a code 2 // error is returned by ASWebAuthenticationSession). To avoid that, a default provider @@ -149,7 +148,7 @@ public static partial class OpenIddictClientSystemIntegrationHandlers GetCurrentUIWindow() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0447))); #pragma warning restore CA1416 } -#endif + using var registration = context.CancellationToken.Register( static state => ((ASWebAuthenticationSession) state!).Cancel(), session); diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs index 3b978e65..47ef9ee7 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs @@ -137,7 +137,6 @@ public static partial class OpenIddictClientSystemIntegrationHandlers using var session = CreateASWebAuthenticationSession(); -#if SUPPORTS_PRESENTATION_CONTEXT_PROVIDER // On iOS 13.0 and higher, a presentation context provider returning the UI window to // which the Safari web view will be attached MUST be provided (otherwise, a code 2 // error is returned by ASWebAuthenticationSession). To avoid that, a default provider @@ -149,7 +148,7 @@ public static partial class OpenIddictClientSystemIntegrationHandlers GetCurrentUIWindow() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0447))); #pragma warning restore CA1416 } -#endif + using var registration = context.CancellationToken.Register( static state => ((ASWebAuthenticationSession) state!).Cancel(), session); diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs index 020d98a8..48141587 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs @@ -19,10 +19,6 @@ using Microsoft.Net.Http.Headers; using OpenIddict.Extensions; using static OpenIddict.Client.SystemIntegration.OpenIddictClientSystemIntegrationConstants; -#if !SUPPORTS_HOST_APPLICATION_LIFETIME -using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime; -#endif - namespace OpenIddict.Client.SystemIntegration; [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHelpers.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHelpers.cs index 770baed3..242b5f72 100644 --- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHelpers.cs +++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHelpers.cs @@ -251,7 +251,7 @@ public static class OpenIddictClientSystemIntegrationHelpers out uint ReturnLength); } -#if SUPPORTS_PRESENTATION_CONTEXT_PROVIDER +#if SUPPORTS_APPKIT || SUPPORTS_UIKIT /// /// Gets a reference to the current . /// diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddict.Client.SystemNetHttp.csproj b/src/OpenIddict.Client.SystemNetHttp/OpenIddict.Client.SystemNetHttp.csproj index 16f9ae41..968b12e7 100644 --- a/src/OpenIddict.Client.SystemNetHttp/OpenIddict.Client.SystemNetHttp.csproj +++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddict.Client.SystemNetHttp.csproj @@ -22,28 +22,11 @@ - - - - - - + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> - + diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs index 781f3317..be289c8b 100644 --- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs +++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs @@ -120,11 +120,8 @@ public sealed class OpenIddictClientSystemNetHttpConfiguration : IConfigureOptio options.HttpMessageHandlerBuilderActions.Add(builder => { -#if SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER var options = builder.Services.GetRequiredService>(); -#else - var options = _provider.GetRequiredService>(); -#endif + // If applicable, add the handler responsible for replaying failed HTTP requests. // // Note: on .NET 8.0 and higher, the HTTP error policy is always set diff --git a/src/OpenIddict.Client/OpenIddictClientBuilder.cs b/src/OpenIddict.Client/OpenIddictClientBuilder.cs index b46a4468..dc9054d5 100644 --- a/src/OpenIddict.Client/OpenIddictClientBuilder.cs +++ b/src/OpenIddict.Client/OpenIddictClientBuilder.cs @@ -217,11 +217,10 @@ public sealed class OpenIddictClientBuilder Services.AddOptions().Configure((options, provider) => { -#if SUPPORTS_TIME_PROVIDER - var now = (options.TimeProvider ?? provider.GetService())?.GetUtcNow() ?? DateTimeOffset.UtcNow; -#else - var now = DateTimeOffset.UtcNow; -#endif + // Important: the time provider might not be set yet when this configuration delegate is called. + // In that case, resolve the provider from the service provider or use the default time provider. + var now = (options.TimeProvider ?? provider.GetService() ?? TimeProvider.System).GetUtcNow(); + using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); @@ -634,11 +633,10 @@ public sealed class OpenIddictClientBuilder Services.AddOptions().Configure((options, provider) => { -#if SUPPORTS_TIME_PROVIDER - var now = (options.TimeProvider ?? provider.GetService())?.GetUtcNow() ?? DateTimeOffset.UtcNow; -#else - var now = DateTimeOffset.UtcNow; -#endif + // Important: the time provider might not be set yet when this configuration delegate is called. + // In that case, resolve the provider from the service provider or use the default time provider. + var now = (options.TimeProvider ?? provider.GetService() ?? TimeProvider.System).GetUtcNow(); + using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); diff --git a/src/OpenIddict.Client/OpenIddictClientConfiguration.cs b/src/OpenIddict.Client/OpenIddictClientConfiguration.cs index fb573299..a40481ac 100644 --- a/src/OpenIddict.Client/OpenIddictClientConfiguration.cs +++ b/src/OpenIddict.Client/OpenIddictClientConfiguration.cs @@ -51,9 +51,7 @@ public sealed class OpenIddictClientConfiguration : IPostConfigureOptions() ?? TimeProvider.System; -#endif foreach (var registration in options.Registrations) { @@ -230,12 +228,7 @@ public sealed class OpenIddictClientConfiguration : IPostConfigureOptions left.Order.CompareTo(right.Order)); - var now = ( -#if SUPPORTS_TIME_PROVIDER - options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow - ).LocalDateTime; + var now = options.TimeProvider.GetUtcNow().LocalDateTime; // Sort the encryption and signing credentials. options.EncryptionCredentials.Sort((left, right) => Compare(left.Key, right.Key, now)); diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Introspection.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Introspection.cs index 77524e1b..f5f0c2c1 100644 --- a/src/OpenIddict.Client/OpenIddictClientHandlers.Introspection.cs +++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Introspection.cs @@ -295,11 +295,7 @@ public static partial class OpenIddictClientHandlers if (long.TryParse((string?) context.Response[Claims.ExpiresAt], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) && DateTimeOffset.FromUnixTimeSeconds(value) is DateTimeOffset date && - date.Add(context.Registration.TokenValidationParameters.ClockSkew) < ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)) + date.Add(context.Registration.TokenValidationParameters.ClockSkew) < context.Options.TimeProvider.GetUtcNow()) { context.Reject( error: Errors.ServerError, diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs index 11ac46d3..b008be37 100644 --- a/src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs +++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs @@ -679,12 +679,8 @@ public static partial class OpenIddictClientHandlers Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); - var date = context.Principal.GetExpirationDate(); - if (date.HasValue && date.Value.Add(context.TokenValidationParameters.ClockSkew) < ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)) + if (context.Principal.GetExpirationDate() is DateTimeOffset date && + date + context.TokenValidationParameters.ClockSkew < context.Options.TimeProvider.GetUtcNow()) { context.Reject( error: Errors.InvalidToken, diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.cs index 28318145..00d1e606 100644 --- a/src/OpenIddict.Client/OpenIddictClientHandlers.cs +++ b/src/OpenIddict.Client/OpenIddictClientHandlers.cs @@ -1528,11 +1528,8 @@ public static partial class OpenIddictClientHandlers context.FrontchannelAccessTokenExpirationDate = context.EndpointType switch { OpenIddictClientEndpointType.Redirection when context.ExtractFrontchannelAccessToken - => (long?) context.Request[Parameters.ExpiresIn] is long value ? ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow).AddSeconds(value) : null, + => (long?) context.Request[Parameters.ExpiresIn] is long value ? + context.Options.TimeProvider.GetUtcNow().AddSeconds(value) : null, _ => null }; @@ -2581,11 +2578,7 @@ public static partial class OpenIddictClientHandlers nameType: Claims.Name, roleType: Claims.Role)); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Options.ClientAssertionLifetime; if (lifetime.HasValue) @@ -2974,11 +2967,7 @@ public static partial class OpenIddictClientHandlers context.BackchannelAccessTokenExpirationDate = context.ExtractBackchannelAccessToken && context.TokenResponse.ExpiresIn is long value - ? ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow).AddSeconds(value) + ? context.Options.TimeProvider.GetUtcNow().AddSeconds(value) : null; context.BackchannelIdentityToken = context.ExtractBackchannelIdentityToken ? @@ -5336,11 +5325,7 @@ public static partial class OpenIddictClientHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Principal.GetStateTokenLifetime() ?? context.Options.StateTokenLifetime; if (lifetime.HasValue) @@ -6027,11 +6012,7 @@ public static partial class OpenIddictClientHandlers nameType: Claims.Name, roleType: Claims.Role)); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Options.ClientAssertionLifetime; if (lifetime.HasValue) @@ -7098,11 +7079,7 @@ public static partial class OpenIddictClientHandlers nameType: Claims.Name, roleType: Claims.Role)); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Options.ClientAssertionLifetime; if (lifetime.HasValue) @@ -7773,11 +7750,7 @@ public static partial class OpenIddictClientHandlers nameType: Claims.Name, roleType: Claims.Role)); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Options.ClientAssertionLifetime; if (lifetime.HasValue) @@ -8428,11 +8401,7 @@ public static partial class OpenIddictClientHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); var lifetime = context.Principal.GetStateTokenLifetime() ?? context.Options.StateTokenLifetime; if (lifetime.HasValue) diff --git a/src/OpenIddict.Client/OpenIddictClientOptions.cs b/src/OpenIddict.Client/OpenIddictClientOptions.cs index 580026c7..8b66b2c2 100644 --- a/src/OpenIddict.Client/OpenIddictClientOptions.cs +++ b/src/OpenIddict.Client/OpenIddictClientOptions.cs @@ -189,10 +189,13 @@ public sealed class OpenIddictClientOptions [EditorBrowsable(EditorBrowsableState.Advanced)] public HashSet ResponseTypes { get; } = new(StringComparer.Ordinal); -#if SUPPORTS_TIME_PROVIDER /// /// Gets or sets the time provider. /// - public TimeProvider? TimeProvider { get; set; } -#endif + /// + /// Note: if this property is not explicitly set, the time provider is + /// automatically resolved from the dependency injection container. + /// If no service can be found, is used. + /// + public TimeProvider TimeProvider { get; set; } = default!; } diff --git a/src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs b/src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs index 4b085e04..6288ba30 100644 --- a/src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs +++ b/src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs @@ -232,11 +232,7 @@ public class OpenIddictAuthorizationManager : IOpenIddictAuthori var descriptor = new OpenIddictAuthorizationDescriptor { ApplicationId = client, - CreationDate = -#if SUPPORTS_TIME_PROVIDER - Options.CurrentValue.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow, + CreationDate = Options.CurrentValue.TimeProvider.GetUtcNow(), Principal = principal, Status = Statuses.Valid, Subject = subject, diff --git a/src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs b/src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs index 54529e75..f444a38d 100644 --- a/src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs +++ b/src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs @@ -1011,11 +1011,7 @@ public class OpenIddictTokenManager : IOpenIddictTokenManager where TTok // the first time the token is redeemed. In this case, attach the current date. if (await Store.GetRedemptionDateAsync(token, cancellationToken) is null) { - await Store.SetRedemptionDateAsync(token, -#if SUPPORTS_TIME_PROVIDER - Options.CurrentValue.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow, cancellationToken); + await Store.SetRedemptionDateAsync(token, Options.CurrentValue.TimeProvider.GetUtcNow(), cancellationToken); } await Store.SetStatusAsync(token, Statuses.Redeemed, cancellationToken); diff --git a/src/OpenIddict.Core/OpenIddictCoreConfiguration.cs b/src/OpenIddict.Core/OpenIddictCoreConfiguration.cs index 2c655e49..c1e2d5a1 100644 --- a/src/OpenIddict.Core/OpenIddictCoreConfiguration.cs +++ b/src/OpenIddict.Core/OpenIddictCoreConfiguration.cs @@ -26,8 +26,6 @@ public class OpenIddictCoreConfiguration : IPostConfigureOptions public void PostConfigure(string? name, OpenIddictCoreOptions options) { -#if SUPPORTS_TIME_PROVIDER options.TimeProvider ??= _provider.GetService() ?? TimeProvider.System; -#endif } } diff --git a/src/OpenIddict.Core/OpenIddictCoreOptions.cs b/src/OpenIddict.Core/OpenIddictCoreOptions.cs index 0adda6d8..3d6aad1e 100644 --- a/src/OpenIddict.Core/OpenIddictCoreOptions.cs +++ b/src/OpenIddict.Core/OpenIddictCoreOptions.cs @@ -60,10 +60,13 @@ public sealed class OpenIddictCoreOptions /// public int EntityCacheLimit { get; set; } = 250; -#if SUPPORTS_TIME_PROVIDER /// /// Gets or sets the time provider. /// - public TimeProvider? TimeProvider { get; set; } -#endif + /// + /// Note: if this property is not explicitly set, the time provider is + /// automatically resolved from the dependency injection container. + /// If no service can be found, is used. + /// + public TimeProvider TimeProvider { get; set; } = default!; } diff --git a/src/OpenIddict.MongoDb.Models/OpenIddict.MongoDb.Models.csproj b/src/OpenIddict.MongoDb.Models/OpenIddict.MongoDb.Models.csproj index 56a2b8bc..b7d3b82d 100644 --- a/src/OpenIddict.MongoDb.Models/OpenIddict.MongoDb.Models.csproj +++ b/src/OpenIddict.MongoDb.Models/OpenIddict.MongoDb.Models.csproj @@ -21,8 +21,7 @@ + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs b/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs index 241883e8..90ff5e15 100644 --- a/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs +++ b/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs @@ -56,8 +56,6 @@ public sealed class OpenIddictQuartzConfiguration : IConfigureOptions public void PostConfigure(string? name, OpenIddictQuartzOptions options) { -#if SUPPORTS_TIME_PROVIDER options.TimeProvider ??= _provider.GetService() ?? TimeProvider.System; -#endif } } diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs b/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs index 99e2e51c..6fab9690 100644 --- a/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs +++ b/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs @@ -72,11 +72,7 @@ public sealed class OpenIddictQuartzJob : IJob UnscheduleFiringTrigger = true }; - var threshold = ( -#if SUPPORTS_TIME_PROVIDER - _options.CurrentValue.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow) - _options.CurrentValue.MinimumTokenLifespan; + var threshold = _options.CurrentValue.TimeProvider.GetUtcNow() - _options.CurrentValue.MinimumTokenLifespan; try { @@ -121,11 +117,7 @@ public sealed class OpenIddictQuartzJob : IJob UnscheduleFiringTrigger = true }; - var threshold = ( -#if SUPPORTS_TIME_PROVIDER - _options.CurrentValue.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow) - _options.CurrentValue.MinimumAuthorizationLifespan; + var threshold = _options.CurrentValue.TimeProvider.GetUtcNow() - _options.CurrentValue.MinimumAuthorizationLifespan; try { diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs b/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs index 8cc17659..1a77ba31 100644 --- a/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs +++ b/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs @@ -39,10 +39,13 @@ public sealed class OpenIddictQuartzOptions /// public TimeSpan MinimumTokenLifespan { get; set; } = TimeSpan.FromDays(14); -#if SUPPORTS_TIME_PROVIDER /// /// Gets or sets the time provider. /// - public TimeProvider? TimeProvider { get; set; } -#endif + /// + /// Note: if this property is not explicitly set, the time provider is + /// automatically resolved from the dependency injection container. + /// If no service can be found, is used. + /// + public TimeProvider TimeProvider { get; set; } = default!; } diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddict.Server.AspNetCore.csproj b/src/OpenIddict.Server.AspNetCore/OpenIddict.Server.AspNetCore.csproj index f6f86253..d42ae86b 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddict.Server.AspNetCore.csproj +++ b/src/OpenIddict.Server.AspNetCore/OpenIddict.Server.AspNetCore.csproj @@ -13,15 +13,12 @@ - + + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs index 32b60cfa..070a6c92 100644 --- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs +++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs @@ -10,6 +10,7 @@ using System.Diagnostics; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http.Extensions; @@ -19,10 +20,6 @@ using Microsoft.Net.Http.Headers; using OpenIddict.Extensions; using Properties = OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreConstants.Properties; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Server.AspNetCore; [EditorBrowsable(EditorBrowsableState.Never)] @@ -260,15 +257,13 @@ public static partial class OpenIddictServerAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), -#if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), -#endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } @@ -359,15 +354,13 @@ public static partial class OpenIddictServerAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), -#if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), -#endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } @@ -420,15 +413,13 @@ public static partial class OpenIddictServerAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), -#if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), -#endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } diff --git a/src/OpenIddict.Server.DataProtection/OpenIddict.Server.DataProtection.csproj b/src/OpenIddict.Server.DataProtection/OpenIddict.Server.DataProtection.csproj index e7aabb11..94546789 100644 --- a/src/OpenIddict.Server.DataProtection/OpenIddict.Server.DataProtection.csproj +++ b/src/OpenIddict.Server.DataProtection/OpenIddict.Server.DataProtection.csproj @@ -18,14 +18,12 @@ + Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp' "> + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Server/OpenIddictServerBuilder.cs b/src/OpenIddict.Server/OpenIddictServerBuilder.cs index 94c1430a..1b6109c9 100644 --- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs +++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs @@ -226,11 +226,10 @@ public sealed class OpenIddictServerBuilder Services.AddOptions().Configure((options, provider) => { -#if SUPPORTS_TIME_PROVIDER - var now = (options.TimeProvider ?? provider.GetService())?.GetUtcNow() ?? DateTimeOffset.UtcNow; -#else - var now = DateTimeOffset.UtcNow; -#endif + // Important: the time provider might not be set yet when this configuration delegate is called. + // In that case, resolve the provider from the service provider or use the default time provider. + var now = (options.TimeProvider ?? provider.GetService() ?? TimeProvider.System).GetUtcNow(); + using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); @@ -643,11 +642,10 @@ public sealed class OpenIddictServerBuilder Services.AddOptions().Configure((options, provider) => { -#if SUPPORTS_TIME_PROVIDER - var now = (options.TimeProvider ?? provider.GetService())?.GetUtcNow() ?? DateTimeOffset.UtcNow; -#else - var now = DateTimeOffset.UtcNow; -#endif + // Important: the time provider might not be set yet when this configuration delegate is called. + // In that case, resolve the provider from the service provider or use the default time provider. + var now = (options.TimeProvider ?? provider.GetService() ?? TimeProvider.System).GetUtcNow(); + using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs index de9c9300..778502bd 100644 --- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs +++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs @@ -38,9 +38,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions() ?? TimeProvider.System; -#endif // Explicitly disable all the features that are implicitly excluded when the degraded mode is active. if (options.EnableDegradedMode) @@ -205,13 +203,7 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions credentials.Key is X509SecurityKey x509SecurityKey && diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs index eda2e55c..4df45238 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs @@ -913,12 +913,8 @@ public static partial class OpenIddictServerHandlers Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); - var date = context.Principal.GetExpirationDate(); - if (date.HasValue && date.Value.Add(context.TokenValidationParameters.ClockSkew) < ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)) + if (context.Principal.GetExpirationDate() is DateTimeOffset date && + date + context.TokenValidationParameters.ClockSkew < context.Options.TimeProvider.GetUtcNow()) { context.Reject( error: context.Principal.GetTokenType() switch @@ -1120,11 +1116,8 @@ public static partial class OpenIddictServerHandlers } var date = await _tokenManager.GetRedemptionDateAsync(token); - if (date is null || ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow) < date + context.Options.RefreshTokenReuseLeeway) + if (date is null || context.Options.TimeProvider.GetUtcNow() < + date + context.Options.RefreshTokenReuseLeeway) { return true; } diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs index 170c1bb2..d8c0ec95 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.cs @@ -3004,11 +3004,7 @@ public static partial class OpenIddictServerHandlers var descriptor = new OpenIddictAuthorizationDescriptor { - CreationDate = -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow, + CreationDate = context.Options.TimeProvider.GetUtcNow(), Principal = context.Principal, Status = Statuses.Valid, Subject = context.Principal.GetClaim(Claims.Subject), @@ -3148,11 +3144,7 @@ public static partial class OpenIddictServerHandlers claim.Properties.Remove(Properties.Destinations); } - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetAccessTokenLifetime(); @@ -3276,11 +3268,7 @@ public static partial class OpenIddictServerHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetAuthorizationCodeLifetime(); @@ -3406,11 +3394,7 @@ public static partial class OpenIddictServerHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetDeviceCodeLifetime(); @@ -3523,11 +3507,7 @@ public static partial class OpenIddictServerHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetRequestTokenLifetime(); @@ -3655,11 +3635,7 @@ public static partial class OpenIddictServerHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // When sliding expiration is disabled, the expiration date of generated refresh tokens is fixed // and must exactly match the expiration date of the refresh token used in the token request. @@ -3810,11 +3786,7 @@ public static partial class OpenIddictServerHandlers claim.Properties.Remove(Properties.Destinations); } - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetIdentityTokenLifetime(); @@ -3941,11 +3913,7 @@ public static partial class OpenIddictServerHandlers return true; }); - principal.SetCreationDate( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow); + principal.SetCreationDate(context.Options.TimeProvider.GetUtcNow()); // If a specific token lifetime was attached to the principal, prefer it over any other value. var lifetime = context.Principal.GetUserCodeLifetime(); @@ -4774,18 +4742,11 @@ public static partial class OpenIddictServerHandlers if (context.AccessTokenPrincipal is not null) { // If an expiration date was set on the access token principal, return it to the client application. - if (context.AccessTokenPrincipal.GetExpirationDate() - is DateTimeOffset date && date > ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)) + if (context.AccessTokenPrincipal.GetExpirationDate() is DateTimeOffset date && + date > context.Options.TimeProvider.GetUtcNow()) { - context.Response.ExpiresIn = (long) ((date - ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)).TotalSeconds + .5); + context.Response.ExpiresIn = (long) + ((date - context.Options.TimeProvider.GetUtcNow()).TotalSeconds + .5); } // If the granted access token scopes differ from the requested scopes, return the granted scopes @@ -4858,16 +4819,8 @@ public static partial class OpenIddictServerHandlers { // If an expiration date was set on the device code or user // code principal, return it to the client application. - DateTimeOffset date when date > ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow) - => (long) ((date - ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)).TotalSeconds + .5), + DateTimeOffset date when date > context.Options.TimeProvider.GetUtcNow() + => (long) ((date - context.Options.TimeProvider.GetUtcNow()).TotalSeconds + .5), // Otherwise, return an arbitrary value, as the "expires_in" // parameter is required in device authorization responses. @@ -4881,16 +4834,8 @@ public static partial class OpenIddictServerHandlers { // If an expiration date was set on the pushed authorization // request token principal, return it to the client application. - DateTimeOffset date when date > ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow) - => (long) ((date - ( -#if SUPPORTS_TIME_PROVIDER - context.Options.TimeProvider?.GetUtcNow() ?? -#endif - DateTimeOffset.UtcNow)).TotalSeconds + .5), + DateTimeOffset date when date > context.Options.TimeProvider.GetUtcNow() + => (long) ((date - context.Options.TimeProvider.GetUtcNow()).TotalSeconds + .5), // Otherwise, return an arbitrary value, as the "expires_in" // parameter is required in pushed authorization responses. diff --git a/src/OpenIddict.Server/OpenIddictServerOptions.cs b/src/OpenIddict.Server/OpenIddictServerOptions.cs index 340584b5..28c3f802 100644 --- a/src/OpenIddict.Server/OpenIddictServerOptions.cs +++ b/src/OpenIddict.Server/OpenIddictServerOptions.cs @@ -510,10 +510,13 @@ public sealed class OpenIddictServerOptions /// public bool UseReferenceRefreshTokens { get; set; } -#if SUPPORTS_TIME_PROVIDER /// /// Gets or sets the time provider. /// - public TimeProvider? TimeProvider { get; set; } -#endif + /// + /// Note: if this property is not explicitly set, the time provider is + /// automatically resolved from the dependency injection container. + /// If no service can be found, is used. + /// + public TimeProvider TimeProvider { get; set; } = default!; } diff --git a/src/OpenIddict.Validation.AspNetCore/OpenIddict.Validation.AspNetCore.csproj b/src/OpenIddict.Validation.AspNetCore/OpenIddict.Validation.AspNetCore.csproj index 21ebdbb0..550868ff 100644 --- a/src/OpenIddict.Validation.AspNetCore/OpenIddict.Validation.AspNetCore.csproj +++ b/src/OpenIddict.Validation.AspNetCore/OpenIddict.Validation.AspNetCore.csproj @@ -13,15 +13,12 @@ - + + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs b/src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs index be88fe55..b5232854 100644 --- a/src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs +++ b/src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs @@ -9,6 +9,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Logging; @@ -17,10 +18,6 @@ using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Properties = OpenIddict.Validation.AspNetCore.OpenIddictValidationAspNetCoreConstants.Properties; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Validation.AspNetCore; [EditorBrowsable(EditorBrowsableState.Never)] @@ -371,15 +368,13 @@ public static partial class OpenIddictValidationAspNetCoreHandlers { OpenIddictParameter value => value, JsonElement value => new OpenIddictParameter(value), + JsonNode value => new OpenIddictParameter(value), bool value => new OpenIddictParameter(value), int value => new OpenIddictParameter(value), long value => new OpenIddictParameter(value), string value => new OpenIddictParameter(value), string[] value => new OpenIddictParameter(value), - #if SUPPORTS_JSON_NODES - JsonNode value => new OpenIddictParameter(value), - #endif _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0115)) }; } diff --git a/src/OpenIddict.Validation.DataProtection/OpenIddict.Validation.DataProtection.csproj b/src/OpenIddict.Validation.DataProtection/OpenIddict.Validation.DataProtection.csproj index 916bb234..e4c96818 100644 --- a/src/OpenIddict.Validation.DataProtection/OpenIddict.Validation.DataProtection.csproj +++ b/src/OpenIddict.Validation.DataProtection/OpenIddict.Validation.DataProtection.csproj @@ -17,15 +17,12 @@ - + + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddict.Validation.SystemNetHttp.csproj b/src/OpenIddict.Validation.SystemNetHttp/OpenIddict.Validation.SystemNetHttp.csproj index cdb49383..3b2fcfcb 100644 --- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddict.Validation.SystemNetHttp.csproj +++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddict.Validation.SystemNetHttp.csproj @@ -22,28 +22,11 @@ - - - - - - + Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' Or '$(TargetFrameworkIdentifier)' == '.NETStandard' "> - + diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs index 6ce4be8d..39d73cb1 100644 --- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs +++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs @@ -108,11 +108,8 @@ public sealed class OpenIddictValidationSystemNetHttpConfiguration : IConfigureO options.HttpMessageHandlerBuilderActions.Add(builder => { -#if SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER var options = builder.Services.GetRequiredService>(); -#else - var options = _provider.GetRequiredService>(); -#endif + // If applicable, add the handler responsible for replaying failed HTTP requests. // // Note: on .NET 8.0 and higher, the HTTP error policy is always set diff --git a/src/OpenIddict.Validation/OpenIddictValidationConfiguration.cs b/src/OpenIddict.Validation/OpenIddictValidationConfiguration.cs index 50697788..54ed45d4 100644 --- a/src/OpenIddict.Validation/OpenIddictValidationConfiguration.cs +++ b/src/OpenIddict.Validation/OpenIddictValidationConfiguration.cs @@ -39,9 +39,7 @@ public sealed class OpenIddictValidationConfiguration : IPostConfigureOptions() ?? TimeProvider.System; -#endif if (options.JsonWebTokenHandler is null) { @@ -100,13 +98,7 @@ public sealed class OpenIddictValidationConfiguration : IPostConfigureOptions /// Gets or sets the time provider. /// - public TimeProvider? TimeProvider { get; set; } -#endif + /// + /// Note: if this property is not explicitly set, the time provider is + /// automatically resolved from the dependency injection container. + /// If no service can be found, is used. + /// + public TimeProvider TimeProvider { get; set; } = default!; } diff --git a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictConverterTests.cs b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictConverterTests.cs index 056a96e7..f4b47866 100644 --- a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictConverterTests.cs +++ b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictConverterTests.cs @@ -6,11 +6,8 @@ using System.Text; using System.Text.Json; -using Xunit; - -#if SUPPORTS_JSON_NODES using System.Text.Json.Nodes; -#endif +using Xunit; namespace OpenIddict.Abstractions.Tests.Primitives; @@ -133,11 +130,8 @@ public class OpenIddictConverterTests Assert.Null((long?) message.GetParameter("long")); Assert.Equal(JsonValueKind.Null, ((JsonElement) message.GetParameter("array")).ValueKind); Assert.Equal(JsonValueKind.Null, ((JsonElement) message.GetParameter("object")).ValueKind); - -#if SUPPORTS_JSON_NODES Assert.Null((JsonNode?) message.GetParameter("array")); Assert.Null((JsonNode?) message.GetParameter("object")); -#endif } [Fact] @@ -158,11 +152,8 @@ public class OpenIddictConverterTests Assert.Empty(((string?) message.GetParameter("string"))!); Assert.NotNull((JsonElement?) message.GetParameter("array")); Assert.NotNull((JsonElement?) message.GetParameter("object")); - -#if SUPPORTS_JSON_NODES Assert.NotNull((JsonNode?) message.GetParameter("array")); Assert.NotNull((JsonNode?) message.GetParameter("object")); -#endif } [Fact] @@ -228,10 +219,7 @@ public class OpenIddictConverterTests message.AddParameter("bool", new OpenIddictParameter((bool?) null)); message.AddParameter("long", new OpenIddictParameter((long?) null)); message.AddParameter("element", new OpenIddictParameter(default(JsonElement))); - -#if SUPPORTS_JSON_NODES message.AddParameter("node", new OpenIddictParameter((JsonNode?) null)); -#endif // Act converter.Write(writer, value: message, options: null!); @@ -240,11 +228,7 @@ public class OpenIddictConverterTests writer.Flush(); stream.Seek(0L, SeekOrigin.Begin); -#if SUPPORTS_JSON_NODES Assert.Equal(@"{""string"":null,""bool"":null,""long"":null,""element"":null,""node"":null}", reader.ReadToEnd()); -#else - Assert.Equal(@"{""string"":null,""bool"":null,""long"":null,""element"":null}", reader.ReadToEnd()); -#endif } [Fact] @@ -260,12 +244,9 @@ public class OpenIddictConverterTests message.AddParameter("string", new OpenIddictParameter(string.Empty)); message.AddParameter("element_array", new OpenIddictParameter(JsonSerializer.Deserialize("[]"))); message.AddParameter("element_object", new OpenIddictParameter(JsonSerializer.Deserialize("{}"))); - -#if SUPPORTS_JSON_NODES message.AddParameter("node_array", new OpenIddictParameter(new JsonArray())); message.AddParameter("node_object", new OpenIddictParameter(new JsonObject())); message.AddParameter("node_value", new OpenIddictParameter(JsonValue.Create(new { }))); -#endif // Act converter.Write(writer, value: message, options: null!); @@ -274,11 +255,7 @@ public class OpenIddictConverterTests writer.Flush(); stream.Seek(0L, SeekOrigin.Begin); -#if SUPPORTS_JSON_NODES Assert.Equal(@"{""string"":"""",""element_array"":[],""element_object"":{},""node_array"":[],""node_object"":{},""node_value"":{}}", reader.ReadToEnd()); -#else - Assert.Equal(@"{""string"":"""",""element_array"":[],""element_object"":{}}", reader.ReadToEnd()); -#endif } [Fact] diff --git a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictMessageTests.cs b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictMessageTests.cs index e6e722fe..663b7e2d 100644 --- a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictMessageTests.cs +++ b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictMessageTests.cs @@ -7,11 +7,8 @@ using System.Text; using System.Text.Encodings.Web; using System.Text.Json; -using Xunit; - -#if SUPPORTS_JSON_NODES using System.Text.Json.Nodes; -#endif +using Xunit; namespace OpenIddict.Abstractions.Tests.Primitives; @@ -188,24 +185,18 @@ public class OpenIddictMessageTests message.AddParameter("object", JsonSerializer.Deserialize("{}")); message.AddParameter("value", JsonSerializer.Deserialize( @"{""property"":""""}").GetProperty("property").GetString()); - -#if SUPPORTS_JSON_NODES message.AddParameter("node_array", new JsonArray()); message.AddParameter("node_object", new JsonObject()); message.AddParameter("node_value", JsonValue.Create(string.Empty)); -#endif // Assert Assert.Empty(((string?) message.GetParameter("string"))!); Assert.NotNull((JsonElement?) message.GetParameter("array")); Assert.NotNull((JsonElement?) message.GetParameter("object")); Assert.NotNull((JsonElement?) message.GetParameter("value")); - -#if SUPPORTS_JSON_NODES Assert.NotNull((JsonNode?) message.GetParameter("node_array")); Assert.NotNull((JsonNode?) message.GetParameter("node_object")); Assert.NotNull((JsonNode?) message.GetParameter("node_value")); -#endif } [Theory] @@ -399,12 +390,9 @@ public class OpenIddictMessageTests message.SetParameter("object", JsonSerializer.Deserialize("{}")); message.SetParameter("value", JsonSerializer.Deserialize( @"{""property"":""""}").GetProperty("property").GetString()); - -#if SUPPORTS_JSON_NODES message.SetParameter("node_array", new JsonArray()); message.SetParameter("node_object", new JsonObject()); message.SetParameter("node_value", JsonValue.Create(string.Empty)); -#endif // Assert Assert.Empty(message.GetParameters()); diff --git a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictParameterTests.cs b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictParameterTests.cs index 76c651a3..017606f5 100644 --- a/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictParameterTests.cs +++ b/test/OpenIddict.Abstractions.Tests/Primitives/OpenIddictParameterTests.cs @@ -6,11 +6,8 @@ using System.Text; using System.Text.Json; -using Xunit; - -#if SUPPORTS_JSON_NODES using System.Text.Json.Nodes; -#endif +using Xunit; namespace OpenIddict.Abstractions.Tests.Primitives; @@ -92,7 +89,6 @@ public class OpenIddictParameterTests Assert.Equal(1, parameter.Count); } -#if SUPPORTS_JSON_NODES [Fact] public void Count_ReturnsExpectedValueForJsonArrayNodes() { @@ -135,7 +131,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Equal(0, parameter.Count); } -#endif [Fact] public void Equals_ReturnsTrueWhenBothParametersAreNull() @@ -183,12 +178,10 @@ public class OpenIddictParameterTests Assert.False(new OpenIddictParameter(JsonSerializer.Deserialize("[]")) .Equals(new OpenIddictParameter(JsonSerializer.Deserialize("{}")))); -#if SUPPORTS_JSON_NODES Assert.False(new OpenIddictParameter(JsonValue.Create(true)).Equals(new OpenIddictParameter(JsonValue.Create("true")))); Assert.False(new OpenIddictParameter(JsonValue.Create("true")).Equals(new OpenIddictParameter(JsonValue.Create(true)))); Assert.False(new OpenIddictParameter(new JsonObject()).Equals(new OpenIddictParameter(new JsonArray()))); Assert.False(new OpenIddictParameter(new JsonArray()).Equals(new OpenIddictParameter(new JsonObject()))); -#endif } [Fact] @@ -216,16 +209,13 @@ public class OpenIddictParameterTests Assert.False(parameter.Equals(JsonSerializer.Deserialize("[3,2,1,0]"))); Assert.False(parameter.Equals(JsonSerializer.Deserialize("{}"))); -#if SUPPORTS_JSON_NODES Assert.True(parameter.Equals(new OpenIddictParameter(new JsonArray(0, 1, 2, 3)))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonArray()))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonArray(0, 1, 2)))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonArray(3, 2, 1, 0)))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonObject()))); -#endif } -#if SUPPORTS_JSON_NODES [Fact] public void Equals_UsesDeepEqualsForJsonArrayNodes() { @@ -245,7 +235,6 @@ public class OpenIddictParameterTests Assert.False(parameter.Equals(new OpenIddictParameter(new JsonArray(3, 2, 1, 0)))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonObject()))); } -#endif [Fact] public void Equals_UsesDeepEqualsForJsonObjectElements() @@ -260,7 +249,6 @@ public class OpenIddictParameterTests Assert.False(parameter.Equals(JsonSerializer.Deserialize(@"{""field"":[0,1,2]}"))); Assert.False(parameter.Equals(JsonSerializer.Deserialize(@"[]"))); -#if SUPPORTS_JSON_NODES Assert.True(parameter.Equals(new OpenIddictParameter(new JsonObject { ["field"] = new JsonArray(0, 1, 2, 3) @@ -285,10 +273,8 @@ public class OpenIddictParameterTests }))); Assert.False(parameter.Equals(new OpenIddictParameter(new JsonArray()))); -#endif } -#if SUPPORTS_JSON_NODES [Fact] public void Equals_UsesDeepEqualsForJsonObjectNodes() { @@ -338,7 +324,6 @@ public class OpenIddictParameterTests ["field"] = new[] { 0, 1, 2, 3 } }))); } -#endif [Fact] public void Equals_ComparesUnderlyingValuesForJsonValueElements() @@ -357,7 +342,6 @@ public class OpenIddictParameterTests @"{""field"":""Fabrikam""}").GetProperty("field")).Equals(new OpenIddictParameter("Contoso"))); } -#if SUPPORTS_JSON_NODES [Fact] public void Equals_ComparesUnderlyingValuesForJsonValueNodes() { @@ -381,7 +365,6 @@ public class OpenIddictParameterTests Assert.False(new OpenIddictParameter(JsonValue.Create(JsonSerializer.Deserialize( @"{""field"":""Fabrikam""}").GetProperty("field")))!.Equals(new OpenIddictParameter("Contoso"))); } -#endif [Fact] public void Equals_SupportsUndefinedJsonValueElements() @@ -393,7 +376,6 @@ public class OpenIddictParameterTests Assert.False(parameter.Equals(new OpenIddictParameter(default(JsonElement)))); } -#if SUPPORTS_JSON_NODES [Fact] public void Equals_SupportsUndefinedJsonValueNodes() { @@ -403,7 +385,6 @@ public class OpenIddictParameterTests // Act and assert Assert.False(parameter.Equals(new OpenIddictParameter((JsonNode?) null))); } -#endif [Fact] public void Equals_SupportsJsonValueElements() @@ -418,7 +399,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":100}").GetProperty("field")))); } -#if SUPPORTS_JSON_NODES [Fact] public void Equals_SupportsJsonValueNodes() { @@ -435,7 +415,6 @@ public class OpenIddictParameterTests Assert.False(parameter.Equals(new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":100}").GetProperty("field"))))); } -#endif [Fact] public void Equals_ReturnsFalseForNonParameters() @@ -546,7 +525,6 @@ public class OpenIddictParameterTests @"[""Contoso"",""Fabrikam""]")).GetHashCode()); } -#if SUPPORTS_JSON_NODES [Fact] public void GetHashCode_ReturnsUnderlyingHashCodeForJsonNodes() { @@ -591,7 +569,6 @@ public class OpenIddictParameterTests new OpenIddictParameter(JsonValue.Create(new { field = "value" })).GetHashCode(), new OpenIddictParameter(JsonValue.Create(new { field = "abc" })).GetHashCode()); } -#endif [Theory] [InlineData(null)] @@ -654,7 +631,6 @@ public class OpenIddictParameterTests Assert.Null(parameter.GetNamedParameter("Fabrikam")); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameter_ReturnsNullForJsonArrayNodes() { @@ -664,7 +640,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Null(parameter.GetNamedParameter("Fabrikam")); } -#endif [Fact] public void GetNamedParameter_ReturnsExpectedParameterForJsonObjectElements() @@ -677,7 +652,6 @@ public class OpenIddictParameterTests Assert.Equal("value", (string?) parameter.GetNamedParameter("parameter")); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameter_ReturnsExpectedParameterForJsonObjectNodes() { @@ -690,7 +664,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Equal("value", (string?) parameter.GetNamedParameter("parameter")); } -#endif [Fact] public void GetUnnamedParameter_ThrowsAnExceptionForNegativeIndex() @@ -755,7 +728,6 @@ public class OpenIddictParameterTests Assert.Null(parameter.GetUnnamedParameter(2)); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameter_ReturnsNullForOutOfRangeJsonArrayNodeIndex() { @@ -765,7 +737,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Null(parameter.GetUnnamedParameter(2)); } -#endif [Fact] public void GetUnnamedParameter_ReturnsNullForJsonObjectElements() @@ -778,7 +749,6 @@ public class OpenIddictParameterTests Assert.Null(parameter.GetUnnamedParameter(0)); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameter_ReturnsNullForJsonObjectNodes() { @@ -791,7 +761,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Null(parameter.GetUnnamedParameter(0)); } -#endif [Fact] public void GetUnnamedParameter_ReturnsExpectedNodeForJsonArrayElements() @@ -804,7 +773,6 @@ public class OpenIddictParameterTests Assert.Equal("Fabrikam", (string?) parameter.GetUnnamedParameter(0)); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameter_ReturnsExpectedNodeForJsonArrayNodes() { @@ -814,7 +782,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Equal("Fabrikam", (string?) parameter.GetUnnamedParameter(0)); } -#endif [Fact] public void GetNamedParameters_ReturnsEmptyDictionaryForPrimitiveValues() @@ -853,7 +820,6 @@ public class OpenIddictParameterTests Assert.Empty(parameter.GetNamedParameters()); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameters_ReturnsEmptyDictionaryForJsonValueNodes() { @@ -863,7 +829,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Empty(parameter.GetNamedParameters()); } -#endif [Fact] public void GetNamedParameters_ReturnsEmptyDictionaryForJsonArrayElements() @@ -876,7 +841,6 @@ public class OpenIddictParameterTests Assert.Empty(parameter.GetNamedParameters()); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameters_ReturnsEmptyDictionaryForJsonArrayNodes() { @@ -886,7 +850,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Empty(parameter.GetNamedParameters()); } -#endif [Fact] public void GetNamedParameters_ReturnsExpectedParametersForJsonObjectElements() @@ -904,7 +867,6 @@ public class OpenIddictParameterTests Assert.Equal(parameters, parameter.GetNamedParameters().ToDictionary(pair => pair.Key, pair => (string?) pair.Value)); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameters_ReturnsExpectedParametersForJsonObjectNodes() { @@ -922,7 +884,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Equal(parameters, parameter.GetNamedParameters().ToDictionary(pair => pair.Key, pair => (string?) pair.Value)); } -#endif [Fact] public void GetNamedParameters_ReturnsLastOccurrenceOfMultipleElementParameters() @@ -935,7 +896,6 @@ public class OpenIddictParameterTests Assert.Equal("value_2", parameter.GetNamedParameters()["parameter"]); } -#if SUPPORTS_JSON_NODES [Fact] public void GetNamedParameters_ReturnsLastOccurrenceOfMultipleNodeParameters() { @@ -949,7 +909,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Equal("value_2", parameter.GetNamedParameters()["parameter"]); } -#endif [Fact] public void GetUnnamedParameters_ReturnsEmptyListForPrimitiveValues() @@ -989,7 +948,6 @@ public class OpenIddictParameterTests Assert.Empty(parameter.GetUnnamedParameters()); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameters_ReturnsEmptyListForJsonValueNodes() { @@ -999,7 +957,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Empty(parameter.GetUnnamedParameters()); } -#endif [Fact] public void GetUnnamedParameters_ReturnsExpectedParametersForJsonArrayElements() @@ -1019,7 +976,6 @@ public class OpenIddictParameterTests select (string?) element); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameters_ReturnsExpectedParametersForJsonArrayNodes() { @@ -1036,7 +992,6 @@ public class OpenIddictParameterTests Assert.Equal(parameters, from element in parameter.GetUnnamedParameters() select (string?) element); } -#endif [Fact] public void GetUnnamedParameters_ReturnsEmptyListForJsonObjectElements() @@ -1049,7 +1004,6 @@ public class OpenIddictParameterTests Assert.Empty(parameter.GetUnnamedParameters()); } -#if SUPPORTS_JSON_NODES [Fact] public void GetUnnamedParameters_ReturnsEmptyListForJsonObjectNodes() { @@ -1062,7 +1016,6 @@ public class OpenIddictParameterTests // Act and assert Assert.Empty(parameter.GetUnnamedParameters()); } -#endif [Fact] public void IsNullOrEmpty_ReturnsTrueForNullValues() @@ -1079,10 +1032,7 @@ public class OpenIddictParameterTests { // Arrange, act and assert Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(default(JsonElement)))); - -#if SUPPORTS_JSON_NODES Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter((JsonNode?) null))); -#endif } [Fact] @@ -1099,14 +1049,12 @@ public class OpenIddictParameterTests Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":""""}").GetProperty("field")))); -#if SUPPORTS_JSON_NODES Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(new JsonArray()))); Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(new JsonObject()))); Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(JsonValue.Create(string.Empty)))); Assert.True(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":""""}").GetProperty("field"))))); -#endif } [Fact] @@ -1127,7 +1075,6 @@ public class OpenIddictParameterTests Assert.False(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":""Fabrikam""}").GetProperty("field")))); -#if SUPPORTS_JSON_NODES Assert.False(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(new JsonArray("Fabrikam")))); Assert.False(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(new JsonObject @@ -1139,7 +1086,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":""Fabrikam""}").GetProperty("field"))))); Assert.False(OpenIddictParameter.IsNullOrEmpty(new OpenIddictParameter(JsonValue.Create("Fabrikam")))); -#endif } [Fact] @@ -1238,7 +1184,6 @@ public class OpenIddictParameterTests Assert.Empty(result); } -#if SUPPORTS_JSON_NODES [Fact] public void ToString_ReturnsEmptyStringForUndefinedJsonValueNodes() { @@ -1252,7 +1197,6 @@ public class OpenIddictParameterTests Assert.NotNull(result); Assert.Empty(result); } -#endif [Fact] public void ToString_ReturnsUnderlyingJsonValue() @@ -1269,7 +1213,6 @@ public class OpenIddictParameterTests Assert.Equal(@"{""field"":""value""}", new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":""value""}")).ToString()); -#if SUPPORTS_JSON_NODES Assert.Equal("true", new OpenIddictParameter(JsonValue.Create(true)).ToString()); Assert.Equal("false", new OpenIddictParameter(JsonValue.Create(false)).ToString()); Assert.Equal("Fabrikam", new OpenIddictParameter(JsonValue.Create("Fabrikam")).ToString()); @@ -1291,7 +1234,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":false}").GetProperty("field"))).ToString()); Assert.Equal("Fabrikam", new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":""Fabrikam""}").GetProperty("field"))).ToString()); -#endif } [Theory] @@ -1359,7 +1301,6 @@ public class OpenIddictParameterTests Assert.Equal(default, value); } -#if SUPPORTS_JSON_NODES [Fact] public void TryGetNamedParameter_ReturnsFalseForJsonArrayNodes() { @@ -1370,7 +1311,6 @@ public class OpenIddictParameterTests Assert.False(parameter.TryGetNamedParameter("Fabrikam", out var value)); Assert.Equal(default, value); } -#endif [Fact] public void TryGetNamedParameter_ReturnsExpectedParameterForJsonObjectElements() @@ -1384,7 +1324,6 @@ public class OpenIddictParameterTests Assert.Equal("value", (string?) value); } -#if SUPPORTS_JSON_NODES [Fact] public void TryGetNamedParameter_ReturnsExpectedParameterForJsonObjectNodes() { @@ -1398,7 +1337,6 @@ public class OpenIddictParameterTests Assert.True(parameter.TryGetNamedParameter("parameter", out var value)); Assert.Equal("value", (string?) value); } -#endif [Fact] public void TryGetUnnamedParameter_ThrowsAnExceptionForNegativeIndex() @@ -1467,7 +1405,6 @@ public class OpenIddictParameterTests Assert.Equal(default, value); } -#if SUPPORTS_JSON_NODES [Fact] public void TryGetUnnamedParameter_ReturnsFalseForOutOfRangeJsonArrayNodeIndex() { @@ -1478,7 +1415,6 @@ public class OpenIddictParameterTests Assert.False(parameter.TryGetUnnamedParameter(2, out var value)); Assert.Equal(default, value); } -#endif [Fact] public void TryGetUnnamedParameter_ReturnsFalseForJsonObjectElements() @@ -1492,7 +1428,6 @@ public class OpenIddictParameterTests Assert.Equal(default, value); } -#if SUPPORTS_JSON_NODES [Fact] public void TryGetUnnamedParameter_ReturnsFalseForJsonObjectNodes() { @@ -1506,7 +1441,6 @@ public class OpenIddictParameterTests Assert.False(parameter.TryGetUnnamedParameter(0, out var value)); Assert.Equal(default, value); } -#endif [Fact] public void TryGetUnnamedParameter_ReturnsExpectedNodeForJsonArrayElements() @@ -1520,7 +1454,6 @@ public class OpenIddictParameterTests Assert.Equal("Fabrikam", (string?) value); } -#if SUPPORTS_JSON_NODES [Fact] public void TryGetUnnamedParameter_ReturnsExpectedNodeForJsonArrayNodes() { @@ -1531,7 +1464,6 @@ public class OpenIddictParameterTests Assert.True(parameter.TryGetUnnamedParameter(0, out var value)); Assert.Equal("Fabrikam", (string?) value); } -#endif [Fact] public void WriteTo_ThrowsAnExceptionForNullWriter() @@ -1612,13 +1544,10 @@ public class OpenIddictParameterTests Assert.Null((bool?) new OpenIddictParameter(JsonSerializer.Deserialize("[]"))); Assert.False((bool) new OpenIddictParameter(JsonSerializer.Deserialize("{}"))); Assert.Null((bool?) new OpenIddictParameter(JsonSerializer.Deserialize("{}"))); - -#if SUPPORTS_JSON_NODES Assert.False((bool) new OpenIddictParameter(new JsonObject())); Assert.Null((bool?) new OpenIddictParameter(new JsonObject())); Assert.False((bool) new OpenIddictParameter(new JsonArray())); Assert.Null((bool?) new OpenIddictParameter(new JsonArray())); -#endif } [Fact] @@ -1658,7 +1587,6 @@ public class OpenIddictParameterTests Assert.False((bool?) new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":""false""}").GetProperty("field"))); -#if SUPPORTS_JSON_NODES Assert.True((bool) new OpenIddictParameter(JsonValue.Create(true))); Assert.True((bool?) new OpenIddictParameter(JsonValue.Create(true))); Assert.True((bool) new OpenIddictParameter(JsonValue.Create("true"))); @@ -1686,7 +1614,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":""false""}").GetProperty("field")))); Assert.False((bool?) new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":""false""}").GetProperty("field")))); -#endif } [Fact] @@ -1782,7 +1709,6 @@ public class OpenIddictParameterTests Assert.Equal("value", dictionary.GetProperty("Property").GetString()); } -#if SUPPORTS_JSON_NODES [Fact] public void JsonNodeConverter_ReturnsDefaultValueForNullValues() { @@ -1967,7 +1893,6 @@ public class OpenIddictParameterTests ["Property"] = "value" })); } -#endif [Fact] public void LongConverter_CanCreateParameterFromLongValue() @@ -2007,11 +1932,8 @@ public class OpenIddictParameterTests // Arrange, act and assert Assert.Equal(0, (long) new OpenIddictParameter(JsonSerializer.Deserialize("[]"))); Assert.Null((long?) new OpenIddictParameter(JsonSerializer.Deserialize("[]"))); - -#if SUPPORTS_JSON_NODES Assert.Equal(0, (long) new OpenIddictParameter(new JsonArray())); Assert.Null((long?) new OpenIddictParameter(new JsonArray())); -#endif } [Fact] @@ -2033,7 +1955,6 @@ public class OpenIddictParameterTests Assert.Equal(42, (long?) new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":42}").GetProperty("field"))); -#if SUPPORTS_JSON_NODES Assert.Equal(42, (long?) new OpenIddictParameter(JsonValue.Create(42))); Assert.Equal(42, (long?) new OpenIddictParameter(JsonValue.Create(42))); Assert.Equal(42, (long?) new OpenIddictParameter(JsonValue.Create(42L))); @@ -2043,7 +1964,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":42}").GetProperty("field")))); Assert.Equal(42, (long?) new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":42}").GetProperty("field")))); -#endif } [Fact] @@ -2077,13 +1997,11 @@ public class OpenIddictParameterTests Assert.Null((string?) new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":""Fabrikam""}"))); -#if SUPPORTS_JSON_NODES Assert.Null((string?) new OpenIddictParameter(new JsonArray("Contoso", "Fabrikam"))); Assert.Null((string?) new OpenIddictParameter(new JsonObject { ["field"] = "Fabrikam" })); -#endif } [Fact] @@ -2106,7 +2024,6 @@ public class OpenIddictParameterTests Assert.Equal("42", (string?) new OpenIddictParameter( JsonSerializer.Deserialize(@"{""field"":42}").GetProperty("field"))); -#if SUPPORTS_JSON_NODES Assert.Equal("Fabrikam", (string?) new OpenIddictParameter(JsonValue.Create("Fabrikam"))); Assert.Equal("false", (string?) new OpenIddictParameter(JsonValue.Create(false))); Assert.Equal("42", (string?) new OpenIddictParameter(JsonValue.Create(42))); @@ -2118,7 +2035,6 @@ public class OpenIddictParameterTests JsonSerializer.Deserialize(@"{""field"":false}").GetProperty("field")))); Assert.Equal("42", (string?) new OpenIddictParameter(JsonValue.Create( JsonSerializer.Deserialize(@"{""field"":42}").GetProperty("field")))); -#endif } [Fact] @@ -2168,11 +2084,9 @@ public class OpenIddictParameterTests Assert.Null((string?[]?) new OpenIddictParameter( JsonSerializer.Deserialize(@"[""value"",{}]"))); -#if SUPPORTS_JSON_NODES Assert.Null((string?[]?) new OpenIddictParameter((JsonNode?) null)); Assert.Null((string?[]?) new OpenIddictParameter(new JsonArray("value", new JsonArray()))); Assert.Null((string?[]?) new OpenIddictParameter(new JsonArray("value", new JsonObject()))); -#endif } [Fact] @@ -2192,7 +2106,6 @@ public class OpenIddictParameterTests Assert.Equal(new[] { "value", "42", "true" }, (string?[]?) new OpenIddictParameter( JsonSerializer.Deserialize(@"[""value"",42,true]"))); -#if SUPPORTS_JSON_NODES Assert.Equal(new[] { "Fabrikam" }, (string?[]?) new OpenIddictParameter(JsonValue.Create("Fabrikam"))); Assert.Equal(new[] { "false" }, (string?[]?) new OpenIddictParameter(JsonValue.Create(false))); Assert.Equal(new[] { "42" }, (string?[]?) new OpenIddictParameter(JsonValue.Create(42))); @@ -2200,6 +2113,5 @@ public class OpenIddictParameterTests Assert.Equal(new[] { "Fabrikam" }, (string?[]?) new OpenIddictParameter(new JsonArray("Fabrikam"))); Assert.Equal(new[] { "Contoso", "Fabrikam" }, (string?[]?) new OpenIddictParameter(new JsonArray("Contoso", "Fabrikam"))); Assert.Equal(new[] { "value", "42", "true" }, (string?[]?) new OpenIddictParameter(new JsonArray("value", 42, true))); -#endif } } diff --git a/test/OpenIddict.Client.IntegrationTests/OpenIddict.Client.IntegrationTests.csproj b/test/OpenIddict.Client.IntegrationTests/OpenIddict.Client.IntegrationTests.csproj index c996acd2..29e76a9a 100644 --- a/test/OpenIddict.Client.IntegrationTests/OpenIddict.Client.IntegrationTests.csproj +++ b/test/OpenIddict.Client.IntegrationTests/OpenIddict.Client.IntegrationTests.csproj @@ -21,10 +21,7 @@ - + diff --git a/test/OpenIddict.Quartz.Tests/OpenIddictQuartzJobTests.cs b/test/OpenIddict.Quartz.Tests/OpenIddictQuartzJobTests.cs index 3c269f59..05798bdf 100644 --- a/test/OpenIddict.Quartz.Tests/OpenIddictQuartzJobTests.cs +++ b/test/OpenIddict.Quartz.Tests/OpenIddictQuartzJobTests.cs @@ -28,7 +28,10 @@ public class OpenIddictQuartzJobTests var scope = Mock.Of(scope => scope.ServiceProvider == provider); var factory = Mock.Of(factory => factory.CreateScope() == scope); var monitor = Mock.Of>( - monitor => monitor.CurrentValue == new OpenIddictQuartzOptions()); + monitor => monitor.CurrentValue == new OpenIddictQuartzOptions + { + TimeProvider = TimeProvider.System + }); var job = new OpenIddictQuartzJob(monitor, Mock.Of(provider => provider.GetService(typeof(IServiceScopeFactory)) == factory)); @@ -51,10 +54,7 @@ public class OpenIddictQuartzJobTests provider.GetService(typeof(IOpenIddictAuthorizationManager)) == Mock.Of() && provider.GetService(typeof(IOpenIddictTokenManager)) == manager.Object); - var job = CreateJob(provider, new OpenIddictQuartzOptions - { - DisableTokenPruning = true - }); + var job = CreateJob(provider, options => options.DisableTokenPruning = true); // Act await job.Execute(Mock.Of()); @@ -74,10 +74,7 @@ public class OpenIddictQuartzJobTests provider.GetService(typeof(IOpenIddictAuthorizationManager)) == manager.Object && provider.GetService(typeof(IOpenIddictTokenManager)) == Mock.Of()); - var job = CreateJob(provider, new OpenIddictQuartzOptions - { - DisableAuthorizationPruning = true - }); + var job = CreateJob(provider, options => options.DisableAuthorizationPruning = true); // Act await job.Execute(Mock.Of()); @@ -319,10 +316,7 @@ public class OpenIddictQuartzJobTests var context = Mock.Of(context => context.RefireCount == 5); - var job = CreateJob(provider, new OpenIddictQuartzOptions - { - MaximumRefireCount = 5 - }); + var job = CreateJob(provider, options => options.MaximumRefireCount = 5); // Act and assert var exception = await Assert.ThrowsAsync(() => job.Execute(context)); @@ -330,12 +324,18 @@ public class OpenIddictQuartzJobTests Assert.False(exception.RefireImmediately); } - private static OpenIddictQuartzJob CreateJob(IServiceProvider provider, OpenIddictQuartzOptions? options = null) + private static OpenIddictQuartzJob CreateJob(IServiceProvider provider, Action? configuration = null) { var scope = Mock.Of(scope => scope.ServiceProvider == provider); var factory = Mock.Of(factory => factory.CreateScope() == scope); - var monitor = Mock.Of>( - monitor => monitor.CurrentValue == (options ?? new OpenIddictQuartzOptions())); + var options = new OpenIddictQuartzOptions + { + TimeProvider = TimeProvider.System + }; + + configuration?.Invoke(options); + + var monitor = Mock.Of>(monitor => monitor.CurrentValue == options); return new OpenIddictQuartzJob(monitor, Mock.Of(provider => provider.GetService(typeof(IServiceScopeFactory)) == factory)); diff --git a/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIntegrationTests.cs b/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIntegrationTests.cs index 82a6dc0e..165c54b4 100644 --- a/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIntegrationTests.cs +++ b/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIntegrationTests.cs @@ -6,6 +6,7 @@ using System.Security.Claims; using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -21,10 +22,6 @@ using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlers; using static OpenIddict.Server.OpenIddictServerHandlers.Protection; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Server.AspNetCore.IntegrationTests; public partial class OpenIddictServerAspNetCoreIntegrationTests : OpenIddictServerIntegrationTests @@ -264,13 +261,10 @@ public partial class OpenIddictServerAspNetCoreIntegrationTests : OpenIddictServ Assert.Equal(JsonValueKind.Array, ((JsonElement) response["array_parameter"]).ValueKind); Assert.Equal("value", (string?) response["object_parameter"]?["parameter"]); Assert.Equal(JsonValueKind.Object, ((JsonElement) response["object_parameter"]).ValueKind); - -#if SUPPORTS_JSON_NODES Assert.Equal(new[] { "Contoso", "Fabrikam" }, (string[]?) response["node_array_parameter"]); Assert.IsType((JsonNode?) response["node_array_parameter"]); Assert.Equal("value", (string?) response["node_object_parameter"]?["parameter"]); Assert.IsType((JsonNode?) response["node_object_parameter"]); -#endif } [Fact] @@ -498,13 +492,10 @@ public partial class OpenIddictServerAspNetCoreIntegrationTests : OpenIddictServ Assert.Equal(JsonValueKind.Array, ((JsonElement) response["array_parameter"]).ValueKind); Assert.Equal("value", (string?) response["object_parameter"]?["parameter"]); Assert.Equal(JsonValueKind.Object, ((JsonElement) response["object_parameter"]).ValueKind); - -#if SUPPORTS_JSON_NODES Assert.Equal(new[] { "Contoso", "Fabrikam" }, (string[]?) response["node_array_parameter"]); Assert.IsType((JsonNode?) response["node_array_parameter"]); Assert.Equal("value", (string?) response["node_object_parameter"]?["parameter"]); Assert.IsType((JsonNode?) response["node_object_parameter"]); -#endif } [Fact] @@ -677,10 +668,8 @@ public partial class OpenIddictServerAspNetCoreIntegrationTests : OpenIddictServ ["string_parameter"] = "Bob l'Eponge", ["array_parameter"] = JsonSerializer.Deserialize(@"[""Contoso"",""Fabrikam""]"), ["object_parameter"] = JsonSerializer.Deserialize(@"{""parameter"":""value""}"), -#if SUPPORTS_JSON_NODES ["node_array_parameter"] = new JsonArray("Contoso", "Fabrikam"), ["node_object_parameter"] = new JsonObject { ["parameter"] = "value" } -#endif }); await context.SignInAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, principal, properties); @@ -735,10 +724,8 @@ public partial class OpenIddictServerAspNetCoreIntegrationTests : OpenIddictServ ["string_parameter"] = "Bob l'Eponge", ["array_parameter"] = JsonSerializer.Deserialize(@"[""Contoso"",""Fabrikam""]"), ["object_parameter"] = JsonSerializer.Deserialize(@"{""parameter"":""value""}"), -#if SUPPORTS_JSON_NODES ["node_array_parameter"] = new JsonArray("Contoso", "Fabrikam"), ["node_object_parameter"] = new JsonObject { ["parameter"] = "value" } -#endif }); await context.ChallengeAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, properties); diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddict.Server.IntegrationTests.csproj b/test/OpenIddict.Server.IntegrationTests/OpenIddict.Server.IntegrationTests.csproj index e2af95ab..dcb0caed 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddict.Server.IntegrationTests.csproj +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddict.Server.IntegrationTests.csproj @@ -26,10 +26,7 @@ - + diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Exchange.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Exchange.cs index 37af2c2e..181ee382 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Exchange.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Exchange.cs @@ -450,7 +450,7 @@ public abstract partial class OpenIddictServerIntegrationTests context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) .SetTokenType(TokenTypeHints.AuthorizationCode) - .SetExpirationDate(DateTimeOffset.UtcNow - TimeSpan.FromDays(1)) + .SetExpirationDate(TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)) .SetClaim(Claims.Subject, "Bob le Bricoleur"); return default; @@ -493,7 +493,7 @@ public abstract partial class OpenIddictServerIntegrationTests context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) .SetTokenType(TokenTypeHints.RefreshToken) - .SetExpirationDate(DateTimeOffset.UtcNow - TimeSpan.FromDays(1)) + .SetExpirationDate(TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)) .SetClaim(Claims.Subject, "Bob le Bricoleur"); return default; @@ -545,7 +545,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(token); mock.Setup(manager => manager.GetExpirationDateAsync(token, It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow - TimeSpan.FromDays(1)); + .ReturnsAsync(TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)); mock.Setup(manager => manager.GetTypeAsync(token, It.IsAny())) .ReturnsAsync(TokenTypeHints.DeviceCode); @@ -2601,7 +2601,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(token, It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow); + .ReturnsAsync(TimeProvider.System.GetUtcNow()); }); await using var server = await CreateServerAsync(options => @@ -2678,7 +2678,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(token, It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow - TimeSpan.FromMinutes(1)); + .ReturnsAsync(TimeProvider.System.GetUtcNow() - TimeSpan.FromMinutes(1)); }); await using var server = await CreateServerAsync(options => @@ -2755,7 +2755,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(token, It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow - TimeSpan.FromMinutes(1)); + .ReturnsAsync(TimeProvider.System.GetUtcNow() - TimeSpan.FromMinutes(1)); mock.Setup(manager => manager.CreateAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new OpenIddictToken()); @@ -2941,7 +2941,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(tokens[0], It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow); + .ReturnsAsync(TimeProvider.System.GetUtcNow()); mock.Setup(manager => manager.FindByAuthorizationIdAsync("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0", It.IsAny())) .Returns(tokens.ToAsyncEnumerable()); @@ -3032,7 +3032,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(tokens[0], It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow - TimeSpan.FromMinutes(1)); + .ReturnsAsync(TimeProvider.System.GetUtcNow() - TimeSpan.FromMinutes(1)); mock.Setup(manager => manager.FindByAuthorizationIdAsync("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0", It.IsAny())) .Returns(tokens.ToAsyncEnumerable()); @@ -3123,7 +3123,7 @@ public abstract partial class OpenIddictServerIntegrationTests .ReturnsAsync(true); mock.Setup(manager => manager.GetRedemptionDateAsync(tokens[0], It.IsAny())) - .ReturnsAsync(DateTimeOffset.UtcNow - TimeSpan.FromMinutes(1)); + .ReturnsAsync(TimeProvider.System.GetUtcNow() - TimeSpan.FromMinutes(1)); mock.Setup(manager => manager.FindByAuthorizationIdAsync("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0", It.IsAny())) .Returns(tokens.ToAsyncEnumerable()); diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Introspection.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Introspection.cs index 55991618..7edf5fd6 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Introspection.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Introspection.cs @@ -523,7 +523,7 @@ public abstract partial class OpenIddictServerIntegrationTests context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) .SetTokenType(TokenTypeHints.RefreshToken) - .SetExpirationDate(DateTimeOffset.UtcNow - TimeSpan.FromDays(1)); + .SetExpirationDate(TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)); return default; }); diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Userinfo.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Userinfo.cs index 2ca03e61..332c7218 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Userinfo.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Userinfo.cs @@ -180,7 +180,7 @@ public abstract partial class OpenIddictServerIntegrationTests context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) .SetTokenType(TokenTypeHints.AccessToken) - .SetExpirationDate(DateTimeOffset.UtcNow - TimeSpan.FromDays(1)); + .SetExpirationDate(TimeProvider.System.GetUtcNow() - TimeSpan.FromDays(1)); return default; }); diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.cs index f55fd1df..254f3e42 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.cs @@ -10,6 +10,7 @@ using System.Collections.Immutable; using System.Globalization; using System.Security.Claims; using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; @@ -21,10 +22,6 @@ using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlers; using static OpenIddict.Server.OpenIddictServerHandlers.Protection; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Server.IntegrationTests; public abstract partial class OpenIddictServerIntegrationTests @@ -1435,10 +1432,9 @@ public abstract partial class OpenIddictServerIntegrationTests context.Parameters["string_parameter"] = "Bob l'Eponge"; context.Parameters["array_parameter"] = JsonSerializer.Deserialize(@"[""Contoso"",""Fabrikam""]"); context.Parameters["object_parameter"] = JsonSerializer.Deserialize(@"{""parameter"":""value""}"); -#if SUPPORTS_JSON_NODES context.Parameters["node_array_parameter"] = new JsonArray("Contoso", "Fabrikam"); context.Parameters["node_object_parameter"] = new JsonObject { ["parameter"] = "value" }; -#endif + return default; })); }); @@ -1464,13 +1460,10 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(JsonValueKind.Array, ((JsonElement) response["array_parameter"]).ValueKind); Assert.Equal("value", (string?) response["object_parameter"]?["parameter"]); Assert.Equal(JsonValueKind.Object, ((JsonElement) response["object_parameter"]).ValueKind); - -#if SUPPORTS_JSON_NODES Assert.Equal(new[] { "Contoso", "Fabrikam" }, (string[]?) response["node_array_parameter"]); Assert.IsType((JsonNode?) response["node_array_parameter"]); Assert.Equal("value", (string?) response["node_object_parameter"]?["parameter"]); Assert.IsType((JsonNode?) response["node_object_parameter"]); -#endif } [Fact] @@ -3883,10 +3876,8 @@ public abstract partial class OpenIddictServerIntegrationTests context.Parameters["string_parameter"] = "Bob l'Eponge"; context.Parameters["array_parameter"] = JsonSerializer.Deserialize(@"[""Contoso"",""Fabrikam""]"); context.Parameters["object_parameter"] = JsonSerializer.Deserialize(@"{""parameter"":""value""}"); -#if SUPPORTS_JSON_NODES context.Parameters["node_array_parameter"] = new JsonArray("Contoso", "Fabrikam"); context.Parameters["node_object_parameter"] = new JsonObject { ["parameter"] = "value" }; -#endif return default; })); }); @@ -3912,13 +3903,10 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(JsonValueKind.Array, ((JsonElement) response["array_parameter"]).ValueKind); Assert.Equal("value", (string?) response["object_parameter"]?["parameter"]); Assert.Equal(JsonValueKind.Object, ((JsonElement) response["object_parameter"]).ValueKind); - -#if SUPPORTS_JSON_NODES Assert.Equal(new[] { "Contoso", "Fabrikam" }, (string[]?) response["node_array_parameter"]); Assert.IsType((JsonNode?) response["node_array_parameter"]); Assert.Equal("value", (string?) response["node_object_parameter"]?["parameter"]); Assert.IsType((JsonNode?) response["node_object_parameter"]); -#endif } [Fact] diff --git a/test/OpenIddict.Server.Owin.IntegrationTests/OpenIddict.Server.Owin.IntegrationTests.csproj b/test/OpenIddict.Server.Owin.IntegrationTests/OpenIddict.Server.Owin.IntegrationTests.csproj index 8f17f052..7bf61994 100644 --- a/test/OpenIddict.Server.Owin.IntegrationTests/OpenIddict.Server.Owin.IntegrationTests.csproj +++ b/test/OpenIddict.Server.Owin.IntegrationTests/OpenIddict.Server.Owin.IntegrationTests.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/OpenIddict.Validation.AspNetCore.IntegrationTests/OpenIddictValidationAspNetCoreIntegrationTests.cs b/test/OpenIddict.Validation.AspNetCore.IntegrationTests/OpenIddictValidationAspNetCoreIntegrationTests.cs index a29ccdab..c1f327d6 100644 --- a/test/OpenIddict.Validation.AspNetCore.IntegrationTests/OpenIddictValidationAspNetCoreIntegrationTests.cs +++ b/test/OpenIddict.Validation.AspNetCore.IntegrationTests/OpenIddictValidationAspNetCoreIntegrationTests.cs @@ -20,10 +20,6 @@ using Xunit.Abstractions; using static OpenIddict.Validation.OpenIddictValidationEvents; using static OpenIddict.Validation.OpenIddictValidationHandlers.Protection; -#if SUPPORTS_JSON_NODES -using System.Text.Json.Nodes; -#endif - namespace OpenIddict.Validation.AspNetCore.IntegrationTests; public partial class OpenIddictValidationAspNetCoreIntegrationTests : OpenIddictValidationIntegrationTests diff --git a/test/OpenIddict.Validation.IntegrationTests/OpenIddict.Validation.IntegrationTests.csproj b/test/OpenIddict.Validation.IntegrationTests/OpenIddict.Validation.IntegrationTests.csproj index 745f0a00..63fc2c3a 100644 --- a/test/OpenIddict.Validation.IntegrationTests/OpenIddict.Validation.IntegrationTests.csproj +++ b/test/OpenIddict.Validation.IntegrationTests/OpenIddict.Validation.IntegrationTests.csproj @@ -25,10 +25,7 @@ - + diff --git a/test/OpenIddict.Validation.Owin.IntegrationTests/OpenIddict.Validation.Owin.IntegrationTests.csproj b/test/OpenIddict.Validation.Owin.IntegrationTests/OpenIddict.Validation.Owin.IntegrationTests.csproj index 3ad98f2c..dcc261db 100644 --- a/test/OpenIddict.Validation.Owin.IntegrationTests/OpenIddict.Validation.Owin.IntegrationTests.csproj +++ b/test/OpenIddict.Validation.Owin.IntegrationTests/OpenIddict.Validation.Owin.IntegrationTests.csproj @@ -13,7 +13,7 @@ - +