diff --git a/Directory.Packages.props b/Directory.Packages.props
index 40909ed4..6e63f2d0 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -48,8 +48,6 @@
-
-
@@ -93,7 +91,6 @@
-
@@ -127,7 +124,6 @@
-
@@ -140,6 +136,7 @@
+
diff --git a/OpenIddict.slnx b/OpenIddict.slnx
index 0e76237a..a82e216d 100644
--- a/OpenIddict.slnx
+++ b/OpenIddict.slnx
@@ -66,7 +66,6 @@
-
@@ -95,7 +94,6 @@
-
diff --git a/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config b/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config
index 79435b34..92cb6ef4 100644
--- a/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config
+++ b/sandbox/OpenIddict.Sandbox.AspNet.Client/Web.config
@@ -172,18 +172,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
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 011b2a3f..828e7234 100644
--- a/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj
+++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Client/OpenIddict.Sandbox.AspNetCore.Client.csproj
@@ -7,7 +7,6 @@
-
diff --git a/sandbox/OpenIddict.Sandbox.AspNetCore.Client/Program.cs b/sandbox/OpenIddict.Sandbox.AspNetCore.Client/Program.cs
index 21e31a7f..b194b1ce 100644
--- a/sandbox/OpenIddict.Sandbox.AspNetCore.Client/Program.cs
+++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Client/Program.cs
@@ -6,7 +6,6 @@ using Microsoft.IdentityModel.Tokens;
using OpenIddict.Client;
using OpenIddict.Client.WebIntegration;
using OpenIddict.Sandbox.AspNetCore.Client.Models;
-using Quartz;
using static OpenIddict.Abstractions.OpenIddictConstants;
var builder = WebApplication.CreateBuilder(args);
@@ -36,17 +35,6 @@ builder.Services.AddAuthentication(options =>
options.SlidingExpiration = false;
});
-// OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
-// (like pruning orphaned authorizations from the database) at regular intervals.
-builder.Services.AddQuartz(options =>
-{
- options.UseSimpleTypeLoader();
- options.UseInMemoryStore();
-});
-
-// Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
-builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
-
builder.Services.AddOpenIddict()
// Register the OpenIddict core components.
@@ -61,8 +49,13 @@ builder.Services.AddOpenIddict()
// options.UseMongoDb()
// .UseDatabase(new MongoClient().GetDatabase("openiddict"));
- // Enable Quartz.NET integration.
- options.UseQuartz();
+ // Note: by default, OpenIddict automatically prunes authorizations, sessions and tokens
+ // that are no longer valid at regular intervals. For those who prefer using their own
+ // pruning mechanism (e.g based on Quartz.NET or Hangfire), automatic pruning can be disabled.
+ //
+ // options.DisableAutomaticAuthorizationPruning()
+ // .DisableAutomaticSessionPruning()
+ // .DisableAutomaticTokenPruning();
})
// Register the OpenIddict client components.
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 057c0336..30858557 100644
--- a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj
+++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/OpenIddict.Sandbox.AspNetCore.Server.csproj
@@ -9,7 +9,6 @@
-
diff --git a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs
index 62ba3e97..05390651 100644
--- a/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs
+++ b/sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs
@@ -10,7 +10,6 @@ using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Sandbox.AspNetCore.Server.Models;
using OpenIddict.Sandbox.AspNetCore.Server.Services;
-using Quartz;
using static OpenIddict.Abstractions.OpenIddictConstants;
var builder = WebApplication.CreateBuilder(args);
@@ -50,17 +49,6 @@ builder.Services.Configure(options => options.OnR
return Task.CompletedTask;
});
-// OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
-// (like pruning orphaned authorizations/tokens from the database) at regular intervals.
-builder.Services.AddQuartz(options =>
-{
- options.UseSimpleTypeLoader();
- options.UseInMemoryStore();
-});
-
-// Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
-builder.Services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
-
builder.Services.AddOpenIddict()
// Register the OpenIddict core components.
@@ -75,8 +63,13 @@ builder.Services.AddOpenIddict()
// options.UseMongoDb()
// .UseDatabase(new MongoClient().GetDatabase("openiddict"));
- // Enable Quartz.NET integration.
- options.UseQuartz();
+ // Note: by default, OpenIddict automatically prunes authorizations, sessions and tokens
+ // that are no longer valid at regular intervals. For those who prefer using their own
+ // pruning mechanism (e.g based on Quartz.NET or Hangfire), automatic pruning can be disabled.
+ //
+ // options.DisableAutomaticAuthorizationPruning()
+ // .DisableAutomaticSessionPruning()
+ // .DisableAutomaticTokenPruning();
})
// Register the OpenIddict client components.
diff --git a/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs b/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs
index 5481ce0f..13928e3c 100644
--- a/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs
+++ b/sandbox/OpenIddict.Sandbox.Console.Client/Program.cs
@@ -32,6 +32,14 @@ builder.Services.AddOpenIddict()
options.UseEntityFramework()
.UseDbContext();
#endif
+
+ // Note: by default, OpenIddict automatically prunes authorizations, sessions and tokens
+ // that are no longer valid at regular intervals. For those who prefer using their own
+ // pruning mechanism (e.g based on Quartz.NET or Hangfire), automatic pruning can be disabled.
+ //
+ // options.DisableAutomaticAuthorizationPruning()
+ // .DisableAutomaticSessionPruning()
+ // .DisableAutomaticTokenPruning();
})
// Register the OpenIddict client components.
diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index 0e5466e4..debb0713 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -383,10 +383,6 @@ Consider using 'options.AddSigningCredentials(SigningCredentials)' instead.
Endpoint URIs cannot start with '{0}'.
-
- Dependency injection support must be enabled in Quartz.NET when using the OpenIddict integration.
-To enable DI support, call 'services.AddQuartz(options => options.UseMicrosoftDependencyInjectionJobFactory())' or 'services.AddQuartz(options => options.UseMicrosoftDependencyInjectionScopedJobFactory())'.
-
Reference tokens cannot be used when disabling token storage.
@@ -896,10 +892,6 @@ To apply configuration responses, create a class implementing 'IOpenIddictServer
The Entity Framework 6.x stores cannot be used with generic types.
Consider creating non-generic classes derived from the default entities for the application, authorization, scope and token entities.
-
-
- The core services must be registered when enabling the OpenIddict Quartz.NET integration.
-To register the OpenIddict core services, reference the 'OpenIddict.Core' package and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.The maximum refire count cannot be negative.
@@ -3287,22 +3279,16 @@ This may indicate that the hashed entry is corrupted or malformed.
The session '{Identifier}' was no longer valid.
-
- https://documentation.openiddict.com/errors/{0}
+
+ A non-fatal error occurred while pruning tokens from the database.
-
- Removes orphaned tokens and authorizations from the database.
+
+ A non-fatal error occurred while pruning authorizations from the database.
-
- Starts the scheduled task at regular intervals.
+
+ A non-fatal error occurred while pruning sessions from the database.
-
- OpenIddict job
-
-
- Built-in automatic trigger
-
-
- OpenIddict/Quartz.NET integration
+
+ https://documentation.openiddict.com/errors/{0}
\ No newline at end of file
diff --git a/src/OpenIddict.Core/OpenIddict.Core.csproj b/src/OpenIddict.Core/OpenIddict.Core.csproj
index e8616c44..5c53a8f4 100644
--- a/src/OpenIddict.Core/OpenIddict.Core.csproj
+++ b/src/OpenIddict.Core/OpenIddict.Core.csproj
@@ -15,6 +15,7 @@
+
diff --git a/src/OpenIddict.Core/OpenIddictCoreBackgroundService.cs b/src/OpenIddict.Core/OpenIddictCoreBackgroundService.cs
new file mode 100644
index 00000000..846e8181
--- /dev/null
+++ b/src/OpenIddict.Core/OpenIddictCoreBackgroundService.cs
@@ -0,0 +1,144 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+using System.ComponentModel;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+
+namespace OpenIddict.Core;
+
+///
+/// Represents a hosted service performing background tasks for OpenIddict.
+///
+[EditorBrowsable(EditorBrowsableState.Never)]
+public sealed class OpenIddictCoreBackgroundService : BackgroundService
+{
+ private readonly ILogger _logger;
+ private readonly IOptionsMonitor _options;
+ private readonly IServiceProvider _provider;
+
+ ///
+ /// Creates a new instance of the class.
+ ///
+ /// The logger.
+ /// The OpenIddict core options.
+ /// The service provider.
+ public OpenIddictCoreBackgroundService(
+ ILogger logger,
+ IOptionsMonitor options,
+ IServiceProvider provider)
+ {
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _options = options ?? throw new ArgumentNullException(nameof(options));
+ _provider = provider ?? throw new ArgumentNullException(nameof(provider));
+ }
+
+ ///
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ var options = _options.CurrentValue;
+
+ // Note: if all the automatic pruning features are disabled, the background service no-ops.
+ if (options.DisableAutomaticAuthorizationPruning &&
+ options.DisableAutomaticSessionPruning && options.DisableAutomaticTokenPruning)
+ {
+ return;
+ }
+
+ // Note: an initialization delay is used to avoid executing the pruning logic immediately after
+ // the application starts and to reduce the risk of multiple instances of the application
+ // pruning the database at the same time (which could lead to deadlocks in some cases).
+#if NET
+ await Task.Delay(TimeSpan.FromMinutes(Random.Shared.Next(1, 10)), options.TimeProvider, stoppingToken);
+#else
+ await Task.Delay(TimeSpan.FromMinutes(Random.Shared.Next(1, 10)), stoppingToken);
+#endif
+
+ using var timer = new PeriodicTimer(TimeSpan.FromHours(1), options.TimeProvider);
+
+ // Note: exceptions thrown by the pruning logic are caught and logged to avoid crashing
+ // the background service and to ensure these exceptions are not propagated to the
+ // .NET Generic Host (which would cause the application to be stopped by default).
+
+ do
+ {
+ await using var scope = _provider.CreateAsyncScope();
+
+ // Important: since authorizations that still have tokens attached are never
+ // pruned, the tokens MUST be deleted before deleting the authorizations.
+
+ if (!options.DisableAutomaticTokenPruning)
+ {
+ var manager = scope.ServiceProvider.GetRequiredService();
+ var threshold = options.TimeProvider.GetUtcNow() - options.MinimumTokenLifespan;
+
+ try
+ {
+ await manager.PruneAsync(threshold, stoppingToken);
+ }
+
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ return;
+ }
+
+ catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
+ {
+ _logger.LogInformation(6298, exception, SR.GetResourceString(SR.ID6298));
+ }
+ }
+
+ if (!options.DisableAutomaticAuthorizationPruning)
+ {
+ var manager = scope.ServiceProvider.GetRequiredService();
+ var threshold = options.TimeProvider.GetUtcNow() - options.MinimumAuthorizationLifespan;
+
+ try
+ {
+ await manager.PruneAsync(threshold, stoppingToken);
+ }
+
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ return;
+ }
+
+ catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
+ {
+ _logger.LogInformation(6299, exception, SR.GetResourceString(SR.ID6299));
+ }
+ }
+
+ // Important: since sessions that still have tokens attached are never
+ // pruned, the tokens MUST be deleted before deleting the sessions.
+
+ if (!options.DisableAutomaticSessionPruning)
+ {
+ var manager = scope.ServiceProvider.GetRequiredService();
+ var threshold = options.TimeProvider.GetUtcNow() - options.MinimumSessionLifespan;
+
+ try
+ {
+ await manager.PruneAsync(threshold, stoppingToken);
+ }
+
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ return;
+ }
+
+ catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
+ {
+ _logger.LogInformation(6300, exception, SR.GetResourceString(SR.ID6300));
+ }
+ }
+ }
+
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/OpenIddict.Core/OpenIddictCoreBuilder.cs b/src/OpenIddict.Core/OpenIddictCoreBuilder.cs
index 353eca76..c38c9b48 100644
--- a/src/OpenIddict.Core/OpenIddictCoreBuilder.cs
+++ b/src/OpenIddict.Core/OpenIddictCoreBuilder.cs
@@ -57,6 +57,27 @@ public sealed class OpenIddictCoreBuilder
return this;
}
+ ///
+ /// Disables automatic authorizations pruning.
+ ///
+ /// The instance.
+ public OpenIddictCoreBuilder DisableAutomaticAuthorizationPruning()
+ => Configure(options => options.DisableAutomaticAuthorizationPruning = true);
+
+ ///
+ /// Disables automatic sessions pruning.
+ ///
+ /// The instance.
+ public OpenIddictCoreBuilder DisableAutomaticSessionPruning()
+ => Configure(options => options.DisableAutomaticSessionPruning = true);
+
+ ///
+ /// Disables automatic tokens pruning.
+ ///
+ /// The instance.
+ public OpenIddictCoreBuilder DisableAutomaticTokenPruning()
+ => Configure(options => options.DisableAutomaticTokenPruning = true);
+
///
/// Replaces the application manager by the specified type.
///
@@ -719,6 +740,42 @@ public sealed class OpenIddictCoreBuilder
return Configure(options => options.EntityCacheLimit = limit);
}
+ ///
+ /// Sets the minimum lifespan authorizations must have to be pruned.
+ ///
+ /// The minimum lifespan authorizations must have to be pruned.
+ /// The instance.
+ public OpenIddictCoreBuilder SetMinimumAuthorizationLifespan(TimeSpan lifespan)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
+
+ return Configure(options => options.MinimumAuthorizationLifespan = lifespan);
+ }
+
+ ///
+ /// Sets the minimum lifespan sessions must have to be pruned.
+ ///
+ /// The minimum lifespan sessions must have to be pruned.
+ /// The instance.
+ public OpenIddictCoreBuilder SetMinimumSessionLifespan(TimeSpan lifespan)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
+
+ return Configure(options => options.MinimumSessionLifespan = lifespan);
+ }
+
+ ///
+ /// Sets the minimum lifespan tokens must have to be pruned.
+ ///
+ /// The minimum lifespan tokens must have to be pruned.
+ /// The instance.
+ public OpenIddictCoreBuilder SetMinimumTokenLifespan(TimeSpan lifespan)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
+
+ return Configure(options => options.MinimumTokenLifespan = lifespan);
+ }
+
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals([NotNullWhen(true)] object? obj) => base.Equals(obj);
diff --git a/src/OpenIddict.Core/OpenIddictCoreExtensions.cs b/src/OpenIddict.Core/OpenIddictCoreExtensions.cs
index 2dc8aff1..c9de0215 100644
--- a/src/OpenIddict.Core/OpenIddictCoreExtensions.cs
+++ b/src/OpenIddict.Core/OpenIddictCoreExtensions.cs
@@ -59,6 +59,8 @@ public static class OpenIddictCoreExtensions
builder.Services.TryAddScoped(static provider =>
throw new InvalidOperationException(SR.GetResourceString(SR.ID0472)));
+ builder.Services.AddHostedService();
+
// Note: TryAddEnumerable() is used here to ensure the initializers are registered only once.
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<
IPostConfigureOptions, OpenIddictCoreConfiguration>());
diff --git a/src/OpenIddict.Core/OpenIddictCoreOptions.cs b/src/OpenIddict.Core/OpenIddictCoreOptions.cs
index 20a35b4b..842d5457 100644
--- a/src/OpenIddict.Core/OpenIddictCoreOptions.cs
+++ b/src/OpenIddict.Core/OpenIddictCoreOptions.cs
@@ -63,6 +63,21 @@ public sealed class OpenIddictCoreOptions
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool DisableEntityCaching { get; set; }
+ ///
+ /// Gets or sets a boolean indicating whether authorizations pruning should be disabled.
+ ///
+ public bool DisableAutomaticAuthorizationPruning { get; set; }
+
+ ///
+ /// Gets or sets a boolean indicating whether sessions pruning should be disabled.
+ ///
+ public bool DisableAutomaticSessionPruning { get; set; }
+
+ ///
+ /// Gets or sets a boolean indicating whether tokens pruning should be disabled.
+ ///
+ public bool DisableAutomaticTokenPruning { get; set; }
+
///
/// Gets or sets the maximum number of cached entries allowed. When the threshold
/// is reached, the cache is automatically compacted to ensure it doesn't grow
@@ -72,6 +87,24 @@ public sealed class OpenIddictCoreOptions
[EditorBrowsable(EditorBrowsableState.Advanced)]
public int EntityCacheLimit { get; set; } = 250;
+ ///
+ /// Gets or sets the minimum lifespan authorizations must have to be pruned.
+ /// By default, this value is set to 14 days and cannot be less than 10 minutes.
+ ///
+ public TimeSpan MinimumAuthorizationLifespan { get; set; } = TimeSpan.FromDays(14);
+
+ ///
+ /// Gets or sets the minimum lifespan sessions must have to be pruned.
+ /// By default, this value is set to 14 days and cannot be less than 10 minutes.
+ ///
+ public TimeSpan MinimumSessionLifespan { get; set; } = TimeSpan.FromDays(14);
+
+ ///
+ /// Gets or sets the minimum lifespan tokens must have to be pruned.
+ /// By default, this value is set to 14 days and cannot be less than 10 minutes.
+ ///
+ public TimeSpan MinimumTokenLifespan { get; set; } = TimeSpan.FromDays(14);
+
///
/// Gets or sets the time provider.
///
diff --git a/src/OpenIddict.Quartz/OpenIddict.Quartz.csproj b/src/OpenIddict.Quartz/OpenIddict.Quartz.csproj
deleted file mode 100644
index 8cd60427..00000000
--- a/src/OpenIddict.Quartz/OpenIddict.Quartz.csproj
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
- $(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks)
-
-
-
- Quartz.NET integration package for OpenIddict.
- $(PackageTags);quartz
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzBuilder.cs b/src/OpenIddict.Quartz/OpenIddictQuartzBuilder.cs
deleted file mode 100644
index c11a86f9..00000000
--- a/src/OpenIddict.Quartz/OpenIddictQuartzBuilder.cs
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- * See https://github.com/openiddict/openiddict-core for more information concerning
- * the license and the contributors participating to this project.
- */
-
-using System.ComponentModel;
-using System.Diagnostics.CodeAnalysis;
-using OpenIddict.Quartz;
-
-namespace Microsoft.Extensions.DependencyInjection;
-
-///
-/// Exposes the necessary methods required to configure the OpenIddict Quartz.NET integration.
-///
-public sealed class OpenIddictQuartzBuilder
-{
- ///
- /// Initializes a new instance of .
- ///
- /// The services collection.
- public OpenIddictQuartzBuilder(IServiceCollection services)
- => Services = services ?? throw new ArgumentNullException(nameof(services));
-
- ///
- /// Gets the services collection.
- ///
- [EditorBrowsable(EditorBrowsableState.Never)]
- public IServiceCollection Services { get; }
-
- ///
- /// Enables validation of options during application startup.
- ///
- /// The instance.
- public OpenIddictQuartzBuilder ValidateOnStart()
- {
- Services.AddOptionsWithValidateOnStart();
-
- return this;
- }
-
- ///
- /// Amends the default OpenIddict Quartz.NET configuration.
- ///
- /// The delegate used to configure the OpenIddict options.
- /// This extension can be safely called multiple times.
- /// The instance.
- [EditorBrowsable(EditorBrowsableState.Advanced)]
- public OpenIddictQuartzBuilder Configure(Action configuration)
- {
- ArgumentNullException.ThrowIfNull(configuration);
-
- Services.Configure(configuration);
-
- return this;
- }
-
- ///
- /// Disables authorizations pruning.
- ///
- /// The instance.
- public OpenIddictQuartzBuilder DisableAuthorizationPruning()
- => Configure(options => options.DisableAuthorizationPruning = true);
-
- ///
- /// Disables sessions pruning.
- ///
- /// The instance.
- public OpenIddictQuartzBuilder DisableSessionPruning()
- => Configure(options => options.DisableSessionPruning = true);
-
- ///
- /// Disables tokens pruning.
- ///
- /// The instance.
- public OpenIddictQuartzBuilder DisableTokenPruning()
- => Configure(options => options.DisableTokenPruning = true);
-
- ///
- /// Sets the number of times a failed Quartz.NET job can be retried.
- ///
- /// The number of times a failed Quartz.NET job can be retried.
- /// The instance.
- public OpenIddictQuartzBuilder SetMaximumRefireCount(int count)
- {
- ArgumentOutOfRangeException.ThrowIfNegative(count);
-
- return Configure(options => options.MaximumRefireCount = count);
- }
-
- ///
- /// Sets the minimum lifespan authorizations must have to be pruned.
- ///
- /// The minimum lifespan authorizations must have to be pruned.
- /// The instance.
- public OpenIddictQuartzBuilder SetMinimumAuthorizationLifespan(TimeSpan lifespan)
- {
- ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
-
- return Configure(options => options.MinimumAuthorizationLifespan = lifespan);
- }
-
- ///
- /// Sets the minimum lifespan sessions must have to be pruned.
- ///
- /// The minimum lifespan sessions must have to be pruned.
- /// The instance.
- public OpenIddictQuartzBuilder SetMinimumSessionLifespan(TimeSpan lifespan)
- {
- ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
-
- return Configure(options => options.MinimumSessionLifespan = lifespan);
- }
-
- ///
- /// Sets the minimum lifespan tokens must have to be pruned.
- ///
- /// The minimum lifespan tokens must have to be pruned.
- /// The instance.
- public OpenIddictQuartzBuilder SetMinimumTokenLifespan(TimeSpan lifespan)
- {
- ArgumentOutOfRangeException.ThrowIfLessThan(lifespan, TimeSpan.FromMinutes(10));
-
- return Configure(options => options.MinimumTokenLifespan = lifespan);
- }
-
- ///
- [EditorBrowsable(EditorBrowsableState.Never)]
- public override bool Equals([NotNullWhen(true)] object? obj) => base.Equals(obj);
-
- ///
- [EditorBrowsable(EditorBrowsableState.Never)]
- public override int GetHashCode() => base.GetHashCode();
-
- ///
- [EditorBrowsable(EditorBrowsableState.Never)]
- public override string? ToString() => base.ToString();
-}
diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs b/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs
deleted file mode 100644
index e6d87cd2..00000000
--- a/src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- * See https://github.com/openiddict/openiddict-core for more information concerning
- * the license and the contributors participating to this project.
- */
-
-using System.ComponentModel;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Options;
-
-namespace OpenIddict.Quartz;
-
-///
-/// Contains the methods required to ensure that the OpenIddict Quartz.NET configuration is valid.
-///
-[EditorBrowsable(EditorBrowsableState.Advanced)]
-public sealed class OpenIddictQuartzConfiguration : IPostConfigureOptions
-{
- private readonly IServiceProvider _provider;
-
- ///
- /// Creates a new instance of the class.
- ///
- /// The service provider.
- public OpenIddictQuartzConfiguration(IServiceProvider provider)
- => _provider = provider ?? throw new ArgumentNullException(nameof(provider));
-
- ///
- public void PostConfigure(string? name, OpenIddictQuartzOptions options)
- {
- ArgumentNullException.ThrowIfNull(options);
-
- options.TimeProvider ??= _provider.GetService() ?? TimeProvider.System;
- }
-}
diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzExtensions.cs b/src/OpenIddict.Quartz/OpenIddictQuartzExtensions.cs
deleted file mode 100644
index 8a35970d..00000000
--- a/src/OpenIddict.Quartz/OpenIddictQuartzExtensions.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- * See https://github.com/openiddict/openiddict-core for more information concerning
- * the license and the contributors participating to this project.
- */
-
-using Microsoft.Extensions.DependencyInjection.Extensions;
-using Microsoft.Extensions.Options;
-using OpenIddict.Quartz;
-
-namespace Microsoft.Extensions.DependencyInjection;
-
-///
-/// Exposes extensions allowing to register the OpenIddict Quartz.NET integration.
-///
-public static class OpenIddictQuartzExtensions
-{
- ///
- /// Registers the OpenIddict Quartz.NET integration in the DI container.
- ///
- /// The services builder used by OpenIddict to register new services.
- /// This extension can be safely called multiple times.
- /// The instance.
- public static OpenIddictQuartzBuilder UseQuartz(this OpenIddictCoreBuilder builder)
- {
- ArgumentNullException.ThrowIfNull(builder);
-
- // Note: the AddQuartz() method MUST only be called once to avoid adding multiple jobs and triggers.
- if (!builder.Services.Any(static descriptor => descriptor.ServiceType == typeof(OpenIddictQuartzJob)))
- {
- builder.Services.AddQuartz(options =>
- {
- options.AddJob(static builder =>
- {
- builder.StoreDurably()
- .WithIdentity(OpenIddictQuartzJob.Identity)
- .WithDescription(SR.GetResourceString(SR.ID8001));
- });
-
- options.AddTrigger(static builder =>
- {
- // Note: this trigger uses a quite long interval (1 hour), which means it may be potentially never
- // reached if the application is shut down or recycled. As such, this trigger is set up to fire
- // between 1 and 10 minutes after the application starts to ensure the job is executed at least once.
- builder.ForJob(OpenIddictQuartzJob.Identity)
- .WithIdentity(SR.GetResourceString(SR.ID8004), SR.GetResourceString(SR.ID8005))
- .WithSimpleSchedule(options => options.WithInterval(TimeSpan.FromHours(1)).RepeatForever())
- .WithDescription(SR.GetResourceString(SR.ID8002))
- .StartAt(TimeProvider.System.GetUtcNow() + TimeSpan.FromMinutes(new Random().Next(1, 10)));
- });
- });
- }
-
-#if !NET
- // Note: unlike Quartz.NET 4.0+, Quartz.NET 3.x doesn't automatically register the job as a service.
- builder.Services.TryAddTransient();
-#endif
-
- // Note: TryAddEnumerable() is used here to ensure the initializer is registered only once.
- builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<
- IPostConfigureOptions, OpenIddictQuartzConfiguration>());
-
- return new OpenIddictQuartzBuilder(builder.Services);
- }
-
- ///
- /// Registers the OpenIddict Quartz.NET integration in the DI container.
- ///
- /// The services builder used by OpenIddict to register new services.
- /// The configuration delegate used to configure the Quartz.NET services.
- /// This extension can be safely called multiple times.
- /// The instance.
- public static OpenIddictCoreBuilder UseQuartz(
- this OpenIddictCoreBuilder builder, Action configuration)
- {
- ArgumentNullException.ThrowIfNull(builder);
- ArgumentNullException.ThrowIfNull(configuration);
-
- configuration(builder.UseQuartz());
-
- return builder;
- }
-}
diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs b/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs
deleted file mode 100644
index c9e305ac..00000000
--- a/src/OpenIddict.Quartz/OpenIddictQuartzJob.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- * See https://github.com/openiddict/openiddict-core for more information concerning
- * the license and the contributors participating to this project.
- */
-
-using System.ComponentModel;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Options;
-
-namespace OpenIddict.Quartz;
-
-///
-/// Represents a Quartz.NET job performing scheduled tasks for OpenIddict.
-///
-[DisallowConcurrentExecution, EditorBrowsable(EditorBrowsableState.Advanced)]
-public sealed class OpenIddictQuartzJob : IJob
-{
- private readonly IServiceProvider _provider;
-
-#if !NET
- ///
- /// Creates a new instance of the class.
- ///
- public OpenIddictQuartzJob() => throw new InvalidOperationException(SR.GetResourceString(SR.ID0082));
-#endif
-
- ///
- /// Creates a new instance of the class.
- ///
- /// The service provider.
- public OpenIddictQuartzJob(IServiceProvider provider)
- => _provider = provider ?? throw new ArgumentNullException(nameof(provider));
-
- ///
- /// Gets the default identity assigned to this job.
- ///
- public static JobKey Identity { get; } = new JobKey(
- name: SR.GetResourceString(SR.ID8003),
- group: SR.GetResourceString(SR.ID8005));
-
- ///
-#if NET
- public async ValueTask Execute(IJobExecutionContext context, CancellationToken cancellationToken = default)
-#else
- public async Task Execute(IJobExecutionContext context)
-#endif
- {
- ArgumentNullException.ThrowIfNull(context);
-
- List? exceptions = null;
-
- await using var scope = _provider.CreateAsyncScope();
-
- var options = scope.ServiceProvider.GetRequiredService>().CurrentValue;
-
- // Important: since authorizations that still have tokens attached are never
- // pruned, the tokens MUST be deleted before deleting the authorizations.
-
- if (!options.DisableTokenPruning)
- {
- var manager = scope.ServiceProvider.GetService()
- ?? throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278)))
- {
- RefireImmediately = false,
- UnscheduleAllTriggers = true,
- UnscheduleFiringTrigger = true
- };
-
- var threshold = options.TimeProvider.GetUtcNow() - options.MinimumTokenLifespan;
-
- try
- {
- await manager.PruneAsync(threshold, context.CancellationToken);
- }
-
- // OperationCanceledExceptions are typically thrown when the host is about to shut down.
- // To allow the host to shut down as fast as possible, this exception type is special-cased
- // to prevent further processing in this job and inform Quartz.NET it shouldn't be refired.
- catch (OperationCanceledException exception) when (context.CancellationToken.IsCancellationRequested)
- {
- throw new JobExecutionException(exception)
- {
- RefireImmediately = false
- };
- }
-
- // AggregateExceptions are generally thrown by the manager itself when one or multiple exception(s)
- // occurred while trying to prune the entities. In this case, add the inner exceptions to the collection.
- catch (AggregateException exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: exception.InnerExceptions.Count);
- exceptions.AddRange(exception.InnerExceptions);
- }
-
- // Other non-fatal exceptions are assumed to be transient and are added to the exceptions collection
- // to be re-thrown later (typically, at the very end of this job, as an AggregateException).
- catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: 1);
- exceptions.Add(exception);
- }
- }
-
- if (!options.DisableAuthorizationPruning)
- {
- var manager = scope.ServiceProvider.GetService()
- ?? throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278)))
- {
- RefireImmediately = false,
- UnscheduleAllTriggers = true,
- UnscheduleFiringTrigger = true
- };
-
- var threshold = options.TimeProvider.GetUtcNow() - options.MinimumAuthorizationLifespan;
-
- try
- {
- await manager.PruneAsync(threshold, context.CancellationToken);
- }
-
- // OperationCanceledExceptions are typically thrown when the host is about to shut down.
- // To allow the host to shut down as fast as possible, this exception type is special-cased
- // to prevent further processing in this job and inform Quartz.NET it shouldn't be refired.
- catch (OperationCanceledException exception) when (context.CancellationToken.IsCancellationRequested)
- {
- throw new JobExecutionException(exception)
- {
- RefireImmediately = false
- };
- }
-
- // AggregateExceptions are generally thrown by the manager itself when one or multiple exception(s)
- // occurred while trying to prune the entities. In this case, add the inner exceptions to the collection.
- catch (AggregateException exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: exception.InnerExceptions.Count);
- exceptions.AddRange(exception.InnerExceptions);
- }
-
- // Other non-fatal exceptions are assumed to be transient and are added to the exceptions collection
- // to be re-thrown later (typically, at the very end of this job, as an AggregateException).
- catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: 1);
- exceptions.Add(exception);
- }
- }
-
- // Important: since sessions that still have tokens attached are never
- // pruned, the tokens MUST be deleted before deleting the sessions.
-
- if (!options.DisableSessionPruning)
- {
- var manager = scope.ServiceProvider.GetService()
- ?? throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278)))
- {
- RefireImmediately = false,
- UnscheduleAllTriggers = true,
- UnscheduleFiringTrigger = true
- };
-
- var threshold = options.TimeProvider.GetUtcNow() - options.MinimumSessionLifespan;
-
- try
- {
- await manager.PruneAsync(threshold, context.CancellationToken);
- }
-
- // OperationCanceledExceptions are typically thrown when the host is about to shut down.
- // To allow the host to shut down as fast as possible, this exception type is special-cased
- // to prevent further processing in this job and inform Quartz.NET it shouldn't be refired.
- catch (OperationCanceledException exception) when (context.CancellationToken.IsCancellationRequested)
- {
- throw new JobExecutionException(exception)
- {
- RefireImmediately = false
- };
- }
-
- // AggregateExceptions are generally thrown by the manager itself when one or multiple exception(s)
- // occurred while trying to prune the entities. In this case, add the inner exceptions to the collection.
- catch (AggregateException exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: exception.InnerExceptions.Count);
- exceptions.AddRange(exception.InnerExceptions);
- }
-
- // Other non-fatal exceptions are assumed to be transient and are added to the exceptions collection
- // to be re-thrown later (typically, at the very end of this job, as an AggregateException).
- catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
- {
- exceptions ??= new List(capacity: 1);
- exceptions.Add(exception);
- }
- }
-
- if (exceptions is { Count: > 0 })
- {
- throw new JobExecutionException(new AggregateException(exceptions))
- {
- // Only refire the job if the maximum refire count set in the options wasn't reached.
- RefireImmediately = context.RefireCount < options.MaximumRefireCount
- };
- }
- }
-}
diff --git a/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs b/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs
deleted file mode 100644
index 57539a24..00000000
--- a/src/OpenIddict.Quartz/OpenIddictQuartzOptions.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- * See https://github.com/openiddict/openiddict-core for more information concerning
- * the license and the contributors participating to this project.
- */
-
-namespace OpenIddict.Quartz;
-
-///
-/// Provides various settings needed to configure the OpenIddict Quartz.NET integration.
-///
-public sealed class OpenIddictQuartzOptions
-{
- ///
- /// Gets or sets a boolean indicating whether authorizations pruning should be disabled.
- ///
- public bool DisableAuthorizationPruning { get; set; }
-
- ///
- /// Gets or sets a boolean indicating whether sessions pruning should be disabled.
- ///
- public bool DisableSessionPruning { get; set; }
-
- ///
- /// Gets or sets a boolean indicating whether tokens pruning should be disabled.
- ///
- public bool DisableTokenPruning { get; set; }
-
- ///
- /// Gets or sets the number of times a failed Quartz.NET job can be retried.
- /// By default, failed jobs are automatically retried twice after the initial failure.
- ///
- public int MaximumRefireCount { get; set; } = 2;
-
- ///
- /// Gets or sets the minimum lifespan authorizations must have to be pruned.
- /// By default, this value is set to 14 days and cannot be less than 10 minutes.
- ///
- public TimeSpan MinimumAuthorizationLifespan { get; set; } = TimeSpan.FromDays(14);
-
- ///
- /// Gets or sets the minimum lifespan sessions must have to be pruned.
- /// By default, this value is set to 14 days and cannot be less than 10 minutes.
- ///
- public TimeSpan MinimumSessionLifespan { get; set; } = TimeSpan.FromDays(14);
-
- ///
- /// Gets or sets the minimum lifespan tokens must have to be pruned.
- /// By default, this value is set to 14 days and cannot be less than 10 minutes.
- ///
- public TimeSpan MinimumTokenLifespan { get; set; } = TimeSpan.FromDays(14);
-
- ///
- /// Gets or sets the time provider.
- ///
- ///
- /// 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.Core.Tests/OpenIddict.Core.Tests.csproj b/test/OpenIddict.Core.Tests/OpenIddict.Core.Tests.csproj
index 9856eda4..cb436349 100644
--- a/test/OpenIddict.Core.Tests/OpenIddict.Core.Tests.csproj
+++ b/test/OpenIddict.Core.Tests/OpenIddict.Core.Tests.csproj
@@ -13,6 +13,10 @@
+
+
+
+
diff --git a/test/OpenIddict.Core.Tests/OpenIddictCoreBackgroundServiceTests.cs b/test/OpenIddict.Core.Tests/OpenIddictCoreBackgroundServiceTests.cs
new file mode 100644
index 00000000..7e5a0675
--- /dev/null
+++ b/test/OpenIddict.Core.Tests/OpenIddictCoreBackgroundServiceTests.cs
@@ -0,0 +1,861 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ * See https://github.com/openiddict/openiddict-core for more information concerning
+ * the license and the contributors participating to this project.
+ */
+
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using Moq;
+using Xunit;
+
+#if NET
+using Microsoft.Extensions.Time.Testing;
+#endif
+
+namespace OpenIddict.Core.Tests;
+
+public class OpenIddictCoreBackgroundServiceTests
+{
+ [Theory]
+ [InlineData("logger")]
+ [InlineData("options")]
+ [InlineData("provider")]
+ public void Constructor_ThrowsAnExceptionForNullDependencies(string parameter)
+ {
+ // Act and assert
+ var exception = Assert.Throws(() => new OpenIddictCoreBackgroundService(
+ parameter is "logger" ? null! : Mock.Of>(),
+ parameter is "options" ? null! : Mock.Of>(),
+ parameter is "provider" ? null! : Mock.Of()));
+
+ Assert.Equal(parameter, exception.ParamName);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_StopsWhenAllPruningIsDisabled()
+ {
+ // Arrange
+ var options = new OpenIddictCoreOptions
+ {
+ DisableAutomaticAuthorizationPruning = true,
+ DisableAutomaticSessionPruning = true,
+ DisableAutomaticTokenPruning = true
+ };
+ var factory = new Mock();
+ var provider = Mock.Of(provider => provider.GetService(typeof(IServiceScopeFactory)) == factory.Object);
+ var monitor = Mock.Of>(monitor => monitor.CurrentValue == options);
+ using var service = new OpenIddictCoreBackgroundService(
+ Mock.Of>(), monitor, provider);
+
+ // Act
+ await service.StartAsync(CancellationToken.None);
+ await service.ExecuteTask!;
+
+ // Assert
+ factory.Verify(factory => factory.CreateScope(), Times.Never());
+ }
+
+#if NET
+ [Fact]
+ public async Task ExecuteAsync_UsesAndDisposesServiceScope()
+ {
+ // Arrange
+ var clock = new Mock { CallBase = true };
+ var timer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ clock.Setup(clock => clock.CreateTimer(It.IsAny(), It.IsAny