Browse Source

Bump the .NET SDK to 7.0.100-preview.2.22153.17 and modernize the code base

pull/1409/head
Kévin Chalet 4 years ago
parent
commit
62f3e6ff85
  1. 7
      global.json
  2. 7
      sandbox/OpenIddict.Sandbox.AspNetCore.Server/Helpers/AsyncEnumerableExtensions.cs
  3. 12
      shared/OpenIddict.Extensions/Helpers/OpenIddictHelpers.cs
  4. 4
      src/OpenIddict.Abstractions/OpenIddictBuilder.cs
  5. 23
      src/OpenIddict.Abstractions/OpenIddictExtensions.cs
  6. 26
      src/OpenIddict.Abstractions/Primitives/OpenIddictConverter.cs
  7. 400
      src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs
  8. 37
      src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs
  9. 39
      src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs
  10. 11
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreBuilder.cs
  11. 21
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreConfiguration.cs
  12. 19
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreExtensions.cs
  13. 12
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandler.cs
  14. 50
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlerFilters.cs
  15. 12
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.Authentication.cs
  16. 156
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
  17. 28
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHelpers.cs
  18. 11
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs
  19. 16
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs
  20. 19
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpExtensions.cs
  21. 14
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlerFilters.cs
  22. 12
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Exchange.cs
  23. 24
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Userinfo.cs
  24. 86
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  25. 153
      src/OpenIddict.Client/OpenIddictClientBuilder.cs
  26. 7
      src/OpenIddict.Client/OpenIddictClientConfiguration.cs
  27. 13
      src/OpenIddict.Client/OpenIddictClientDispatcher.cs
  28. 4
      src/OpenIddict.Client/OpenIddictClientEvents.cs
  29. 19
      src/OpenIddict.Client/OpenIddictClientExtensions.cs
  30. 6
      src/OpenIddict.Client/OpenIddictClientFactory.cs
  31. 7
      src/OpenIddict.Client/OpenIddictClientHandler.cs
  32. 65
      src/OpenIddict.Client/OpenIddictClientHandlerDescriptor.cs
  33. 209
      src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs
  34. 76
      src/OpenIddict.Client/OpenIddictClientHandlers.Authentication.cs
  35. 84
      src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs
  36. 7
      src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs
  37. 48
      src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs
  38. 14
      src/OpenIddict.Client/OpenIddictClientHandlers.Userinfo.cs
  39. 436
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  40. 14
      src/OpenIddict.Client/OpenIddictClientHelpers.cs
  41. 2
      src/OpenIddict.Client/OpenIddictClientOptions.cs
  42. 5
      src/OpenIddict.Client/OpenIddictClientRetriever.cs
  43. 37
      src/OpenIddict.Client/OpenIddictClientService.cs
  44. 47
      src/OpenIddict.Core/Caches/OpenIddictApplicationCache.cs
  45. 43
      src/OpenIddict.Core/Caches/OpenIddictAuthorizationCache.cs
  46. 49
      src/OpenIddict.Core/Caches/OpenIddictScopeCache.cs
  47. 47
      src/OpenIddict.Core/Caches/OpenIddictTokenCache.cs
  48. 330
      src/OpenIddict.Core/Managers/OpenIddictApplicationManager.cs
  49. 267
      src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs
  50. 271
      src/OpenIddict.Core/Managers/OpenIddictScopeManager.cs
  51. 316
      src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs
  52. 123
      src/OpenIddict.Core/OpenIddictCoreBuilder.cs
  53. 19
      src/OpenIddict.Core/OpenIddictCoreExtensions.cs
  54. 2
      src/OpenIddict.Core/Resolvers/OpenIddictApplicationStoreResolver.cs
  55. 2
      src/OpenIddict.Core/Resolvers/OpenIddictAuthorizationStoreResolver.cs
  56. 2
      src/OpenIddict.Core/Resolvers/OpenIddictScopeStoreResolver.cs
  57. 2
      src/OpenIddict.Core/Resolvers/OpenIddictTokenStoreResolver.cs
  58. 18
      src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkBuilder.cs
  59. 19
      src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkExtensions.cs
  60. 14
      src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkHelpers.cs
  61. 6
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkApplicationStoreResolver.cs
  62. 6
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkAuthorizationStoreResolver.cs
  63. 6
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkScopeStoreResolver.cs
  64. 6
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkTokenStoreResolver.cs
  65. 273
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkApplicationStore.cs
  66. 206
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkAuthorizationStore.cs
  67. 205
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkScopeStore.cs
  68. 284
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs
  69. 7
      src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreApplicationConfiguration.cs
  70. 7
      src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreAuthorizationConfiguration.cs
  71. 7
      src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreScopeConfiguration.cs
  72. 7
      src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreTokenConfiguration.cs
  73. 18
      src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreBuilder.cs
  74. 12
      src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreCustomizer.cs
  75. 19
      src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreExtensions.cs
  76. 29
      src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreHelpers.cs
  77. 6
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreApplicationStoreResolver.cs
  78. 6
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreAuthorizationStoreResolver.cs
  79. 6
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreScopeStoreResolver.cs
  80. 6
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreTokenStoreResolver.cs
  81. 279
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreApplicationStore.cs
  82. 204
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreAuthorizationStore.cs
  83. 209
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreScopeStore.cs
  84. 286
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreTokenStore.cs
  85. 18
      src/OpenIddict.MongoDb/OpenIddictMongoDbBuilder.cs
  86. 10
      src/OpenIddict.MongoDb/OpenIddictMongoDbContext.cs
  87. 19
      src/OpenIddict.MongoDb/OpenIddictMongoDbExtensions.cs
  88. 18
      src/OpenIddict.MongoDb/OpenIddictMongoDbHelpers.cs
  89. 2
      src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbApplicationStoreResolver.cs
  90. 2
      src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbAuthorizationStoreResolver.cs
  91. 2
      src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbScopeStoreResolver.cs
  92. 2
      src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbTokenStoreResolver.cs
  93. 295
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbApplicationStore.cs
  94. 199
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbAuthorizationStore.cs
  95. 206
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbScopeStore.cs
  96. 276
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbTokenStore.cs
  97. 11
      src/OpenIddict.Quartz/OpenIddictQuartzBuilder.cs
  98. 7
      src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs
  99. 19
      src/OpenIddict.Quartz/OpenIddictQuartzExtensions.cs
  100. 9
      src/OpenIddict.Quartz/OpenIddictQuartzJob.cs

7
global.json

@ -1,16 +1,17 @@
{ {
"sdk": { "sdk": {
"version": "6.0.100" "version": "7.0.100-preview.2.22153.17"
}, },
"tools": { "tools": {
"dotnet": "6.0.100", "dotnet": "7.0.100-preview.2.22153.17",
"runtimes": { "runtimes": {
"aspnetcore": [ "aspnetcore": [
"2.1.28", "2.1.28",
"3.1.16", "3.1.16",
"5.0.7" "5.0.7",
"6.0.0"
] ]
} }
}, },

7
sandbox/OpenIddict.Sandbox.AspNetCore.Server/Helpers/AsyncEnumerableExtensions.cs

@ -2,13 +2,8 @@
public static class AsyncEnumerableExtensions public static class AsyncEnumerableExtensions
{ {
public static Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source) public static Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source!!)
{ {
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return ExecuteAsync(); return ExecuteAsync();
async Task<List<T>> ExecuteAsync() async Task<List<T>> ExecuteAsync()

12
shared/OpenIddict.Extensions/Helpers/OpenIddictHelpers.cs

@ -20,18 +20,8 @@ internal static class OpenIddictHelpers
/// <param name="type">The type to introspect.</param> /// <param name="type">The type to introspect.</param>
/// <param name="definition">The generic type definition.</param> /// <param name="definition">The generic type definition.</param>
/// <returns>A <see cref="Type"/> instance if the base type was found, <c>null</c> otherwise.</returns> /// <returns>A <see cref="Type"/> instance if the base type was found, <c>null</c> otherwise.</returns>
public static IEnumerable<Type> FindGenericBaseTypes(Type type, Type definition) public static IEnumerable<Type> FindGenericBaseTypes(Type type!!, Type definition!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (definition is null)
{
throw new ArgumentNullException(nameof(definition));
}
if (!definition.IsGenericTypeDefinition) if (!definition.IsGenericTypeDefinition)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0263), nameof(definition)); throw new ArgumentException(SR.GetResourceString(SR.ID0263), nameof(definition));

4
src/OpenIddict.Abstractions/OpenIddictBuilder.cs

@ -17,8 +17,8 @@ public class OpenIddictBuilder
/// Initializes a new instance of <see cref="OpenIddictBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictBuilder(IServiceCollection services) public OpenIddictBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.

23
src/OpenIddict.Abstractions/OpenIddictExtensions.cs

@ -17,15 +17,8 @@ public static class OpenIddictExtensions
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictBuilder"/>.</returns>
public static OpenIddictBuilder AddOpenIddict(this IServiceCollection services) public static OpenIddictBuilder AddOpenIddict(this IServiceCollection services!!)
{ => new OpenIddictBuilder(services);
if (services is null)
{
throw new ArgumentNullException(nameof(services));
}
return new OpenIddictBuilder(services);
}
/// <summary> /// <summary>
/// Provides a common entry point for registering the OpenIddict services. /// Provides a common entry point for registering the OpenIddict services.
@ -34,18 +27,8 @@ public static class OpenIddictExtensions
/// <param name="configuration">The configuration delegate used to register new services.</param> /// <param name="configuration">The configuration delegate used to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="IServiceCollection"/>.</returns> /// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddOpenIddict(this IServiceCollection services, Action<OpenIddictBuilder> configuration) public static IServiceCollection AddOpenIddict(this IServiceCollection services!!, Action<OpenIddictBuilder> configuration!!)
{ {
if (services is null)
{
throw new ArgumentNullException(nameof(services));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(services.AddOpenIddict()); configuration(services.AddOpenIddict());
return services; return services;

26
src/OpenIddict.Abstractions/Primitives/OpenIddictConverter.cs

@ -19,13 +19,8 @@ public class OpenIddictConverter : JsonConverter<OpenIddictMessage>
/// </summary> /// </summary>
/// <param name="typeToConvert">The type to convert.</param> /// <param name="typeToConvert">The type to convert.</param>
/// <returns><c>true</c> if the type is supported, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the type is supported, <c>false</c> otherwise.</returns>
public override bool CanConvert(Type typeToConvert) public override bool CanConvert(Type typeToConvert!!)
{ {
if (typeToConvert is null)
{
throw new ArgumentNullException(nameof(typeToConvert));
}
return typeToConvert == typeof(OpenIddictMessage) || return typeToConvert == typeof(OpenIddictMessage) ||
typeToConvert == typeof(OpenIddictRequest) || typeToConvert == typeof(OpenIddictRequest) ||
typeToConvert == typeof(OpenIddictResponse); typeToConvert == typeof(OpenIddictResponse);
@ -38,13 +33,8 @@ public class OpenIddictConverter : JsonConverter<OpenIddictMessage>
/// <param name="typeToConvert">The type of the deserialized instance.</param> /// <param name="typeToConvert">The type of the deserialized instance.</param>
/// <param name="options">The JSON serializer options.</param> /// <param name="options">The JSON serializer options.</param>
/// <returns>The deserialized <see cref="OpenIddictMessage"/> instance.</returns> /// <returns>The deserialized <see cref="OpenIddictMessage"/> instance.</returns>
public override OpenIddictMessage Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override OpenIddictMessage Read(ref Utf8JsonReader reader, Type typeToConvert!!, JsonSerializerOptions options)
{ {
if (typeToConvert is null)
{
throw new ArgumentNullException(nameof(typeToConvert));
}
using var document = JsonDocument.ParseValue(ref reader); using var document = JsonDocument.ParseValue(ref reader);
return typeToConvert == typeof(OpenIddictMessage) ? new OpenIddictMessage(document.RootElement.Clone()) : return typeToConvert == typeof(OpenIddictMessage) ? new OpenIddictMessage(document.RootElement.Clone()) :
@ -59,18 +49,8 @@ public class OpenIddictConverter : JsonConverter<OpenIddictMessage>
/// <param name="writer">The JSON writer.</param> /// <param name="writer">The JSON writer.</param>
/// <param name="value">The instance.</param> /// <param name="value">The instance.</param>
/// <param name="options">The JSON serializer options.</param> /// <param name="options">The JSON serializer options.</param>
public override void Write(Utf8JsonWriter writer, OpenIddictMessage value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer!!, OpenIddictMessage value!!, JsonSerializerOptions options)
{ {
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
value.WriteTo(writer); value.WriteTo(writer);
} }
} }

400
src/OpenIddict.Abstractions/Primitives/OpenIddictExtensions.cs

@ -25,70 +25,37 @@ public static class OpenIddictExtensions
/// Extracts the authentication context class values from an <see cref="OpenIddictRequest"/>. /// Extracts the authentication context class values from an <see cref="OpenIddictRequest"/>.
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
public static ImmutableArray<string> GetAcrValues(this OpenIddictRequest request) public static ImmutableArray<string> GetAcrValues(this OpenIddictRequest request!!)
{ => GetValues(request.AcrValues, Separators.Space);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return GetValues(request.AcrValues, Separators.Space);
}
/// <summary> /// <summary>
/// Extracts the prompt values from an <see cref="OpenIddictRequest"/>. /// Extracts the prompt values from an <see cref="OpenIddictRequest"/>.
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
public static ImmutableArray<string> GetPrompts(this OpenIddictRequest request) public static ImmutableArray<string> GetPrompts(this OpenIddictRequest request!!)
{ => GetValues(request.Prompt, Separators.Space);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return GetValues(request.Prompt, Separators.Space);
}
/// <summary> /// <summary>
/// Extracts the response types from an <see cref="OpenIddictRequest"/>. /// Extracts the response types from an <see cref="OpenIddictRequest"/>.
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
public static ImmutableArray<string> GetResponseTypes(this OpenIddictRequest request) public static ImmutableArray<string> GetResponseTypes(this OpenIddictRequest request!!)
{ => GetValues(request.ResponseType, Separators.Space);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return GetValues(request.ResponseType, Separators.Space);
}
/// <summary> /// <summary>
/// Extracts the scopes from an <see cref="OpenIddictRequest"/>. /// Extracts the scopes from an <see cref="OpenIddictRequest"/>.
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
public static ImmutableArray<string> GetScopes(this OpenIddictRequest request) public static ImmutableArray<string> GetScopes(this OpenIddictRequest request!!)
{ => GetValues(request.Scope, Separators.Space);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return GetValues(request.Scope, Separators.Space);
}
/// <summary> /// <summary>
/// Determines whether the requested authentication context class values contain the specified item. /// Determines whether the requested authentication context class values contain the specified item.
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <param name="value">The component to look for in the parameter.</param> /// <param name="value">The component to look for in the parameter.</param>
public static bool HasAcrValue(this OpenIddictRequest request, string value) public static bool HasAcrValue(this OpenIddictRequest request!!, string value)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(value)) if (string.IsNullOrEmpty(value))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0177), nameof(value)); throw new ArgumentException(SR.GetResourceString(SR.ID0177), nameof(value));
@ -102,13 +69,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <param name="prompt">The component to look for in the parameter.</param> /// <param name="prompt">The component to look for in the parameter.</param>
public static bool HasPrompt(this OpenIddictRequest request, string prompt) public static bool HasPrompt(this OpenIddictRequest request!!, string prompt)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(prompt)) if (string.IsNullOrEmpty(prompt))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0178), nameof(prompt)); throw new ArgumentException(SR.GetResourceString(SR.ID0178), nameof(prompt));
@ -122,13 +84,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <param name="type">The component to look for in the parameter.</param> /// <param name="type">The component to look for in the parameter.</param>
public static bool HasResponseType(this OpenIddictRequest request, string type) public static bool HasResponseType(this OpenIddictRequest request!!, string type)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0179), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0179), nameof(type));
@ -142,13 +99,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <param name="scope">The component to look for in the parameter.</param> /// <param name="scope">The component to look for in the parameter.</param>
public static bool HasScope(this OpenIddictRequest request, string scope) public static bool HasScope(this OpenIddictRequest request!!, string scope)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(scope)) if (string.IsNullOrEmpty(scope))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0180), nameof(scope)); throw new ArgumentException(SR.GetResourceString(SR.ID0180), nameof(scope));
@ -163,13 +115,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a response_type=none request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a response_type=none request, <c>false</c> otherwise.</returns>
public static bool IsNoneFlow(this OpenIddictRequest request) public static bool IsNoneFlow(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(request.ResponseType)) if (string.IsNullOrEmpty(request.ResponseType))
{ {
return false; return false;
@ -190,13 +137,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a code flow request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a code flow request, <c>false</c> otherwise.</returns>
public static bool IsAuthorizationCodeFlow(this OpenIddictRequest request) public static bool IsAuthorizationCodeFlow(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(request.ResponseType)) if (string.IsNullOrEmpty(request.ResponseType))
{ {
return false; return false;
@ -218,13 +160,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is an implicit flow request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is an implicit flow request, <c>false</c> otherwise.</returns>
public static bool IsImplicitFlow(this OpenIddictRequest request) public static bool IsImplicitFlow(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(request.ResponseType)) if (string.IsNullOrEmpty(request.ResponseType))
{ {
return false; return false;
@ -272,13 +209,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is an hybrid flow request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is an hybrid flow request, <c>false</c> otherwise.</returns>
public static bool IsHybridFlow(this OpenIddictRequest request) public static bool IsHybridFlow(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.IsNullOrEmpty(request.ResponseType)) if (string.IsNullOrEmpty(request.ResponseType))
{ {
return false; return false;
@ -339,13 +271,8 @@ public static class OpenIddictExtensions
/// <c>true</c> if the request specified the fragment response mode or if /// <c>true</c> if the request specified the fragment response mode or if
/// it's the default value for the requested flow, <c>false</c> otherwise. /// it's the default value for the requested flow, <c>false</c> otherwise.
/// </returns> /// </returns>
public static bool IsFragmentResponseMode(this OpenIddictRequest request) public static bool IsFragmentResponseMode(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.Equals(request.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal)) if (string.Equals(request.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal))
{ {
return true; return true;
@ -372,13 +299,8 @@ public static class OpenIddictExtensions
/// <c>true</c> if the request specified the query response mode or if /// <c>true</c> if the request specified the query response mode or if
/// it's the default value for the requested flow, <c>false</c> otherwise. /// it's the default value for the requested flow, <c>false</c> otherwise.
/// </returns> /// </returns>
public static bool IsQueryResponseMode(this OpenIddictRequest request) public static bool IsQueryResponseMode(this OpenIddictRequest request!!)
{ {
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
if (string.Equals(request.ResponseMode, ResponseModes.Query, StringComparison.Ordinal)) if (string.Equals(request.ResponseMode, ResponseModes.Query, StringComparison.Ordinal))
{ {
return true; return true;
@ -404,15 +326,8 @@ public static class OpenIddictExtensions
/// <c>true</c> if the request specified the form post response mode or if /// <c>true</c> if the request specified the form post response mode or if
/// it's the default value for the requested flow, <c>false</c> otherwise. /// it's the default value for the requested flow, <c>false</c> otherwise.
/// </returns> /// </returns>
public static bool IsFormPostResponseMode(this OpenIddictRequest request) public static bool IsFormPostResponseMode(this OpenIddictRequest request!!)
{ => string.Equals(request.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Determines whether the "grant_type" parameter corresponds to the authorization code grant. /// Determines whether the "grant_type" parameter corresponds to the authorization code grant.
@ -420,15 +335,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a code grant request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a code grant request, <c>false</c> otherwise.</returns>
public static bool IsAuthorizationCodeGrantType(this OpenIddictRequest request) public static bool IsAuthorizationCodeGrantType(this OpenIddictRequest request!!)
{ => string.Equals(request.GrantType, GrantTypes.AuthorizationCode, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.GrantType, GrantTypes.AuthorizationCode, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Determines whether the "grant_type" parameter corresponds to the client credentials grant. /// Determines whether the "grant_type" parameter corresponds to the client credentials grant.
@ -436,15 +344,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a client credentials grant request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a client credentials grant request, <c>false</c> otherwise.</returns>
public static bool IsClientCredentialsGrantType(this OpenIddictRequest request) public static bool IsClientCredentialsGrantType(this OpenIddictRequest request!!)
{ => string.Equals(request.GrantType, GrantTypes.ClientCredentials, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.GrantType, GrantTypes.ClientCredentials, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Determines whether the "grant_type" parameter corresponds to the device code grant. /// Determines whether the "grant_type" parameter corresponds to the device code grant.
@ -452,15 +353,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a device code grant request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a device code grant request, <c>false</c> otherwise.</returns>
public static bool IsDeviceCodeGrantType(this OpenIddictRequest request) public static bool IsDeviceCodeGrantType(this OpenIddictRequest request!!)
{ => string.Equals(request.GrantType, GrantTypes.DeviceCode, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.GrantType, GrantTypes.DeviceCode, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Determines whether the "grant_type" parameter corresponds to the password grant. /// Determines whether the "grant_type" parameter corresponds to the password grant.
@ -468,15 +362,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a password grant request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a password grant request, <c>false</c> otherwise.</returns>
public static bool IsPasswordGrantType(this OpenIddictRequest request) public static bool IsPasswordGrantType(this OpenIddictRequest request!!)
{ => string.Equals(request.GrantType, GrantTypes.Password, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.GrantType, GrantTypes.Password, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Determines whether the "grant_type" parameter corresponds to the refresh token grant. /// Determines whether the "grant_type" parameter corresponds to the refresh token grant.
@ -484,28 +371,16 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param> /// <param name="request">The <see cref="OpenIddictRequest"/> instance.</param>
/// <returns><c>true</c> if the request is a refresh token grant request, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the request is a refresh token grant request, <c>false</c> otherwise.</returns>
public static bool IsRefreshTokenGrantType(this OpenIddictRequest request) public static bool IsRefreshTokenGrantType(this OpenIddictRequest request!!)
{ => string.Equals(request.GrantType, GrantTypes.RefreshToken, StringComparison.Ordinal);
if (request is null)
{
throw new ArgumentNullException(nameof(request));
}
return string.Equals(request.GrantType, GrantTypes.RefreshToken, StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// Gets the destinations associated with a claim. /// Gets the destinations associated with a claim.
/// </summary> /// </summary>
/// <param name="claim">The <see cref="Claim"/> instance.</param> /// <param name="claim">The <see cref="Claim"/> instance.</param>
/// <returns>The destinations associated with the claim.</returns> /// <returns>The destinations associated with the claim.</returns>
public static ImmutableArray<string> GetDestinations(this Claim claim) public static ImmutableArray<string> GetDestinations(this Claim claim!!)
{ {
if (claim is null)
{
throw new ArgumentNullException(nameof(claim));
}
claim.Properties.TryGetValue(Properties.Destinations, out string? destinations); claim.Properties.TryGetValue(Properties.Destinations, out string? destinations);
if (string.IsNullOrEmpty(destinations)) if (string.IsNullOrEmpty(destinations))
@ -535,13 +410,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="claim">The <see cref="Claim"/> instance.</param> /// <param name="claim">The <see cref="Claim"/> instance.</param>
/// <param name="destination">The required destination.</param> /// <param name="destination">The required destination.</param>
public static bool HasDestination(this Claim claim, string destination) public static bool HasDestination(this Claim claim!!, string destination)
{ {
if (claim is null)
{
throw new ArgumentNullException(nameof(claim));
}
if (string.IsNullOrEmpty(destination)) if (string.IsNullOrEmpty(destination))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0181), nameof(destination)); throw new ArgumentException(SR.GetResourceString(SR.ID0181), nameof(destination));
@ -573,13 +443,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="claim">The <see cref="Claim"/> instance.</param> /// <param name="claim">The <see cref="Claim"/> instance.</param>
/// <param name="destinations">The destinations.</param> /// <param name="destinations">The destinations.</param>
public static Claim SetDestinations(this Claim claim, ImmutableArray<string> destinations) public static Claim SetDestinations(this Claim claim!!, ImmutableArray<string> destinations)
{ {
if (claim is null)
{
throw new ArgumentNullException(nameof(claim));
}
if (destinations.IsDefaultOrEmpty) if (destinations.IsDefaultOrEmpty)
{ {
claim.Properties.Remove(Properties.Destinations); claim.Properties.Remove(Properties.Destinations);
@ -587,7 +452,7 @@ public static class OpenIddictExtensions
return claim; return claim;
} }
if (destinations.Any(destination => string.IsNullOrEmpty(destination))) if (destinations.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0182), nameof(destinations)); throw new ArgumentException(SR.GetResourceString(SR.ID0182), nameof(destinations));
} }
@ -635,13 +500,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="principal">The principal.</param> /// <param name="principal">The principal.</param>
/// <returns>The destinations, returned as a flattened dictionary.</returns> /// <returns>The destinations, returned as a flattened dictionary.</returns>
public static ImmutableDictionary<string, string[]> GetDestinations(this ClaimsPrincipal principal) public static ImmutableDictionary<string, string[]> GetDestinations(this ClaimsPrincipal principal!!)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
var builder = ImmutableDictionary.CreateBuilder<string, string[]>(StringComparer.Ordinal); var builder = ImmutableDictionary.CreateBuilder<string, string[]>(StringComparer.Ordinal);
foreach (var group in principal.Claims.GroupBy(claim => claim.Type)) foreach (var group in principal.Claims.GroupBy(claim => claim.Type))
@ -673,18 +533,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The principal.</param> /// <param name="principal">The principal.</param>
/// <param name="destinations">The destinations, as a flattened dictionary.</param> /// <param name="destinations">The destinations, as a flattened dictionary.</param>
/// <returns>The principal.</returns> /// <returns>The principal.</returns>
public static ClaimsPrincipal SetDestinations(this ClaimsPrincipal principal, ImmutableDictionary<string, string[]> destinations) public static ClaimsPrincipal SetDestinations(this ClaimsPrincipal principal!!, ImmutableDictionary<string, string[]> destinations!!)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (destinations is null)
{
throw new ArgumentNullException(nameof(destinations));
}
foreach (var destination in destinations) foreach (var destination in destinations)
{ {
foreach (var claim in principal.Claims.Where(claim => claim.Type == destination.Key)) foreach (var claim in principal.Claims.Where(claim => claim.Type == destination.Key))
@ -704,18 +554,8 @@ public static class OpenIddictExtensions
/// The delegate filtering the claims: return <c>true</c> /// The delegate filtering the claims: return <c>true</c>
/// to accept the claim, <c>false</c> to remove it. /// to accept the claim, <c>false</c> to remove it.
/// </param> /// </param>
public static ClaimsIdentity Clone(this ClaimsIdentity identity, Func<Claim, bool> filter) public static ClaimsIdentity Clone(this ClaimsIdentity identity!!, Func<Claim, bool> filter!!)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (filter is null)
{
throw new ArgumentNullException(nameof(filter));
}
var clone = identity.Clone(); var clone = identity.Clone();
// Note: make sure to call ToList() to avoid modifying // Note: make sure to call ToList() to avoid modifying
@ -744,18 +584,8 @@ public static class OpenIddictExtensions
/// The delegate filtering the claims: return <c>true</c> /// The delegate filtering the claims: return <c>true</c>
/// to accept the claim, <c>false</c> to remove it. /// to accept the claim, <c>false</c> to remove it.
/// </param> /// </param>
public static ClaimsPrincipal Clone(this ClaimsPrincipal principal, Func<Claim, bool> filter) public static ClaimsPrincipal Clone(this ClaimsPrincipal principal!!, Func<Claim, bool> filter!!)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (filter is null)
{
throw new ArgumentNullException(nameof(filter));
}
var clone = new ClaimsPrincipal(); var clone = new ClaimsPrincipal();
foreach (var identity in principal.Identities) foreach (var identity in principal.Identities)
@ -772,13 +602,8 @@ public static class OpenIddictExtensions
/// <param name="identity">The identity.</param> /// <param name="identity">The identity.</param>
/// <param name="type">The type associated with the claim.</param> /// <param name="type">The type associated with the claim.</param>
/// <param name="value">The value associated with the claim.</param> /// <param name="value">The value associated with the claim.</param>
public static ClaimsIdentity AddClaim(this ClaimsIdentity identity, string type, string value) public static ClaimsIdentity AddClaim(this ClaimsIdentity identity!!, string type, string value)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -800,13 +625,8 @@ public static class OpenIddictExtensions
/// <param name="type">The type associated with the claim.</param> /// <param name="type">The type associated with the claim.</param>
/// <param name="value">The value associated with the claim.</param> /// <param name="value">The value associated with the claim.</param>
/// <param name="destinations">The destinations associated with the claim.</param> /// <param name="destinations">The destinations associated with the claim.</param>
public static ClaimsIdentity AddClaim(this ClaimsIdentity identity, string type, string value, ImmutableArray<string> destinations) public static ClaimsIdentity AddClaim(this ClaimsIdentity identity!!, string type, string value, ImmutableArray<string> destinations)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -837,13 +657,8 @@ public static class OpenIddictExtensions
/// <param name="identity">The identity.</param> /// <param name="identity">The identity.</param>
/// <param name="type">The type associated with the claim.</param> /// <param name="type">The type associated with the claim.</param>
/// <returns>The claim value.</returns> /// <returns>The claim value.</returns>
public static string? GetClaim(this ClaimsIdentity identity, string type) public static string? GetClaim(this ClaimsIdentity identity!!, string type)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -858,13 +673,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The principal.</param> /// <param name="principal">The principal.</param>
/// <param name="type">The type associated with the claim.</param> /// <param name="type">The type associated with the claim.</param>
/// <returns>The claim value.</returns> /// <returns>The claim value.</returns>
public static string? GetClaim(this ClaimsPrincipal principal, string type) public static string? GetClaim(this ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -879,13 +689,8 @@ public static class OpenIddictExtensions
/// <param name="identity">The identity.</param> /// <param name="identity">The identity.</param>
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <returns>The claim values.</returns> /// <returns>The claim values.</returns>
public static ImmutableArray<string> GetClaims(this ClaimsIdentity identity, string type) public static ImmutableArray<string> GetClaims(this ClaimsIdentity identity!!, string type)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -900,13 +705,8 @@ public static class OpenIddictExtensions
/// <param name="identity">The claims identity.</param> /// <param name="identity">The claims identity.</param>
/// <param name="type">The claim type.</param> /// <param name="type">The claim type.</param>
/// <returns><c>true</c> if the identity contains at least one claim of the specified type.</returns> /// <returns><c>true</c> if the identity contains at least one claim of the specified type.</returns>
public static bool HasClaim(this ClaimsIdentity identity, string type) public static bool HasClaim(this ClaimsIdentity identity!!, string type)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -921,13 +721,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The principal.</param> /// <param name="principal">The principal.</param>
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <returns>The claim values.</returns> /// <returns>The claim values.</returns>
public static ImmutableArray<string> GetClaims(this ClaimsPrincipal principal, string type) public static ImmutableArray<string> GetClaims(this ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -942,13 +737,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="type">The claim type.</param> /// <param name="type">The claim type.</param>
/// <returns><c>true</c> if the principal contains at least one claim of the specified type.</returns> /// <returns><c>true</c> if the principal contains at least one claim of the specified type.</returns>
public static bool HasClaim(this ClaimsPrincipal principal, string type) public static bool HasClaim(this ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -963,13 +753,8 @@ public static class OpenIddictExtensions
/// <param name="identity">The identity.</param> /// <param name="identity">The identity.</param>
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsIdentity RemoveClaims(this ClaimsIdentity identity, string type) public static ClaimsIdentity RemoveClaims(this ClaimsIdentity identity!!, string type)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -989,13 +774,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The principal.</param> /// <param name="principal">The principal.</param>
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsPrincipal RemoveClaims(this ClaimsPrincipal principal, string type) public static ClaimsPrincipal RemoveClaims(this ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -1019,13 +799,8 @@ public static class OpenIddictExtensions
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <param name="value">The claim value.</param> /// <param name="value">The claim value.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsIdentity SetClaims(this ClaimsIdentity identity, string type, string? value) public static ClaimsIdentity SetClaims(this ClaimsIdentity identity!!, string type, string? value)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -1048,13 +823,8 @@ public static class OpenIddictExtensions
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <param name="value">The claim value.</param> /// <param name="value">The claim value.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsPrincipal SetClaim(this ClaimsPrincipal principal, string type, string? value) public static ClaimsPrincipal SetClaim(this ClaimsPrincipal principal!!, string type, string? value)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (principal.Identity is not ClaimsIdentity identity) if (principal.Identity is not ClaimsIdentity identity)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0286), nameof(principal)); throw new ArgumentException(SR.GetResourceString(SR.ID0286), nameof(principal));
@ -1082,13 +852,8 @@ public static class OpenIddictExtensions
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <param name="values">The claim values.</param> /// <param name="values">The claim values.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsIdentity SetClaims(this ClaimsIdentity identity, string type, ImmutableArray<string> values) public static ClaimsIdentity SetClaims(this ClaimsIdentity identity!!, string type, ImmutableArray<string> values)
{ {
if (identity is null)
{
throw new ArgumentNullException(nameof(identity));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0184), nameof(type));
@ -1111,13 +876,8 @@ public static class OpenIddictExtensions
/// <param name="type">The type associated with the claims.</param> /// <param name="type">The type associated with the claims.</param>
/// <param name="values">The claim values.</param> /// <param name="values">The claim values.</param>
/// <returns>The claims identity.</returns> /// <returns>The claims identity.</returns>
public static ClaimsPrincipal SetClaims(this ClaimsPrincipal principal, string type, ImmutableArray<string> values) public static ClaimsPrincipal SetClaims(this ClaimsPrincipal principal!!, string type, ImmutableArray<string> values)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (principal.Identity is not ClaimsIdentity identity) if (principal.Identity is not ClaimsIdentity identity)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0286), nameof(principal)); throw new ArgumentException(SR.GetResourceString(SR.ID0286), nameof(principal));
@ -1143,13 +903,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <returns>The creation date or <c>null</c> if the claim cannot be found.</returns> /// <returns>The creation date or <c>null</c> if the claim cannot be found.</returns>
public static DateTimeOffset? GetCreationDate(this ClaimsPrincipal principal) public static DateTimeOffset? GetCreationDate(this ClaimsPrincipal principal!!)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
var claim = principal.FindFirst(Claims.Private.CreationDate); var claim = principal.FindFirst(Claims.Private.CreationDate);
if (claim is null) if (claim is null)
{ {
@ -1169,13 +924,8 @@ public static class OpenIddictExtensions
/// </summary> /// </summary>
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <returns>The expiration date or <c>null</c> if the claim cannot be found.</returns> /// <returns>The expiration date or <c>null</c> if the claim cannot be found.</returns>
public static DateTimeOffset? GetExpirationDate(this ClaimsPrincipal principal) public static DateTimeOffset? GetExpirationDate(this ClaimsPrincipal principal!!)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
var claim = principal.FindFirst(Claims.Private.ExpirationDate); var claim = principal.FindFirst(Claims.Private.ExpirationDate);
if (claim is null) if (claim is null)
{ {
@ -1308,13 +1058,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="audience">The audience.</param> /// <param name="audience">The audience.</param>
/// <returns><c>true</c> if the principal contains the given audience.</returns> /// <returns><c>true</c> if the principal contains the given audience.</returns>
public static bool HasAudience(this ClaimsPrincipal principal, string audience) public static bool HasAudience(this ClaimsPrincipal principal!!, string audience)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(audience)) if (string.IsNullOrEmpty(audience))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0186), nameof(audience)); throw new ArgumentException(SR.GetResourceString(SR.ID0186), nameof(audience));
@ -1329,13 +1074,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="presenter">The presenter.</param> /// <param name="presenter">The presenter.</param>
/// <returns><c>true</c> if the principal contains the given presenter.</returns> /// <returns><c>true</c> if the principal contains the given presenter.</returns>
public static bool HasPresenter(this ClaimsPrincipal principal, string presenter) public static bool HasPresenter(this ClaimsPrincipal principal!!, string presenter)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(presenter)) if (string.IsNullOrEmpty(presenter))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0187), nameof(presenter)); throw new ArgumentException(SR.GetResourceString(SR.ID0187), nameof(presenter));
@ -1350,13 +1090,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="resource">The resource.</param> /// <param name="resource">The resource.</param>
/// <returns><c>true</c> if the principal contains the given resource.</returns> /// <returns><c>true</c> if the principal contains the given resource.</returns>
public static bool HasResource(this ClaimsPrincipal principal, string resource) public static bool HasResource(this ClaimsPrincipal principal!!, string resource)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(resource)) if (string.IsNullOrEmpty(resource))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
@ -1371,13 +1106,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="scope">The scope.</param> /// <param name="scope">The scope.</param>
/// <returns><c>true</c> if the principal contains the given scope.</returns> /// <returns><c>true</c> if the principal contains the given scope.</returns>
public static bool HasScope(this ClaimsPrincipal principal, string scope) public static bool HasScope(this ClaimsPrincipal principal!!, string scope)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(scope)) if (string.IsNullOrEmpty(scope))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0180), nameof(scope)); throw new ArgumentException(SR.GetResourceString(SR.ID0180), nameof(scope));
@ -1392,13 +1122,8 @@ public static class OpenIddictExtensions
/// <param name="principal">The claims principal.</param> /// <param name="principal">The claims principal.</param>
/// <param name="type">The token type.</param> /// <param name="type">The token type.</param>
/// <returns><c>true</c> if the token type matches the specified type.</returns> /// <returns><c>true</c> if the token type matches the specified type.</returns>
public static bool HasTokenType(this ClaimsPrincipal principal, string type) public static bool HasTokenType(this ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0188), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0188), nameof(type));
@ -1752,13 +1477,8 @@ public static class OpenIddictExtensions
return false; return false;
} }
private static TimeSpan? GetLifetime(ClaimsPrincipal principal, string type) private static TimeSpan? GetLifetime(ClaimsPrincipal principal!!, string type)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
var value = principal.GetClaim(type); var value = principal.GetClaim(type);
if (string.IsNullOrEmpty(value)) if (string.IsNullOrEmpty(value))
{ {

37
src/OpenIddict.Abstractions/Primitives/OpenIddictMessage.cs

@ -40,7 +40,7 @@ public class OpenIddictMessage
/// <remarks>Parameters with a null or empty key are always ignored.</remarks> /// <remarks>Parameters with a null or empty key are always ignored.</remarks>
public OpenIddictMessage(JsonElement parameters) public OpenIddictMessage(JsonElement parameters)
{ {
if (parameters.ValueKind != JsonValueKind.Object) if (parameters.ValueKind is not JsonValueKind.Object)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0189), nameof(parameters)); throw new ArgumentException(SR.GetResourceString(SR.ID0189), nameof(parameters));
} }
@ -69,13 +69,8 @@ public class OpenIddictMessage
/// </summary> /// </summary>
/// <param name="parameters">The message parameters.</param> /// <param name="parameters">The message parameters.</param>
/// <remarks>Parameters with a null or empty key are always ignored.</remarks> /// <remarks>Parameters with a null or empty key are always ignored.</remarks>
public OpenIddictMessage(IEnumerable<KeyValuePair<string, OpenIddictParameter>> parameters) public OpenIddictMessage(IEnumerable<KeyValuePair<string, OpenIddictParameter>> parameters!!)
{ {
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
// Ignore parameters whose name is null or empty. // Ignore parameters whose name is null or empty.
@ -93,13 +88,8 @@ public class OpenIddictMessage
/// </summary> /// </summary>
/// <param name="parameters">The message parameters.</param> /// <param name="parameters">The message parameters.</param>
/// <remarks>Parameters with a null or empty key are always ignored.</remarks> /// <remarks>Parameters with a null or empty key are always ignored.</remarks>
public OpenIddictMessage(IEnumerable<KeyValuePair<string, string?>> parameters) public OpenIddictMessage(IEnumerable<KeyValuePair<string, string?>> parameters!!)
{ {
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
foreach (var parameter in parameters.GroupBy(parameter => parameter.Key)) foreach (var parameter in parameters.GroupBy(parameter => parameter.Key))
{ {
// Ignore parameters whose name is null or empty. // Ignore parameters whose name is null or empty.
@ -128,13 +118,8 @@ public class OpenIddictMessage
/// </summary> /// </summary>
/// <param name="parameters">The message parameters.</param> /// <param name="parameters">The message parameters.</param>
/// <remarks>Parameters with a null or empty key are always ignored.</remarks> /// <remarks>Parameters with a null or empty key are always ignored.</remarks>
public OpenIddictMessage(IEnumerable<KeyValuePair<string, string?[]?>> parameters) public OpenIddictMessage(IEnumerable<KeyValuePair<string, string?[]?>> parameters!!)
{ {
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
// Ignore parameters whose name is null or empty. // Ignore parameters whose name is null or empty.
@ -161,13 +146,8 @@ public class OpenIddictMessage
/// </summary> /// </summary>
/// <param name="parameters">The message parameters.</param> /// <param name="parameters">The message parameters.</param>
/// <remarks>Parameters with a null or empty key are always ignored.</remarks> /// <remarks>Parameters with a null or empty key are always ignored.</remarks>
public OpenIddictMessage(IEnumerable<KeyValuePair<string, StringValues>> parameters) public OpenIddictMessage(IEnumerable<KeyValuePair<string, StringValues>> parameters!!)
{ {
if (parameters is null)
{
throw new ArgumentNullException(nameof(parameters));
}
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
// Ignore parameters whose name is null or empty. // Ignore parameters whose name is null or empty.
@ -387,13 +367,8 @@ public class OpenIddictMessage
/// Writes the message to the specified JSON writer. /// Writes the message to the specified JSON writer.
/// </summary> /// </summary>
/// <param name="writer">The UTF-8 JSON writer.</param> /// <param name="writer">The UTF-8 JSON writer.</param>
public void WriteTo(Utf8JsonWriter writer) public void WriteTo(Utf8JsonWriter writer!!)
{ {
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
writer.WriteStartObject(); writer.WriteStartObject();
foreach (var parameter in Parameters) foreach (var parameter in Parameters)

39
src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs

@ -151,24 +151,24 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
switch (left.ValueKind) switch (left.ValueKind)
{ {
case JsonValueKind.Undefined: case JsonValueKind.Undefined:
return right.ValueKind == JsonValueKind.Undefined; return right.ValueKind is JsonValueKind.Undefined;
case JsonValueKind.Null: case JsonValueKind.Null:
return right.ValueKind == JsonValueKind.Null; return right.ValueKind is JsonValueKind.Null;
case JsonValueKind.False: case JsonValueKind.False:
return right.ValueKind == JsonValueKind.False; return right.ValueKind is JsonValueKind.False;
case JsonValueKind.True: case JsonValueKind.True:
return right.ValueKind == JsonValueKind.True; return right.ValueKind is JsonValueKind.True;
case JsonValueKind.Number when right.ValueKind == JsonValueKind.Number: case JsonValueKind.Number when right.ValueKind is JsonValueKind.Number:
return left.GetInt64() == right.GetInt64(); return left.GetInt64() == right.GetInt64();
case JsonValueKind.String when right.ValueKind == JsonValueKind.String: case JsonValueKind.String when right.ValueKind is JsonValueKind.String:
return string.Equals(left.GetString(), right.GetString(), StringComparison.Ordinal); return string.Equals(left.GetString(), right.GetString(), StringComparison.Ordinal);
case JsonValueKind.Array when right.ValueKind == JsonValueKind.Array: case JsonValueKind.Array when right.ValueKind is JsonValueKind.Array:
if (left.GetArrayLength() != right.GetArrayLength()) if (left.GetArrayLength() != right.GetArrayLength())
{ {
return false; return false;
@ -187,7 +187,7 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
return true; return true;
case JsonValueKind.Object when right.ValueKind == JsonValueKind.Object: case JsonValueKind.Object when right.ValueKind is JsonValueKind.Object:
foreach (var property in left.EnumerateObject()) foreach (var property in left.EnumerateObject())
{ {
if (!right.TryGetProperty(property.Name, out JsonElement element) || if (!right.TryGetProperty(property.Name, out JsonElement element) ||
@ -502,13 +502,8 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
/// Writes the parameter value to the specified JSON writer. /// Writes the parameter value to the specified JSON writer.
/// </summary> /// </summary>
/// <param name="writer">The UTF-8 JSON writer.</param> /// <param name="writer">The UTF-8 JSON writer.</param>
public void WriteTo(Utf8JsonWriter writer) public void WriteTo(Utf8JsonWriter writer!!)
{ {
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
switch (Value) switch (Value)
{ {
// Note: undefined JsonElement values are assimilated to null values. // Note: undefined JsonElement values are assimilated to null values.
@ -803,7 +798,7 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
for (var index = 0; enumerator.MoveNext(); index++) for (var index = 0; enumerator.MoveNext(); index++)
{ {
var element = enumerator.Current; var element = enumerator.Current;
if (element.ValueKind != JsonValueKind.String) if (element.ValueKind is not JsonValueKind.String)
{ {
return null; return null;
} }
@ -820,49 +815,49 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(bool value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(bool value) => new(value);
/// <summary> /// <summary>
/// Converts a nullable boolean to an <see cref="OpenIddictParameter"/> instance. /// Converts a nullable boolean to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(bool? value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(bool? value) => new(value);
/// <summary> /// <summary>
/// Converts a <see cref="JsonElement"/> to an <see cref="OpenIddictParameter"/> instance. /// Converts a <see cref="JsonElement"/> to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(JsonElement value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(JsonElement value) => new(value);
/// <summary> /// <summary>
/// Converts a long integer to an <see cref="OpenIddictParameter"/> instance. /// Converts a long integer to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(long value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(long value) => new(value);
/// <summary> /// <summary>
/// Converts a nullable long integer to an <see cref="OpenIddictParameter"/> instance. /// Converts a nullable long integer to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(long? value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(long? value) => new(value);
/// <summary> /// <summary>
/// Converts a string to an <see cref="OpenIddictParameter"/> instance. /// Converts a string to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(string? value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(string? value) => new(value);
/// <summary> /// <summary>
/// Converts an array of strings to an <see cref="OpenIddictParameter"/> instance. /// Converts an array of strings to an <see cref="OpenIddictParameter"/> instance.
/// </summary> /// </summary>
/// <param name="value">The value to convert</param> /// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns> /// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(string?[]? value) => new OpenIddictParameter(value); public static implicit operator OpenIddictParameter(string?[]? value) => new(value);
/// <summary> /// <summary>
/// Determines whether a parameter is null or empty. /// Determines whether a parameter is null or empty.

11
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreBuilder.cs

@ -20,8 +20,8 @@ public class OpenIddictClientAspNetCoreBuilder
/// Initializes a new instance of <see cref="OpenIddictClientAspNetCoreBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictClientAspNetCoreBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictClientAspNetCoreBuilder(IServiceCollection services) public OpenIddictClientAspNetCoreBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -35,13 +35,8 @@ public class OpenIddictClientAspNetCoreBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientAspNetCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientAspNetCoreBuilder"/>.</returns>
public OpenIddictClientAspNetCoreBuilder Configure(Action<OpenIddictClientAspNetCoreOptions> configuration) public OpenIddictClientAspNetCoreBuilder Configure(Action<OpenIddictClientAspNetCoreOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;

21
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreConfiguration.cs

@ -19,13 +19,8 @@ public class OpenIddictClientAspNetCoreConfiguration : IConfigureOptions<Authent
/// Registers the OpenIddict client handler in the global authentication options. /// Registers the OpenIddict client handler in the global authentication options.
/// </summary> /// </summary>
/// <param name="options">The options instance to initialize.</param> /// <param name="options">The options instance to initialize.</param>
public void Configure(AuthenticationOptions options) public void Configure(AuthenticationOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
// If a handler was already registered and the type doesn't correspond to the OpenIddict handler, throw an exception. // If a handler was already registered and the type doesn't correspond to the OpenIddict handler, throw an exception.
if (options.SchemeMap.TryGetValue(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, out var builder) && if (options.SchemeMap.TryGetValue(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, out var builder) &&
builder.HandlerType != typeof(OpenIddictClientAspNetCoreHandler)) builder.HandlerType != typeof(OpenIddictClientAspNetCoreHandler))
@ -37,13 +32,8 @@ public class OpenIddictClientAspNetCoreConfiguration : IConfigureOptions<Authent
OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, displayName: null); OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, displayName: null);
} }
public void Configure(OpenIddictClientOptions options) public void Configure(OpenIddictClientOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
// Register the built-in event handlers used by the OpenIddict ASP.NET Core client components. // Register the built-in event handlers used by the OpenIddict ASP.NET Core client components.
options.Handlers.AddRange(OpenIddictClientAspNetCoreHandlers.DefaultHandlers); options.Handlers.AddRange(OpenIddictClientAspNetCoreHandlers.DefaultHandlers);
} }
@ -53,13 +43,8 @@ public class OpenIddictClientAspNetCoreConfiguration : IConfigureOptions<Authent
/// </summary> /// </summary>
/// <param name="name">The authentication scheme associated with the handler instance.</param> /// <param name="name">The authentication scheme associated with the handler instance.</param>
/// <param name="options">The options instance to initialize.</param> /// <param name="options">The options instance to initialize.</param>
public void PostConfigure(string name, AuthenticationOptions options) public void PostConfigure(string name, AuthenticationOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
if (!TryValidate(options.SchemeMap, options.DefaultAuthenticateScheme) || if (!TryValidate(options.SchemeMap, options.DefaultAuthenticateScheme) ||
!TryValidate(options.SchemeMap, options.DefaultScheme) || !TryValidate(options.SchemeMap, options.DefaultScheme) ||
!TryValidate(options.SchemeMap, options.DefaultSignInScheme) || !TryValidate(options.SchemeMap, options.DefaultSignInScheme) ||

19
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreExtensions.cs

@ -22,13 +22,8 @@ public static class OpenIddictClientAspNetCoreExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientAspNetCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientAspNetCoreBuilder"/>.</returns>
public static OpenIddictClientAspNetCoreBuilder UseAspNetCore(this OpenIddictClientBuilder builder) public static OpenIddictClientAspNetCoreBuilder UseAspNetCore(this OpenIddictClientBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddAuthentication(); builder.Services.AddAuthentication();
builder.Services.TryAddScoped<OpenIddictClientAspNetCoreHandler>(); builder.Services.TryAddScoped<OpenIddictClientAspNetCoreHandler>();
@ -64,18 +59,8 @@ public static class OpenIddictClientAspNetCoreExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public static OpenIddictClientBuilder UseAspNetCore( public static OpenIddictClientBuilder UseAspNetCore(
this OpenIddictClientBuilder builder, Action<OpenIddictClientAspNetCoreBuilder> configuration) this OpenIddictClientBuilder builder!!, Action<OpenIddictClientAspNetCoreBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseAspNetCore()); configuration(builder.UseAspNetCore());
return builder; return builder;

12
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandler.cs

@ -27,12 +27,12 @@ public class OpenIddictClientAspNetCoreHandler : AuthenticationHandler<OpenIddic
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreHandler"/> class. /// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreHandler"/> class.
/// </summary> /// </summary>
public OpenIddictClientAspNetCoreHandler( public OpenIddictClientAspNetCoreHandler(
IOpenIddictClientDispatcher dispatcher, IOpenIddictClientDispatcher dispatcher!!,
IOpenIddictClientFactory factory, IOpenIddictClientFactory factory!!,
IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options, IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!,
ILoggerFactory logger, ILoggerFactory logger!!,
UrlEncoder encoder, UrlEncoder encoder!!,
ISystemClock clock) ISystemClock clock!!)
: base(options, logger, encoder, clock) : base(options, logger, encoder, clock)
{ {
_dispatcher = dispatcher; _dispatcher = dispatcher;

50
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlerFilters.cs

@ -24,18 +24,11 @@ public static class OpenIddictClientAspNetCoreHandlerFilters
{ {
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options; private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options;
public RequireRedirectionEndpointPassthroughEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options) public RequireRedirectionEndpointPassthroughEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!)
=> _options = options; => _options = options;
public ValueTask<bool> IsActiveAsync(BaseContext context) public ValueTask<bool> IsActiveAsync(BaseContext context!!)
{ => new(_options.CurrentValue.EnableRedirectionEndpointPassthrough);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(_options.CurrentValue.EnableRedirectionEndpointPassthrough);
}
} }
/// <summary> /// <summary>
@ -45,18 +38,11 @@ public static class OpenIddictClientAspNetCoreHandlerFilters
{ {
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options; private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options;
public RequireErrorPassthroughEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options) public RequireErrorPassthroughEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!)
=> _options = options; => _options = options;
public ValueTask<bool> IsActiveAsync(BaseContext context) public ValueTask<bool> IsActiveAsync(BaseContext context!!)
{ => new(_options.CurrentValue.EnableErrorPassthrough);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(_options.CurrentValue.EnableErrorPassthrough);
}
} }
/// <summary> /// <summary>
@ -64,15 +50,8 @@ public static class OpenIddictClientAspNetCoreHandlerFilters
/// </summary> /// </summary>
public class RequireHttpRequest : IOpenIddictClientHandlerFilter<BaseContext> public class RequireHttpRequest : IOpenIddictClientHandlerFilter<BaseContext>
{ {
public ValueTask<bool> IsActiveAsync(BaseContext context) public ValueTask<bool> IsActiveAsync(BaseContext context!!)
{ => new(context.Transaction.GetHttpRequest() is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.Transaction.GetHttpRequest() is not null);
}
} }
/// <summary> /// <summary>
@ -82,17 +61,10 @@ public static class OpenIddictClientAspNetCoreHandlerFilters
{ {
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options; private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options;
public RequireStatusCodePagesIntegrationEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options) public RequireStatusCodePagesIntegrationEnabled(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!)
=> _options = options; => _options = options;
public ValueTask<bool> IsActiveAsync(BaseContext context) public ValueTask<bool> IsActiveAsync(BaseContext context!!)
{ => new(_options.CurrentValue.EnableStatusCodePagesIntegration);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(_options.CurrentValue.EnableStatusCodePagesIntegration);
}
} }
} }

12
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.Authentication.cs

@ -57,20 +57,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ApplyAuthorizationRequestContext context) public ValueTask HandleAsync(ApplyAuthorizationRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters // Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification. // with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.

156
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs

@ -57,20 +57,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context) public ValueTask HandleAsync(ProcessRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest(); var request = context.Transaction.GetHttpRequest() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
context.EndpointType = context.EndpointType =
Matches(request, context.Options.RedirectionEndpointUris) ? OpenIddictClientEndpointType.Redirection : Matches(request, context.Options.RedirectionEndpointUris) ? OpenIddictClientEndpointType.Redirection :
@ -149,20 +141,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest(); var request = context.Transaction.GetHttpRequest() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
if (HttpMethods.IsGet(request.Method)) if (HttpMethods.IsGet(request.Method))
{ {
@ -203,20 +187,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest(); var request = context.Transaction.GetHttpRequest() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
if (HttpMethods.IsGet(request.Method)) if (HttpMethods.IsGet(request.Method))
{ {
@ -286,20 +262,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest(); var request = context.Transaction.GetHttpRequest() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
if (HttpMethods.IsPost(request.Method)) if (HttpMethods.IsPost(request.Method))
{ {
@ -354,7 +322,7 @@ public static partial class OpenIddictClientAspNetCoreHandlers
{ {
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options; private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options;
public ValidateCorrelationCookie(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options) public ValidateCorrelationCookie(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!)
=> _options = options; => _options = options;
/// <summary> /// <summary>
@ -370,22 +338,14 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest(); var request = context.Transaction.GetHttpRequest() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
// Resolve the request forgery protection from the state token principal. // Resolve the request forgery protection from the state token principal.
// If the claim cannot be found, this means the protection was disabled // If the claim cannot be found, this means the protection was disabled
@ -449,13 +409,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!); var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!);
if (properties is null) if (properties is null)
{ {
@ -508,7 +463,7 @@ public static partial class OpenIddictClientAspNetCoreHandlers
{ {
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options; private readonly IOptionsMonitor<OpenIddictClientAspNetCoreOptions> _options;
public GenerateCorrelationCookie(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options) public GenerateCorrelationCookie(IOptionsMonitor<OpenIddictClientAspNetCoreOptions> options!!)
=> _options = options; => _options = options;
/// <summary> /// <summary>
@ -524,12 +479,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: using a correlation cookie serves as an antiforgery protection as the request will // Note: using a correlation cookie serves as an antiforgery protection as the request will
// always be rejected if a cookie corresponding to the request forgery protection claim // always be rejected if a cookie corresponding to the request forgery protection claim
@ -548,11 +499,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
var options = _options.CurrentValue.CookieBuilder.Build(response.HttpContext); var options = _options.CurrentValue.CookieBuilder.Build(response.HttpContext);
@ -595,13 +543,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.SkipRequest(); context.SkipRequest();
return default; return default;
@ -626,20 +569,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -672,20 +607,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[HeaderNames.CacheControl] = "no-store"; response.Headers[HeaderNames.CacheControl] = "no-store";
@ -719,20 +646,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -767,20 +686,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -826,20 +737,12 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response; var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
}
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -903,13 +806,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.Logger.LogInformation(SR.GetResourceString(SR.ID6145)); context.Logger.LogInformation(SR.GetResourceString(SR.ID6145));
context.HandleRequest(); context.HandleRequest();

28
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHelpers.cs

@ -19,13 +19,8 @@ public static class OpenIddictClientAspNetCoreHelpers
/// </summary> /// </summary>
/// <param name="transaction">The transaction instance.</param> /// <param name="transaction">The transaction instance.</param>
/// <returns>The <see cref="HttpRequest"/> instance or <c>null</c> if it couldn't be found.</returns> /// <returns>The <see cref="HttpRequest"/> instance or <c>null</c> if it couldn't be found.</returns>
public static HttpRequest? GetHttpRequest(this OpenIddictClientTransaction transaction) public static HttpRequest? GetHttpRequest(this OpenIddictClientTransaction transaction!!)
{ {
if (transaction is null)
{
throw new ArgumentNullException(nameof(transaction));
}
if (!transaction.Properties.TryGetValue(typeof(HttpRequest).FullName!, out object? property)) if (!transaction.Properties.TryGetValue(typeof(HttpRequest).FullName!, out object? property))
{ {
return null; return null;
@ -44,13 +39,8 @@ public static class OpenIddictClientAspNetCoreHelpers
/// </summary> /// </summary>
/// <param name="context">The context instance.</param> /// <param name="context">The context instance.</param>
/// <returns>The <see cref="OpenIddictClientEndpointType"/>.</returns> /// <returns>The <see cref="OpenIddictClientEndpointType"/>.</returns>
public static OpenIddictClientEndpointType GetOpenIddictClientEndpointType(this HttpContext context) public static OpenIddictClientEndpointType GetOpenIddictClientEndpointType(this HttpContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.EndpointType ?? default; return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.EndpointType ?? default;
} }
@ -59,13 +49,8 @@ public static class OpenIddictClientAspNetCoreHelpers
/// </summary> /// </summary>
/// <param name="context">The context instance.</param> /// <param name="context">The context instance.</param>
/// <returns>The <see cref="OpenIddictRequest"/> instance or <c>null</c> if it couldn't be found.</returns> /// <returns>The <see cref="OpenIddictRequest"/> instance or <c>null</c> if it couldn't be found.</returns>
public static OpenIddictRequest? GetOpenIddictClientRequest(this HttpContext context) public static OpenIddictRequest? GetOpenIddictClientRequest(this HttpContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.Request; return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.Request;
} }
@ -74,13 +59,8 @@ public static class OpenIddictClientAspNetCoreHelpers
/// </summary> /// </summary>
/// <param name="context">The context instance.</param> /// <param name="context">The context instance.</param>
/// <returns>The <see cref="OpenIddictResponse"/> instance or <c>null</c> if it couldn't be found.</returns> /// <returns>The <see cref="OpenIddictResponse"/> instance or <c>null</c> if it couldn't be found.</returns>
public static OpenIddictResponse? GetOpenIddictClientResponse(this HttpContext context) public static OpenIddictResponse? GetOpenIddictClientResponse(this HttpContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.Response; return context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction?.Response;
} }
} }

11
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs

@ -19,8 +19,8 @@ public class OpenIddictClientSystemNetHttpBuilder
/// Initializes a new instance of <see cref="OpenIddictClientBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictClientBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictClientSystemNetHttpBuilder(IServiceCollection services) public OpenIddictClientSystemNetHttpBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -34,13 +34,8 @@ public class OpenIddictClientSystemNetHttpBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientSystemNetHttpBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientSystemNetHttpBuilder"/>.</returns>
public OpenIddictClientSystemNetHttpBuilder Configure(Action<OpenIddictClientSystemNetHttpOptions> configuration) public OpenIddictClientSystemNetHttpBuilder Configure(Action<OpenIddictClientSystemNetHttpOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;

16
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs

@ -21,17 +21,12 @@ public class OpenIddictClientSystemNetHttpConfiguration : IConfigureOptions<Open
#if !SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER #if !SUPPORTS_SERVICE_PROVIDER_IN_HTTP_MESSAGE_HANDLER_BUILDER
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
public OpenIddictClientSystemNetHttpConfiguration(IServiceProvider serviceProvider) public OpenIddictClientSystemNetHttpConfiguration(IServiceProvider serviceProvider!!)
=> _serviceProvider = serviceProvider; => _serviceProvider = serviceProvider;
#endif #endif
public void Configure(OpenIddictClientOptions options) public void Configure(OpenIddictClientOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
// Register the built-in event handlers used by the OpenIddict System.Net.Http client components. // Register the built-in event handlers used by the OpenIddict System.Net.Http client components.
options.Handlers.AddRange(OpenIddictClientSystemNetHttpHandlers.DefaultHandlers); options.Handlers.AddRange(OpenIddictClientSystemNetHttpHandlers.DefaultHandlers);
} }
@ -39,13 +34,8 @@ public class OpenIddictClientSystemNetHttpConfiguration : IConfigureOptions<Open
public void Configure(HttpClientFactoryOptions options) public void Configure(HttpClientFactoryOptions options)
=> Debug.Fail("This infrastructure method shouldn't be called."); => Debug.Fail("This infrastructure method shouldn't be called.");
public void Configure(string name, HttpClientFactoryOptions options) public void Configure(string name, HttpClientFactoryOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
var assembly = typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName(); var assembly = typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName();
if (!string.Equals(name, assembly.Name, StringComparison.Ordinal)) if (!string.Equals(name, assembly.Name, StringComparison.Ordinal))

19
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpExtensions.cs

@ -23,13 +23,8 @@ public static class OpenIddictClientSystemNetHttpExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public static OpenIddictClientSystemNetHttpBuilder UseSystemNetHttp(this OpenIddictClientBuilder builder) public static OpenIddictClientSystemNetHttpBuilder UseSystemNetHttp(this OpenIddictClientBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
// Register the built-in validation event handlers used by the OpenIddict System.Net.Http components. // Register the built-in validation event handlers used by the OpenIddict System.Net.Http components.
@ -57,18 +52,8 @@ public static class OpenIddictClientSystemNetHttpExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictBuilder"/>.</returns>
public static OpenIddictClientBuilder UseSystemNetHttp( public static OpenIddictClientBuilder UseSystemNetHttp(
this OpenIddictClientBuilder builder, Action<OpenIddictClientSystemNetHttpBuilder> configuration) this OpenIddictClientBuilder builder!!, Action<OpenIddictClientSystemNetHttpBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseSystemNetHttp()); configuration(builder.UseSystemNetHttp());
return builder; return builder;

14
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlerFilters.cs

@ -16,16 +16,8 @@ public static class OpenIddictClientSystemNetHttpHandlerFilters
/// </summary> /// </summary>
public class RequireHttpMetadataAddress : IOpenIddictClientHandlerFilter<BaseExternalContext> public class RequireHttpMetadataAddress : IOpenIddictClientHandlerFilter<BaseExternalContext>
{ {
public ValueTask<bool> IsActiveAsync(BaseExternalContext context) public ValueTask<bool> IsActiveAsync(BaseExternalContext context!!)
{ => new(string.Equals(context.Address?.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
if (context is null) string.Equals(context.Address?.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(
string.Equals(context.Address?.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
string.Equals(context.Address?.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
}
} }
} }

12
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Exchange.cs

@ -48,22 +48,14 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(PrepareTokenRequestContext context) public async ValueTask HandleAsync(PrepareTokenRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Request is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
// If no client identifier was attached to the request, skip the following logic. // If no client identifier was attached to the request, skip the following logic.
if (string.IsNullOrEmpty(context.Request.ClientId)) if (string.IsNullOrEmpty(context.Request.ClientId))

24
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Userinfo.cs

@ -48,22 +48,14 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(PrepareUserinfoRequestContext context) public ValueTask HandleAsync(PrepareUserinfoRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Request is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
// Attach the authorization header containing the access token to the HTTP request. // Attach the authorization header containing the access token to the HTTP request.
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.Request.AccessToken); request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.Request.AccessToken);
@ -92,20 +84,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ExtractUserinfoResponseContext context) public async ValueTask HandleAsync(ExtractUserinfoResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage(); var response = context.Transaction.GetHttpResponseMessage() ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
// The status code is deliberately not validated to ensure even errored responses // The status code is deliberately not validated to ensure even errored responses
// (typically in the 4xx range) can be deserialized and handled by the event handlers. // (typically in the 4xx range) can be deserialized and handled by the event handlers.

86
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs

@ -41,13 +41,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
/// <inheritdoc/> /// <inheritdoc/>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The HTTP request message is disposed later by a dedicated handler.")] Justification = "The HTTP request message is disposed later by a dedicated handler.")]
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var request = new HttpRequestMessage(HttpMethod.Get, context.Address) var request = new HttpRequestMessage(HttpMethod.Get, context.Address)
{ {
Headers = Headers =
@ -83,13 +78,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
/// <inheritdoc/> /// <inheritdoc/>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The HTTP request message is disposed later by a dedicated handler.")] Justification = "The HTTP request message is disposed later by a dedicated handler.")]
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var request = new HttpRequestMessage(HttpMethod.Post, context.Address) var request = new HttpRequestMessage(HttpMethod.Post, context.Address)
{ {
Headers = Headers =
@ -123,22 +113,14 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
if (request.RequestUri is null || context.Transaction.Request.Count == 0) if (request.RequestUri is null || context.Transaction.Request.Count == 0)
{ {
@ -189,22 +171,14 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
request.Content = new FormUrlEncodedContent( request.Content = new FormUrlEncodedContent(
from parameter in context.Transaction.Request.GetParameters() from parameter in context.Transaction.Request.GetParameters()
@ -240,20 +214,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
var assembly = typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName(); var assembly = typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName();
using var client = _factory.CreateClient(assembly.Name!); using var client = _factory.CreateClient(assembly.Name!);
@ -294,20 +260,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage(); var request = context.Transaction.GetHttpRequestMessage() ??
if (request is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
request.Dispose(); request.Dispose();
@ -335,20 +293,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage(); var response = context.Transaction.GetHttpResponseMessage() ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
// The status code is deliberately not validated to ensure even errored responses // The status code is deliberately not validated to ensure even errored responses
// (typically in the 4xx range) can be deserialized and handled by the event handlers. // (typically in the 4xx range) can be deserialized and handled by the event handlers.
@ -376,20 +326,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage(); var response = context.Transaction.GetHttpResponseMessage() ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
}
response.Dispose(); response.Dispose();

153
src/OpenIddict.Client/OpenIddictClientBuilder.cs

@ -25,8 +25,8 @@ public class OpenIddictClientBuilder
/// Initializes a new instance of <see cref="OpenIddictClientBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictClientBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictClientBuilder(IServiceCollection services) public OpenIddictClientBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -42,14 +42,9 @@ public class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)] [EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictClientBuilder AddEventHandler<TContext>( public OpenIddictClientBuilder AddEventHandler<TContext>(
Action<OpenIddictClientHandlerDescriptor.Builder<TContext>> configuration) Action<OpenIddictClientHandlerDescriptor.Builder<TContext>> configuration!!)
where TContext : OpenIddictClientEvents.BaseContext where TContext : OpenIddictClientEvents.BaseContext
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
// Note: handlers registered using this API are assumed to be custom handlers by default. // Note: handlers registered using this API are assumed to be custom handlers by default.
var builder = OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>() var builder = OpenIddictClientHandlerDescriptor.CreateBuilder<TContext>()
.SetType(OpenIddictClientHandlerType.Custom); .SetType(OpenIddictClientHandlerType.Custom);
@ -65,13 +60,8 @@ public class OpenIddictClientBuilder
/// <param name="descriptor">The handler descriptor.</param> /// <param name="descriptor">The handler descriptor.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)] [EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictClientBuilder AddEventHandler(OpenIddictClientHandlerDescriptor descriptor) public OpenIddictClientBuilder AddEventHandler(OpenIddictClientHandlerDescriptor descriptor!!)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
// Register the handler in the services collection. // Register the handler in the services collection.
Services.Add(descriptor.ServiceDescriptor); Services.Add(descriptor.ServiceDescriptor);
@ -84,13 +74,8 @@ public class OpenIddictClientBuilder
/// <param name="descriptor">The descriptor corresponding to the handler to remove.</param> /// <param name="descriptor">The descriptor corresponding to the handler to remove.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)] [EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictClientBuilder RemoveEventHandler(OpenIddictClientHandlerDescriptor descriptor) public OpenIddictClientBuilder RemoveEventHandler(OpenIddictClientHandlerDescriptor descriptor!!)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
Services.RemoveAll(descriptor.ServiceDescriptor.ServiceType); Services.RemoveAll(descriptor.ServiceDescriptor.ServiceType);
Services.PostConfigure<OpenIddictClientOptions>(options => Services.PostConfigure<OpenIddictClientOptions>(options =>
@ -113,13 +98,8 @@ public class OpenIddictClientBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder Configure(Action<OpenIddictClientOptions> configuration) public OpenIddictClientBuilder Configure(Action<OpenIddictClientOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;
@ -130,28 +110,16 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="credentials">The encrypting credentials.</param> /// <param name="credentials">The encrypting credentials.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddEncryptionCredentials(EncryptingCredentials credentials) public OpenIddictClientBuilder AddEncryptionCredentials(EncryptingCredentials credentials!!)
{ => Configure(options => options.EncryptionCredentials.Add(credentials));
if (credentials is null)
{
throw new ArgumentNullException(nameof(credentials));
}
return Configure(options => options.EncryptionCredentials.Add(credentials));
}
/// <summary> /// <summary>
/// Registers an encryption key. /// Registers an encryption key.
/// </summary> /// </summary>
/// <param name="key">The security key.</param> /// <param name="key">The security key.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddEncryptionKey(SecurityKey key) public OpenIddictClientBuilder AddEncryptionKey(SecurityKey key!!)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
// If the encryption key is an asymmetric security key, ensure it has a private key. // If the encryption key is an asymmetric security key, ensure it has a private key.
if (key is AsymmetricSecurityKey asymmetricSecurityKey && if (key is AsymmetricSecurityKey asymmetricSecurityKey &&
asymmetricSecurityKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist) asymmetricSecurityKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist)
@ -193,13 +161,8 @@ public class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The X.509 certificate is attached to the client options.")] Justification = "The X.509 certificate is attached to the client options.")]
public OpenIddictClientBuilder AddDevelopmentEncryptionCertificate(X500DistinguishedName subject) public OpenIddictClientBuilder AddDevelopmentEncryptionCertificate(X500DistinguishedName subject!!)
{ {
if (subject is null)
{
throw new ArgumentNullException(nameof(subject));
}
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite); store.Open(OpenFlags.ReadWrite);
@ -354,13 +317,8 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="certificate">The encryption certificate.</param> /// <param name="certificate">The encryption certificate.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddEncryptionCertificate(X509Certificate2 certificate) public OpenIddictClientBuilder AddEncryptionCertificate(X509Certificate2 certificate!!)
{ {
if (certificate is null)
{
throw new ArgumentNullException(nameof(certificate));
}
// If the certificate is a X.509v3 certificate that specifies at least one // If the certificate is a X.509v3 certificate that specifies at least one
// key usage, ensure that the certificate key can be used for key encryption. // key usage, ensure that the certificate key can be used for key encryption.
if (certificate.Version >= 3) if (certificate.Version >= 3)
@ -406,14 +364,9 @@ public class OpenIddictClientBuilder
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param> /// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddEncryptionCertificate( public OpenIddictClientBuilder AddEncryptionCertificate(
Assembly assembly, string resource, Assembly assembly!!, string resource,
string? password, X509KeyStorageFlags flags) string? password, X509KeyStorageFlags flags)
{ {
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (string.IsNullOrEmpty(resource)) if (string.IsNullOrEmpty(resource))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
@ -456,13 +409,8 @@ public class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The X.509 certificate is attached to the client options.")] Justification = "The X.509 certificate is attached to the client options.")]
public OpenIddictClientBuilder AddEncryptionCertificate(Stream stream, string? password, X509KeyStorageFlags flags) public OpenIddictClientBuilder AddEncryptionCertificate(Stream stream!!, string? password, X509KeyStorageFlags flags)
{ {
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
using var buffer = new MemoryStream(); using var buffer = new MemoryStream();
stream.CopyTo(buffer); stream.CopyTo(buffer);
@ -534,28 +482,16 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="credentials">The signing credentials.</param> /// <param name="credentials">The signing credentials.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddSigningCredentials(SigningCredentials credentials) public OpenIddictClientBuilder AddSigningCredentials(SigningCredentials credentials!!)
{ => Configure(options => options.SigningCredentials.Add(credentials));
if (credentials is null)
{
throw new ArgumentNullException(nameof(credentials));
}
return Configure(options => options.SigningCredentials.Add(credentials));
}
/// <summary> /// <summary>
/// Registers a signing key. /// Registers a signing key.
/// </summary> /// </summary>
/// <param name="key">The security key.</param> /// <param name="key">The security key.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddSigningKey(SecurityKey key) public OpenIddictClientBuilder AddSigningKey(SecurityKey key!!)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
// If the signing key is an asymmetric security key, ensure it has a private key. // If the signing key is an asymmetric security key, ensure it has a private key.
if (key is AsymmetricSecurityKey asymmetricSecurityKey && if (key is AsymmetricSecurityKey asymmetricSecurityKey &&
asymmetricSecurityKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist) asymmetricSecurityKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist)
@ -615,13 +551,8 @@ public class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The X.509 certificate is attached to the client options.")] Justification = "The X.509 certificate is attached to the client options.")]
public OpenIddictClientBuilder AddDevelopmentSigningCertificate(X500DistinguishedName subject) public OpenIddictClientBuilder AddDevelopmentSigningCertificate(X500DistinguishedName subject!!)
{ {
if (subject is null)
{
throw new ArgumentNullException(nameof(subject));
}
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite); store.Open(OpenFlags.ReadWrite);
@ -794,13 +725,8 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="certificate">The signing certificate.</param> /// <param name="certificate">The signing certificate.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddSigningCertificate(X509Certificate2 certificate) public OpenIddictClientBuilder AddSigningCertificate(X509Certificate2 certificate!!)
{ {
if (certificate is null)
{
throw new ArgumentNullException(nameof(certificate));
}
// If the certificate is a X.509v3 certificate that specifies at least // If the certificate is a X.509v3 certificate that specifies at least
// one key usage, ensure that the certificate key can be used for signing. // one key usage, ensure that the certificate key can be used for signing.
if (certificate.Version >= 3) if (certificate.Version >= 3)
@ -846,14 +772,9 @@ public class OpenIddictClientBuilder
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param> /// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddSigningCertificate( public OpenIddictClientBuilder AddSigningCertificate(
Assembly assembly, string resource, Assembly assembly!!, string resource,
string? password, X509KeyStorageFlags flags) string? password, X509KeyStorageFlags flags)
{ {
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (string.IsNullOrEmpty(resource)) if (string.IsNullOrEmpty(resource))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
@ -896,13 +817,8 @@ public class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The X.509 certificate is attached to the client options.")] Justification = "The X.509 certificate is attached to the client options.")]
public OpenIddictClientBuilder AddSigningCertificate(Stream stream, string? password, X509KeyStorageFlags flags) public OpenIddictClientBuilder AddSigningCertificate(Stream stream!!, string? password, X509KeyStorageFlags flags)
{ {
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
using var buffer = new MemoryStream(); using var buffer = new MemoryStream();
stream.CopyTo(buffer); stream.CopyTo(buffer);
@ -974,15 +890,8 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="registration">The client registration.</param> /// <param name="registration">The client registration.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder AddRegistration(OpenIddictClientRegistration registration) public OpenIddictClientBuilder AddRegistration(OpenIddictClientRegistration registration!!)
{ => Configure(options => options.Registrations.Add(registration));
if (registration is null)
{
throw new ArgumentNullException(nameof(registration));
}
return Configure(options => options.Registrations.Add(registration));
}
/// <summary> /// <summary>
/// Sets the relative or absolute URLs associated to the redirection endpoint. /// Sets the relative or absolute URLs associated to the redirection endpoint.
@ -991,15 +900,8 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="addresses">The addresses associated to the endpoint.</param> /// <param name="addresses">The addresses associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder SetRedirectionEndpointUris(params string[] addresses) public OpenIddictClientBuilder SetRedirectionEndpointUris(params string[] addresses!!)
{ => SetRedirectionEndpointUris(addresses.Select(address => new Uri(address, UriKind.RelativeOrAbsolute)).ToArray());
if (addresses is null)
{
throw new ArgumentNullException(nameof(addresses));
}
return SetRedirectionEndpointUris(addresses.Select(address => new Uri(address, UriKind.RelativeOrAbsolute)).ToArray());
}
/// <summary> /// <summary>
/// Sets the relative or absolute URLs associated to the redirection endpoint. /// Sets the relative or absolute URLs associated to the redirection endpoint.
@ -1008,13 +910,8 @@ public class OpenIddictClientBuilder
/// </summary> /// </summary>
/// <param name="addresses">The addresses associated to the endpoint.</param> /// <param name="addresses">The addresses associated to the endpoint.</param>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public OpenIddictClientBuilder SetRedirectionEndpointUris(params Uri[] addresses) public OpenIddictClientBuilder SetRedirectionEndpointUris(params Uri[] addresses!!)
{ {
if (addresses is null)
{
throw new ArgumentNullException(nameof(addresses));
}
if (addresses.Any(address => !address.IsWellFormedOriginalString())) if (addresses.Any(address => !address.IsWellFormedOriginalString()))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0072), nameof(addresses)); throw new ArgumentException(SR.GetResourceString(SR.ID0072), nameof(addresses));

7
src/OpenIddict.Client/OpenIddictClientConfiguration.cs

@ -27,13 +27,8 @@ public class OpenIddictClientConfiguration : IPostConfigureOptions<OpenIddictCli
/// </summary> /// </summary>
/// <param name="name">The authentication scheme associated with the handler instance.</param> /// <param name="name">The authentication scheme associated with the handler instance.</param>
/// <param name="options">The options instance to initialize.</param> /// <param name="options">The options instance to initialize.</param>
public void PostConfigure(string name, OpenIddictClientOptions options) public void PostConfigure(string name, OpenIddictClientOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.JsonWebTokenHandler is null) if (options.JsonWebTokenHandler is null)
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0075)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0075));

13
src/OpenIddict.Client/OpenIddictClientDispatcher.cs

@ -19,22 +19,17 @@ public class OpenIddictClientDispatcher : IOpenIddictClientDispatcher
/// Creates a new instance of the <see cref="OpenIddictClientDispatcher"/> class. /// Creates a new instance of the <see cref="OpenIddictClientDispatcher"/> class.
/// </summary> /// </summary>
public OpenIddictClientDispatcher( public OpenIddictClientDispatcher(
ILogger<OpenIddictClientDispatcher> logger, ILogger<OpenIddictClientDispatcher> logger!!,
IOptionsMonitor<OpenIddictClientOptions> options, IOptionsMonitor<OpenIddictClientOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_logger = logger; _logger = logger;
_options = options; _options = options;
_provider = provider; _provider = provider;
} }
public async ValueTask DispatchAsync<TContext>(TContext context) where TContext : BaseContext public async ValueTask DispatchAsync<TContext>(TContext context!!) where TContext : BaseContext
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
await foreach (var handler in GetHandlersAsync()) await foreach (var handler in GetHandlersAsync())
{ {
try try

4
src/OpenIddict.Client/OpenIddictClientEvents.cs

@ -21,8 +21,8 @@ public static partial class OpenIddictClientEvents
/// <summary> /// <summary>
/// Creates a new instance of the <see cref="BaseContext"/> class. /// Creates a new instance of the <see cref="BaseContext"/> class.
/// </summary> /// </summary>
protected BaseContext(OpenIddictClientTransaction transaction) protected BaseContext(OpenIddictClientTransaction transaction!!)
=> Transaction = transaction ?? throw new ArgumentNullException(nameof(transaction)); => Transaction = transaction;
/// <summary> /// <summary>
/// Gets the environment associated with the current request being processed. /// Gets the environment associated with the current request being processed.

19
src/OpenIddict.Client/OpenIddictClientExtensions.cs

@ -21,13 +21,8 @@ public static class OpenIddictClientExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/>.</returns>
public static OpenIddictClientBuilder AddClient(this OpenIddictBuilder builder) public static OpenIddictClientBuilder AddClient(this OpenIddictBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddLogging(); builder.Services.AddLogging();
builder.Services.AddOptions(); builder.Services.AddOptions();
@ -74,18 +69,8 @@ public static class OpenIddictClientExtensions
/// <param name="configuration">The configuration delegate used to configure the client services.</param> /// <param name="configuration">The configuration delegate used to configure the client services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictBuilder"/>.</returns>
public static OpenIddictBuilder AddClient(this OpenIddictBuilder builder, Action<OpenIddictClientBuilder> configuration) public static OpenIddictBuilder AddClient(this OpenIddictBuilder builder!!, Action<OpenIddictClientBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.AddClient()); configuration(builder.AddClient());
return builder; return builder;

6
src/OpenIddict.Client/OpenIddictClientFactory.cs

@ -18,15 +18,15 @@ public class OpenIddictClientFactory : IOpenIddictClientFactory
/// Creates a new instance of the <see cref="OpenIddictClientFactory"/> class. /// Creates a new instance of the <see cref="OpenIddictClientFactory"/> class.
/// </summary> /// </summary>
public OpenIddictClientFactory( public OpenIddictClientFactory(
ILogger<OpenIddictClientDispatcher> logger, ILogger<OpenIddictClientDispatcher> logger!!,
IOptionsMonitor<OpenIddictClientOptions> options) IOptionsMonitor<OpenIddictClientOptions> options!!)
{ {
_logger = logger; _logger = logger;
_options = options; _options = options;
} }
public ValueTask<OpenIddictClientTransaction> CreateTransactionAsync() public ValueTask<OpenIddictClientTransaction> CreateTransactionAsync()
=> new ValueTask<OpenIddictClientTransaction>(new OpenIddictClientTransaction => new(new OpenIddictClientTransaction
{ {
Logger = _logger, Logger = _logger,
Options = _options.CurrentValue Options = _options.CurrentValue

7
src/OpenIddict.Client/OpenIddictClientHandler.cs

@ -18,8 +18,8 @@ public class OpenIddictClientHandler<TContext> : IOpenIddictClientHandler<TConte
/// Creates a new event using the specified handler delegate. /// Creates a new event using the specified handler delegate.
/// </summary> /// </summary>
/// <param name="handler">The event handler delegate.</param> /// <param name="handler">The event handler delegate.</param>
public OpenIddictClientHandler(Func<TContext, ValueTask> handler) public OpenIddictClientHandler(Func<TContext, ValueTask> handler!!)
=> _handler = handler ?? throw new ArgumentNullException(nameof(handler)); => _handler = handler;
/// <summary> /// <summary>
/// Processes the event. /// Processes the event.
@ -28,6 +28,5 @@ public class OpenIddictClientHandler<TContext> : IOpenIddictClientHandler<TConte
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!) => _handler(context);
=> _handler(context ?? throw new ArgumentNullException(nameof(context)));
} }

65
src/OpenIddict.Client/OpenIddictClientHandlerDescriptor.cs

@ -72,13 +72,8 @@ public class OpenIddictClientHandlerDescriptor
/// </summary> /// </summary>
/// <param name="type">The event handler filter type.</param> /// <param name="type">The event handler filter type.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> AddFilter(Type type) public Builder<TContext> AddFilter(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(IOpenIddictClientHandlerFilter<>).MakeGenericType(typeof(TContext)).IsAssignableFrom(type)) if (!typeof(IOpenIddictClientHandlerFilter<>).MakeGenericType(typeof(TContext)).IsAssignableFrom(type))
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0104)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0104));
@ -104,13 +99,8 @@ public class OpenIddictClientHandlerDescriptor
/// <param name="descriptor">The existing descriptor properties are copied from.</param> /// <param name="descriptor">The existing descriptor properties are copied from.</param>
/// <remarks>All the properties previously set on this instance are automatically replaced.</remarks> /// <remarks>All the properties previously set on this instance are automatically replaced.</remarks>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> Import(OpenIddictClientHandlerDescriptor descriptor) public Builder<TContext> Import(OpenIddictClientHandlerDescriptor descriptor!!)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (descriptor.ContextType != typeof(TContext)) if (descriptor.ContextType != typeof(TContext))
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0284)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0284));
@ -130,13 +120,8 @@ public class OpenIddictClientHandlerDescriptor
/// </summary> /// </summary>
/// <param name="descriptor">The service descriptor.</param> /// <param name="descriptor">The service descriptor.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> SetServiceDescriptor(ServiceDescriptor descriptor) public Builder<TContext> SetServiceDescriptor(ServiceDescriptor descriptor!!)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var type = descriptor.ServiceType; var type = descriptor.ServiceType;
if (!typeof(IOpenIddictClientHandler<>).MakeGenericType(typeof(TContext)).IsAssignableFrom(type)) if (!typeof(IOpenIddictClientHandler<>).MakeGenericType(typeof(TContext)).IsAssignableFrom(type))
{ {
@ -182,15 +167,8 @@ public class OpenIddictClientHandlerDescriptor
/// </summary> /// </summary>
/// <param name="handler">The handler instance.</param> /// <param name="handler">The handler instance.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler) public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler!!)
{ => UseSingletonHandler(new OpenIddictClientHandler<TContext>(handler));
if (handler is null)
{
throw new ArgumentNullException(nameof(handler));
}
return UseSingletonHandler(new OpenIddictClientHandler<TContext>(handler));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified scoped handler. /// Configures the descriptor to use the specified scoped handler.
@ -208,17 +186,10 @@ public class OpenIddictClientHandlerDescriptor
/// <typeparam name="THandler">The handler type.</typeparam> /// <typeparam name="THandler">The handler type.</typeparam>
/// <param name="factory">The factory used to create the handler.</param> /// <param name="factory">The factory used to create the handler.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, object> factory) public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, object> factory!!)
where THandler : IOpenIddictClientHandler<TContext> where THandler : IOpenIddictClientHandler<TContext>
{ => SetServiceDescriptor(new ServiceDescriptor(
if (factory is null)
{
throw new ArgumentNullException(nameof(factory));
}
return SetServiceDescriptor(new ServiceDescriptor(
typeof(THandler), factory, ServiceLifetime.Scoped)); typeof(THandler), factory, ServiceLifetime.Scoped));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -236,17 +207,10 @@ public class OpenIddictClientHandlerDescriptor
/// <typeparam name="THandler">The handler type.</typeparam> /// <typeparam name="THandler">The handler type.</typeparam>
/// <param name="factory">The factory used to create the handler.</param> /// <param name="factory">The factory used to create the handler.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, object> factory) public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, object> factory!!)
where THandler : IOpenIddictClientHandler<TContext> where THandler : IOpenIddictClientHandler<TContext>
{ => SetServiceDescriptor(new ServiceDescriptor(
if (factory is null)
{
throw new ArgumentNullException(nameof(factory));
}
return SetServiceDescriptor(new ServiceDescriptor(
typeof(THandler), factory, ServiceLifetime.Singleton)); typeof(THandler), factory, ServiceLifetime.Singleton));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -254,16 +218,9 @@ public class OpenIddictClientHandlerDescriptor
/// <typeparam name="THandler">The handler type.</typeparam> /// <typeparam name="THandler">The handler type.</typeparam>
/// <param name="handler">The handler instance.</param> /// <param name="handler">The handler instance.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(THandler handler) public Builder<TContext> UseSingletonHandler<THandler>(THandler handler!!)
where THandler : IOpenIddictClientHandler<TContext> where THandler : IOpenIddictClientHandler<TContext>
{ => SetServiceDescriptor(new ServiceDescriptor(typeof(THandler), handler));
if (handler is null)
{
throw new ArgumentNullException(nameof(handler));
}
return SetServiceDescriptor(new ServiceDescriptor(typeof(THandler), handler));
}
/// <summary> /// <summary>
/// Build a new descriptor instance, based on the parameters that were previously set. /// Build a new descriptor instance, based on the parameters that were previously set.

209
src/OpenIddict.Client/OpenIddictClientHandlerFilters.cs

@ -17,15 +17,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireAuthorizationCodeOrImplicitGrantType : IOpenIddictClientHandlerFilter<ProcessChallengeContext> public class RequireAuthorizationCodeOrImplicitGrantType : IOpenIddictClientHandlerFilter<ProcessChallengeContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessChallengeContext context) public ValueTask<bool> IsActiveAsync(ProcessChallengeContext context!!)
{ => new(context.GrantType is GrantTypes.AuthorizationCode or GrantTypes.Implicit);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.GrantType is GrantTypes.AuthorizationCode or GrantTypes.Implicit);
}
} }
/// <summary> /// <summary>
@ -33,15 +26,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireAuthorizationCodeValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireAuthorizationCodeValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateAuthorizationCode);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateAuthorizationCode);
}
} }
/// <summary> /// <summary>
@ -49,15 +35,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireBackchannelAccessTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireBackchannelAccessTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateBackchannelAccessToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateBackchannelAccessToken);
}
} }
/// <summary> /// <summary>
@ -65,15 +44,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireBackchannelIdentityTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireBackchannelIdentityTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.BackchannelIdentityTokenPrincipal is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.BackchannelIdentityTokenPrincipal is not null);
}
} }
/// <summary> /// <summary>
@ -81,15 +53,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireBackchannelIdentityTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireBackchannelIdentityTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateBackchannelIdentityToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateBackchannelIdentityToken);
}
} }
/// <summary> /// <summary>
@ -97,15 +62,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireFrontchannelAccessTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireFrontchannelAccessTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateFrontchannelAccessToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateFrontchannelAccessToken);
}
} }
/// <summary> /// <summary>
@ -113,15 +71,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireFrontchannelIdentityTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireFrontchannelIdentityTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.FrontchannelIdentityTokenPrincipal is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.FrontchannelIdentityTokenPrincipal is not null);
}
} }
/// <summary> /// <summary>
@ -129,15 +80,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireFrontchannelIdentityTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireFrontchannelIdentityTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateFrontchannelIdentityToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateFrontchannelIdentityToken);
}
} }
/// <summary> /// <summary>
@ -145,15 +89,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireRedirectionRequest : IOpenIddictClientHandlerFilter<BaseContext> public class RequireRedirectionRequest : IOpenIddictClientHandlerFilter<BaseContext>
{ {
public ValueTask<bool> IsActiveAsync(BaseContext context) public ValueTask<bool> IsActiveAsync(BaseContext context!!)
{ => new(context.EndpointType is OpenIddictClientEndpointType.Redirection);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.EndpointType == OpenIddictClientEndpointType.Redirection);
}
} }
/// <summary> /// <summary>
@ -161,15 +98,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireRefreshTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireRefreshTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateRefreshToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateRefreshToken);
}
} }
/// <summary> /// <summary>
@ -177,15 +107,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireStateTokenGenerated : IOpenIddictClientHandlerFilter<ProcessChallengeContext> public class RequireStateTokenGenerated : IOpenIddictClientHandlerFilter<ProcessChallengeContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessChallengeContext context) public ValueTask<bool> IsActiveAsync(ProcessChallengeContext context!!)
{ => new(context.GenerateStateToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.GenerateStateToken);
}
} }
/// <summary> /// <summary>
@ -193,15 +116,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireStateTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireStateTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.StateTokenPrincipal is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.StateTokenPrincipal is not null);
}
} }
/// <summary> /// <summary>
@ -209,15 +125,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireStateTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireStateTokenValidated : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ValidateStateToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ValidateStateToken);
}
} }
/// <summary> /// <summary>
@ -225,15 +134,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireTokenRequest : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireTokenRequest : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.TokenRequest is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.TokenRequest is not null);
}
} }
/// <summary> /// <summary>
@ -241,15 +143,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireTokenResponse : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireTokenResponse : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.TokenResponse is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.TokenResponse is not null);
}
} }
/// <summary> /// <summary>
@ -257,15 +152,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireUserinfoRequest : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireUserinfoRequest : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.UserinfoRequest is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.UserinfoRequest is not null);
}
} }
/// <summary> /// <summary>
@ -273,15 +161,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireUserinfoResponse : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireUserinfoResponse : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.UserinfoResponse is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.UserinfoResponse is not null);
}
} }
/// <summary> /// <summary>
@ -289,15 +170,8 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireUserinfoTokenExtracted : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireUserinfoTokenExtracted : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.ExtractUserinfoToken);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.ExtractUserinfoToken);
}
} }
/// <summary> /// <summary>
@ -305,14 +179,7 @@ public static class OpenIddictClientHandlerFilters
/// </summary> /// </summary>
public class RequireUserinfoTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext> public class RequireUserinfoTokenPrincipal : IOpenIddictClientHandlerFilter<ProcessAuthenticationContext>
{ {
public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context) public ValueTask<bool> IsActiveAsync(ProcessAuthenticationContext context!!)
{ => new(context.UserinfoTokenPrincipal is not null);
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
return new ValueTask<bool>(context.UserinfoTokenPrincipal is not null);
}
} }
} }

76
src/OpenIddict.Client/OpenIddictClientHandlers.Authentication.cs

@ -51,7 +51,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public PrepareAuthorizationRequest(IOpenIddictClientDispatcher dispatcher) public PrepareAuthorizationRequest(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -65,13 +65,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new PrepareAuthorizationRequestContext(context.Transaction); var notification = new PrepareAuthorizationRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -96,7 +91,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ApplyAuthorizationRequest(IOpenIddictClientDispatcher dispatcher) public ApplyAuthorizationRequest(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -110,13 +105,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new ApplyAuthorizationRequestContext(context.Transaction); var notification = new ApplyAuthorizationRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -149,13 +139,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ApplyAuthorizationRequestContext context) public async ValueTask HandleAsync(ApplyAuthorizationRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
@ -183,7 +168,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ExtractRedirectionRequest(IOpenIddictClientDispatcher dispatcher) public ExtractRedirectionRequest(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -197,13 +182,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context) public async ValueTask HandleAsync(ProcessRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new ExtractRedirectionRequestContext(context.Transaction); var notification = new ExtractRedirectionRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -244,7 +224,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateRedirectionRequest(IOpenIddictClientDispatcher dispatcher) public ValidateRedirectionRequest(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -259,13 +239,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context) public async ValueTask HandleAsync(ProcessRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new ValidateRedirectionRequestContext(context.Transaction); var notification = new ValidateRedirectionRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -301,7 +276,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public HandleRedirectionRequest(IOpenIddictClientDispatcher dispatcher) public HandleRedirectionRequest(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -315,13 +290,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessRequestContext context) public async ValueTask HandleAsync(ProcessRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new HandleRedirectionRequestContext(context.Transaction); var notification = new HandleRedirectionRequestContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -357,7 +327,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ApplyRedirectionResponse(IOpenIddictClientDispatcher dispatcher) public ApplyRedirectionResponse(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -372,13 +342,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(TContext context) public async ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new ApplyRedirectionResponseContext(context.Transaction); var notification = new ApplyRedirectionResponseContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);
@ -414,12 +379,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(PrepareAuthorizationRequestContext context) public ValueTask HandleAsync(PrepareAuthorizationRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// When the response mode corresponds to the default mode assigned to the selected // When the response mode corresponds to the default mode assigned to the selected
// response type, the specification explicitly recommends omitting the response mode. // response type, the specification explicitly recommends omitting the response mode.
@ -451,7 +412,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateTokens(IOpenIddictClientDispatcher dispatcher) public ValidateTokens(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -465,13 +426,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ValidateRedirectionRequestContext context) public async ValueTask HandleAsync(ValidateRedirectionRequestContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new ProcessAuthenticationContext(context.Transaction); var notification = new ProcessAuthenticationContext(context.Transaction);
await _dispatcher.DispatchAsync(notification); await _dispatcher.DispatchAsync(notification);

84
src/OpenIddict.Client/OpenIddictClientHandlers.Discovery.cs

@ -53,12 +53,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// The issuer returned in the discovery document must exactly match the URL used to access it. // The issuer returned in the discovery document must exactly match the URL used to access it.
// See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationClient. // See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationClient.
@ -105,13 +101,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: the authorization_endpoint node is required by the OpenID Connect discovery specification // Note: the authorization_endpoint node is required by the OpenID Connect discovery specification
// but is optional in the OAuth 2.0 authorization server metadata specification. To make OpenIddict // but is optional in the OAuth 2.0 authorization server metadata specification. To make OpenIddict
// compatible with the newer OAuth 2.0 specification, null/empty and missing values are allowed here. // compatible with the newer OAuth 2.0 specification, null/empty and missing values are allowed here.
@ -157,13 +148,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: the jwks_uri node is required by the OpenID Connect discovery specification. // Note: the jwks_uri node is required by the OpenID Connect discovery specification.
// See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationClient. // See https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationClient.
var address = (string?) context.Response[Metadata.JwksUri]; var address = (string?) context.Response[Metadata.JwksUri];
@ -209,13 +195,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var address = (string?) context.Response[Metadata.TokenEndpoint]; var address = (string?) context.Response[Metadata.TokenEndpoint];
if (!string.IsNullOrEmpty(address)) if (!string.IsNullOrEmpty(address))
{ {
@ -252,13 +233,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var address = (string?) context.Response[Metadata.UserinfoEndpoint]; var address = (string?) context.Response[Metadata.UserinfoEndpoint];
if (!string.IsNullOrEmpty(address)) if (!string.IsNullOrEmpty(address))
{ {
@ -295,12 +271,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the grant types supported by the authorization endpoint, if available. // Resolve the grant types supported by the authorization endpoint, if available.
var types = context.Response[Metadata.GrantTypesSupported]?.GetUnnamedParameters(); var types = context.Response[Metadata.GrantTypesSupported]?.GetUnnamedParameters();
@ -337,12 +309,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the response modes supported by the authorization endpoint, if available. // Resolve the response modes supported by the authorization endpoint, if available.
var modes = context.Response[Metadata.ResponseModesSupported]?.GetUnnamedParameters(); var modes = context.Response[Metadata.ResponseModesSupported]?.GetUnnamedParameters();
@ -379,12 +347,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the response types supported by the authorization endpoint, if available. // Resolve the response types supported by the authorization endpoint, if available.
var types = context.Response[Metadata.ResponseTypesSupported]?.GetUnnamedParameters(); var types = context.Response[Metadata.ResponseTypesSupported]?.GetUnnamedParameters();
@ -421,12 +385,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the code challenge methods supported by the authorization endpoint, if available. // Resolve the code challenge methods supported by the authorization endpoint, if available.
var methods = context.Response[Metadata.CodeChallengeMethodsSupported]?.GetUnnamedParameters(); var methods = context.Response[Metadata.CodeChallengeMethodsSupported]?.GetUnnamedParameters();
@ -463,12 +423,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the scopes supported by the remote server, if available. // Resolve the scopes supported by the remote server, if available.
var scopes = context.Response[Metadata.ScopesSupported]?.GetUnnamedParameters(); var scopes = context.Response[Metadata.ScopesSupported]?.GetUnnamedParameters();
@ -506,13 +462,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.Configuration.AuthorizationResponseIssParameterSupported = (bool?) context.Configuration.AuthorizationResponseIssParameterSupported = (bool?)
context.Response[Metadata.AuthorizationResponseIssParameterSupported]; context.Response[Metadata.AuthorizationResponseIssParameterSupported];
@ -537,12 +488,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleConfigurationResponseContext context) public ValueTask HandleAsync(HandleConfigurationResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Resolve the client authentication methods supported by the token endpoint, if available. // Resolve the client authentication methods supported by the token endpoint, if available.
var methods = context.Response[Metadata.TokenEndpointAuthMethodsSupported]?.GetUnnamedParameters(); var methods = context.Response[Metadata.TokenEndpointAuthMethodsSupported]?.GetUnnamedParameters();
@ -579,13 +526,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleCryptographyResponseContext context) public ValueTask HandleAsync(HandleCryptographyResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var keys = context.Response[JsonWebKeySetParameterNames.Keys]?.GetUnnamedParameters(); var keys = context.Response[JsonWebKeySetParameterNames.Keys]?.GetUnnamedParameters();
if (keys is not { Count: > 0 }) if (keys is not { Count: > 0 })
{ {

7
src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs

@ -36,13 +36,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleTokenResponseContext context) public ValueTask HandleAsync(HandleTokenResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var parameter in context.Response.GetParameters()) foreach (var parameter in context.Response.GetParameters())
{ {
if (ValidateParameterType(parameter.Key, parameter.Value.Value)) if (ValidateParameterType(parameter.Key, parameter.Value.Value))

48
src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs

@ -50,12 +50,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ValidateTokenContext context) public async ValueTask HandleAsync(ValidateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// The OpenIddict client is expected to validate tokens it creates (e.g state tokens) and // The OpenIddict client is expected to validate tokens it creates (e.g state tokens) and
// tokens that are created by one or multiple authorization servers (e.g identity tokens). // tokens that are created by one or multiple authorization servers (e.g identity tokens).
@ -162,13 +158,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ValidateTokenContext context) public async ValueTask HandleAsync(ValidateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If a principal was already attached, don't overwrite it. // If a principal was already attached, don't overwrite it.
if (context.Principal is not null) if (context.Principal is not null)
{ {
@ -278,13 +269,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context) public ValueTask HandleAsync(ValidateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: only map the private claims from fully trusted tokens. // Note: only map the private claims from fully trusted tokens.
if (context.Principal is null || !context.Principal.HasTokenType(TokenTypeHints.StateToken)) if (context.Principal is null || !context.Principal.HasTokenType(TokenTypeHints.StateToken))
{ {
@ -335,13 +321,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context) public ValueTask HandleAsync(ValidateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Principal is null) if (context.Principal is null)
{ {
context.Reject( context.Reject(
@ -387,13 +368,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context) public ValueTask HandleAsync(ValidateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var date = context.Principal.GetExpirationDate(); var date = context.Principal.GetExpirationDate();
@ -427,13 +403,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(GenerateTokenContext context) public ValueTask HandleAsync(GenerateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.SecurityTokenHandler = context.Options.JsonWebTokenHandler; context.SecurityTokenHandler = context.Options.JsonWebTokenHandler;
context.EncryptionCredentials = context.Options.EncryptionCredentials.First(); context.EncryptionCredentials = context.Options.EncryptionCredentials.First();
@ -459,13 +430,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(GenerateTokenContext context) public ValueTask HandleAsync(GenerateTokenContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If a token was already attached by another handler, don't overwrite it. // If a token was already attached by another handler, don't overwrite it.
if (!string.IsNullOrEmpty(context.Token)) if (!string.IsNullOrEmpty(context.Token))
{ {

14
src/OpenIddict.Client/OpenIddictClientHandlers.Userinfo.cs

@ -40,13 +40,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(HandleUserinfoResponseContext context) public ValueTask HandleAsync(HandleUserinfoResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Ignore the response instance if a userinfo token was extracted. // Ignore the response instance if a userinfo token was extracted.
if (!string.IsNullOrEmpty(context.UserinfoToken)) if (!string.IsNullOrEmpty(context.UserinfoToken))
{ {
@ -97,13 +92,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(HandleUserinfoResponseContext context) public async ValueTask HandleAsync(HandleUserinfoResponseContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Ignore the response instance if a userinfo token was extracted. // Ignore the response instance if a userinfo token was extracted.
if (!string.IsNullOrEmpty(context.UserinfoToken)) if (!string.IsNullOrEmpty(context.UserinfoToken))
{ {

436
src/OpenIddict.Client/OpenIddictClientHandlers.cs

@ -124,12 +124,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Authentication demands can be triggered from the redirection endpoint // Authentication demands can be triggered from the redirection endpoint
// to handle authorization callbacks but also from unknown endpoints // to handle authorization callbacks but also from unknown endpoints
@ -181,13 +177,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
(context.ExtractStateToken, (context.ExtractStateToken,
context.RequireStateToken, context.RequireStateToken,
context.ValidateStateToken) = context.EndpointType switch context.ValidateStateToken) = context.EndpointType switch
@ -222,13 +213,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.StateToken = context.EndpointType switch context.StateToken = context.EndpointType switch
{ {
OpenIddictClientEndpointType.Redirection when context.ExtractStateToken OpenIddictClientEndpointType.Redirection when context.ExtractStateToken
@ -257,13 +243,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.RequireStateToken && string.IsNullOrEmpty(context.StateToken)) if (context.RequireStateToken && string.IsNullOrEmpty(context.StateToken))
{ {
context.Reject( context.Reject(
@ -285,7 +266,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateStateToken(IOpenIddictClientDispatcher dispatcher) public ValidateStateToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -300,13 +281,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.StateTokenPrincipal is not null || if (context.StateTokenPrincipal is not null ||
string.IsNullOrEmpty(context.StateToken)) string.IsNullOrEmpty(context.StateToken))
{ {
@ -363,13 +339,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Retrieve the client definition using the authorization server stored in the state token. // Retrieve the client definition using the authorization server stored in the state token.
@ -421,13 +392,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Issuer is { IsAbsoluteUri: true }, SR.GetResourceString(SR.ID4013)); Debug.Assert(context.Issuer is { IsAbsoluteUri: true }, SR.GetResourceString(SR.ID4013));
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
@ -512,13 +478,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var (error, description, uri) = ( var (error, description, uri) = (
(string?) context.Request[Parameters.Error], (string?) context.Request[Parameters.Error],
(string?) context.Request[Parameters.ErrorDescription], (string?) context.Request[Parameters.ErrorDescription],
@ -556,13 +517,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Resolve the negotiated grant type from the state token. // Resolve the negotiated grant type from the state token.
@ -609,13 +565,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Resolve the negotiated response type from the state token. // Resolve the negotiated response type from the state token.
@ -641,13 +592,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
(context.ExtractAuthorizationCode, (context.ExtractAuthorizationCode,
context.RequireAuthorizationCode, context.RequireAuthorizationCode,
context.ValidateAuthorizationCode) = context.GrantType switch context.ValidateAuthorizationCode) = context.GrantType switch
@ -723,13 +669,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.AuthorizationCode = context.EndpointType switch context.AuthorizationCode = context.EndpointType switch
{ {
OpenIddictClientEndpointType.Redirection when context.ExtractAuthorizationCode OpenIddictClientEndpointType.Redirection when context.ExtractAuthorizationCode
@ -774,13 +715,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if ((context.RequireAuthorizationCode && string.IsNullOrEmpty(context.AuthorizationCode)) || if ((context.RequireAuthorizationCode && string.IsNullOrEmpty(context.AuthorizationCode)) ||
(context.RequireFrontchannelAccessToken && string.IsNullOrEmpty(context.FrontchannelAccessToken)) || (context.RequireFrontchannelAccessToken && string.IsNullOrEmpty(context.FrontchannelAccessToken)) ||
(context.RequireFrontchannelIdentityToken && string.IsNullOrEmpty(context.FrontchannelIdentityToken))) (context.RequireFrontchannelIdentityToken && string.IsNullOrEmpty(context.FrontchannelIdentityToken)))
@ -804,7 +740,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateFrontchannelIdentityToken(IOpenIddictClientDispatcher dispatcher) public ValidateFrontchannelIdentityToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -819,13 +755,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.FrontchannelIdentityTokenPrincipal is not null || if (context.FrontchannelIdentityTokenPrincipal is not null ||
string.IsNullOrEmpty(context.FrontchannelIdentityToken)) string.IsNullOrEmpty(context.FrontchannelIdentityToken))
{ {
@ -882,13 +813,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
foreach (var group in context.FrontchannelIdentityTokenPrincipal.Claims foreach (var group in context.FrontchannelIdentityTokenPrincipal.Claims
@ -1018,13 +944,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Note: while an identity token typically contains a single audience represented // Note: while an identity token typically contains a single audience represented
@ -1063,13 +984,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Note: the "azp" claim is optional, but if it's present, it MUST match the client identifier of the application. // Note: the "azp" claim is optional, but if it's present, it MUST match the client identifier of the application.
@ -1107,13 +1023,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -1170,13 +1081,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.FrontchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Resolve the signing algorithm used to sign the identity token. If the private // Resolve the signing algorithm used to sign the identity token. If the private
@ -1299,7 +1205,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateFrontchannelAccessToken(IOpenIddictClientDispatcher dispatcher) public ValidateFrontchannelAccessToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -1314,13 +1220,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.FrontchannelAccessTokenPrincipal is not null || if (context.FrontchannelAccessTokenPrincipal is not null ||
string.IsNullOrEmpty(context.FrontchannelAccessToken)) string.IsNullOrEmpty(context.FrontchannelAccessToken))
{ {
@ -1369,7 +1270,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateAuthorizationCode(IOpenIddictClientDispatcher dispatcher) public ValidateAuthorizationCode(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -1384,13 +1285,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.AuthorizationCodePrincipal is not null || if (context.AuthorizationCodePrincipal is not null ||
string.IsNullOrEmpty(context.AuthorizationCode)) string.IsNullOrEmpty(context.AuthorizationCode))
{ {
@ -1446,13 +1342,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
(context.ExtractBackchannelAccessToken, (context.ExtractBackchannelAccessToken,
context.RequireBackchannelAccessToken, context.RequireBackchannelAccessToken,
context.ValidateBackchannelAccessToken) = context.GrantType switch context.ValidateBackchannelAccessToken) = context.GrantType switch
@ -1537,13 +1428,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.ExtractBackchannelAccessToken && if (!context.ExtractBackchannelAccessToken &&
!context.ExtractBackchannelIdentityToken && !context.ExtractBackchannelIdentityToken &&
!context.ExtractRefreshToken) !context.ExtractRefreshToken)
@ -1620,13 +1506,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.TokenRequest is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.TokenRequest is not null, SR.GetResourceString(SR.ID4008));
context.TokenResponse = await _service.SendTokenRequestAsync(context.Registration, context.TokenRequest); context.TokenResponse = await _service.SendTokenRequestAsync(context.Registration, context.TokenRequest);
@ -1649,13 +1530,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.TokenResponse is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.TokenResponse is not null, SR.GetResourceString(SR.ID4007));
if (!string.IsNullOrEmpty(context.TokenResponse.Error)) if (!string.IsNullOrEmpty(context.TokenResponse.Error))
@ -1688,13 +1564,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.TokenResponse is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.TokenResponse is not null, SR.GetResourceString(SR.ID4007));
context.BackchannelAccessToken = context.ExtractBackchannelAccessToken switch context.BackchannelAccessToken = context.ExtractBackchannelAccessToken switch
@ -1735,13 +1606,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if ((context.RequireBackchannelAccessToken && string.IsNullOrEmpty(context.BackchannelAccessToken)) || if ((context.RequireBackchannelAccessToken && string.IsNullOrEmpty(context.BackchannelAccessToken)) ||
(context.RequireBackchannelIdentityToken && string.IsNullOrEmpty(context.BackchannelIdentityToken)) || (context.RequireBackchannelIdentityToken && string.IsNullOrEmpty(context.BackchannelIdentityToken)) ||
(context.RequireRefreshToken && string.IsNullOrEmpty(context.RefreshToken))) (context.RequireRefreshToken && string.IsNullOrEmpty(context.RefreshToken)))
@ -1765,7 +1631,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateBackchannelIdentityToken(IOpenIddictClientDispatcher dispatcher) public ValidateBackchannelIdentityToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -1780,13 +1646,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.BackchannelIdentityTokenPrincipal is not null || if (context.BackchannelIdentityTokenPrincipal is not null ||
string.IsNullOrEmpty(context.BackchannelIdentityToken)) string.IsNullOrEmpty(context.BackchannelIdentityToken))
{ {
@ -1843,13 +1704,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
foreach (var group in context.BackchannelIdentityTokenPrincipal.Claims foreach (var group in context.BackchannelIdentityTokenPrincipal.Claims
@ -1979,13 +1835,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Note: while an identity token typically contains a single audience represented // Note: while an identity token typically contains a single audience represented
@ -2024,13 +1875,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Note: the "azp" claim is optional, but if it's present, it MUST match the client identifier of the application. // Note: the "azp" claim is optional, but if it's present, it MUST match the client identifier of the application.
@ -2068,13 +1914,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -2131,13 +1972,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.BackchannelIdentityTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(!string.IsNullOrEmpty(context.BackchannelAccessToken), SR.GetResourceString(SR.ID4010)); Debug.Assert(!string.IsNullOrEmpty(context.BackchannelAccessToken), SR.GetResourceString(SR.ID4010));
@ -2233,7 +2069,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateBackchannelAccessToken(IOpenIddictClientDispatcher dispatcher) public ValidateBackchannelAccessToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -2248,13 +2084,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.BackchannelAccessTokenPrincipal is not null || if (context.BackchannelAccessTokenPrincipal is not null ||
string.IsNullOrEmpty(context.BackchannelAccessToken)) string.IsNullOrEmpty(context.BackchannelAccessToken))
{ {
@ -2303,7 +2134,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateRefreshToken(IOpenIddictClientDispatcher dispatcher) public ValidateRefreshToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -2318,13 +2149,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.RefreshTokenPrincipal is not null || if (context.RefreshTokenPrincipal is not null ||
string.IsNullOrEmpty(context.RefreshToken)) string.IsNullOrEmpty(context.RefreshToken))
{ {
@ -2380,13 +2206,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
@ -2438,12 +2259,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Attach a new request instance if necessary. // Attach a new request instance if necessary.
context.UserinfoRequest ??= new OpenIddictRequest(); context.UserinfoRequest ??= new OpenIddictRequest();
@ -2486,13 +2303,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.UserinfoRequest is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.UserinfoRequest is not null, SR.GetResourceString(SR.ID4008));
// Note: userinfo responses can be of two types: // Note: userinfo responses can be of two types:
@ -2520,13 +2332,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.UserinfoResponse is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.UserinfoResponse is not null, SR.GetResourceString(SR.ID4007));
if (!string.IsNullOrEmpty(context.UserinfoResponse.Error)) if (!string.IsNullOrEmpty(context.UserinfoResponse.Error))
@ -2559,13 +2366,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context) public ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.RequireUserinfoToken && string.IsNullOrEmpty(context.UserinfoToken)) if (context.RequireUserinfoToken && string.IsNullOrEmpty(context.UserinfoToken))
{ {
context.Reject( context.Reject(
@ -2587,7 +2389,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public ValidateUserinfoToken(IOpenIddictClientDispatcher dispatcher) public ValidateUserinfoToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -2602,13 +2404,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.UserinfoTokenPrincipal is not null || string.IsNullOrEmpty(context.UserinfoToken)) if (context.UserinfoTokenPrincipal is not null || string.IsNullOrEmpty(context.UserinfoToken))
{ {
return; return;
@ -2664,13 +2461,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.UserinfoTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.UserinfoTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
@ -2737,13 +2529,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.UserinfoTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.UserinfoTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
@ -2822,13 +2609,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If an explicit grant type was specified, ensure it is supported by OpenIddict. // If an explicit grant type was specified, ensure it is supported by OpenIddict.
if (!string.IsNullOrEmpty(context.GrantType) && if (!string.IsNullOrEmpty(context.GrantType) &&
context.GrantType is not (GrantTypes.AuthorizationCode or GrantTypes.Implicit)) context.GrantType is not (GrantTypes.AuthorizationCode or GrantTypes.Implicit))
@ -2866,12 +2648,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: if the static registration cannot be found in the options, this may indicate // Note: if the static registration cannot be found in the options, this may indicate
// the client was removed after the authorization dance started and thus, can no longer // the client was removed after the authorization dance started and thus, can no longer
@ -2901,13 +2679,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If an explicit grant type was specified, don't overwrite it. // If an explicit grant type was specified, don't overwrite it.
if (!string.IsNullOrEmpty(context.GrantType)) if (!string.IsNullOrEmpty(context.GrantType))
{ {
@ -2991,12 +2764,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// In OpenIddict, per-authorization demand values are stored in an encrypted and signed token // In OpenIddict, per-authorization demand values are stored in an encrypted and signed token
// called "state token", that allows flowing per-authorization demand data like the issuer // called "state token", that allows flowing per-authorization demand data like the issuer
@ -3035,13 +2804,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If an explicit response type was specified, don't overwrite it. // If an explicit response type was specified, don't overwrite it.
if (!string.IsNullOrEmpty(context.ResponseType)) if (!string.IsNullOrEmpty(context.ResponseType))
{ {
@ -3233,13 +2997,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If an explicit response type was specified, don't overwrite it. // If an explicit response type was specified, don't overwrite it.
if (!string.IsNullOrEmpty(context.ResponseMode)) if (!string.IsNullOrEmpty(context.ResponseMode))
{ {
@ -3345,13 +3104,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.ClientId ??= context.Registration.ClientId; context.ClientId ??= context.Registration.ClientId;
return default; return default;
@ -3374,12 +3128,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Unlike OpenID Connect, OAuth 2.0 and 2.1 don't require specifying a redirect_uri. // Unlike OpenID Connect, OAuth 2.0 and 2.1 don't require specifying a redirect_uri.
// To keep OpenIddict compatible with OAuth 2.0/2.1 deployments, the redirect_uri // To keep OpenIddict compatible with OAuth 2.0/2.1 deployments, the redirect_uri
@ -3407,13 +3157,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If an explicit set of scopes was specified, don't overwrite it. // If an explicit set of scopes was specified, don't overwrite it.
if (context.Scopes.Count > 0) if (context.Scopes.Count > 0)
{ {
@ -3459,12 +3204,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Generate a new crypto-secure random identifier that will // Generate a new crypto-secure random identifier that will
// be used as the non-guessable part of the state token. // be used as the non-guessable part of the state token.
@ -3497,13 +3238,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await context.Registration.ConfigurationManager.GetConfigurationAsync(default) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
@ -3547,12 +3283,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Don't attach a code challenge method if no authorization code is requested as some implementations // Don't attach a code challenge method if no authorization code is requested as some implementations
// (like OpenIddict server) are known to eagerly block authorization requests that specify an invalid // (like OpenIddict server) are known to eagerly block authorization requests that specify an invalid
@ -3654,13 +3386,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Issuer is { IsAbsoluteUri: true }, SR.GetResourceString(SR.ID4013)); Debug.Assert(context.Issuer is { IsAbsoluteUri: true }, SR.GetResourceString(SR.ID4013));
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -3751,7 +3478,7 @@ public static partial class OpenIddictClientHandlers
{ {
private readonly IOpenIddictClientDispatcher _dispatcher; private readonly IOpenIddictClientDispatcher _dispatcher;
public GenerateStateToken(IOpenIddictClientDispatcher dispatcher) public GenerateStateToken(IOpenIddictClientDispatcher dispatcher!!)
=> _dispatcher = dispatcher; => _dispatcher = dispatcher;
/// <summary> /// <summary>
@ -3766,13 +3493,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessChallengeContext context) public async ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var notification = new GenerateTokenContext(context.Transaction) var notification = new GenerateTokenContext(context.Transaction)
{ {
Principal = context.StateTokenPrincipal!, Principal = context.StateTokenPrincipal!,
@ -3823,12 +3545,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// While OAuth 2.0/2.1 allows sending an authorization request without a redirect_uri, // While OAuth 2.0/2.1 allows sending an authorization request without a redirect_uri,
// doing so is illegal in OpenID Connect and such requests will always be rejected. // doing so is illegal in OpenID Connect and such requests will always be rejected.
@ -3858,12 +3576,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessChallengeContext context) public ValueTask HandleAsync(ProcessChallengeContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Note: while the exact order of the parameters has typically no effect on how requests // Note: while the exact order of the parameters has typically no effect on how requests
// are handled by an authorization server, client_id and redirect_uri are deliberately // are handled by an authorization server, client_id and redirect_uri are deliberately
@ -3919,13 +3633,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(TContext context) public ValueTask HandleAsync(TContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (!string.IsNullOrEmpty(context.Transaction.Response?.Error)) if (!string.IsNullOrEmpty(context.Transaction.Response?.Error))
{ {
context.Reject( context.Reject(
@ -3956,13 +3665,8 @@ public static partial class OpenIddictClientHandlers
.Build(); .Build();
/// <inheritdoc/> /// <inheritdoc/>
public ValueTask HandleAsync(ProcessErrorContext context) public ValueTask HandleAsync(ProcessErrorContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
context.Response.Error = context.Error; context.Response.Error = context.Error;
context.Response.ErrorDescription = context.ErrorDescription; context.Response.ErrorDescription = context.ErrorDescription;
context.Response.ErrorUri = context.ErrorUri; context.Response.ErrorUri = context.ErrorUri;

14
src/OpenIddict.Client/OpenIddictClientHelpers.cs

@ -19,13 +19,8 @@ public static class OpenIddictClientHelpers
/// <param name="name">The property name.</param> /// <param name="name">The property name.</param>
/// <returns>The property value or <c>null</c> if it couldn't be found.</returns> /// <returns>The property value or <c>null</c> if it couldn't be found.</returns>
public static TProperty? GetProperty<TProperty>( public static TProperty? GetProperty<TProperty>(
this OpenIddictClientTransaction transaction, string name) where TProperty : class this OpenIddictClientTransaction transaction!!, string name) where TProperty : class
{ {
if (transaction is null)
{
throw new ArgumentNullException(nameof(transaction));
}
if (string.IsNullOrEmpty(name)) if (string.IsNullOrEmpty(name))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0106), nameof(name)); throw new ArgumentException(SR.GetResourceString(SR.ID0106), nameof(name));
@ -48,14 +43,9 @@ public static class OpenIddictClientHelpers
/// <param name="value">The property value.</param> /// <param name="value">The property value.</param>
/// <returns>The client transaction, so that calls can be easily chained.</returns> /// <returns>The client transaction, so that calls can be easily chained.</returns>
public static OpenIddictClientTransaction SetProperty<TProperty>( public static OpenIddictClientTransaction SetProperty<TProperty>(
this OpenIddictClientTransaction transaction, this OpenIddictClientTransaction transaction!!,
string name, TProperty? value) where TProperty : class string name, TProperty? value) where TProperty : class
{ {
if (transaction is null)
{
throw new ArgumentNullException(nameof(transaction));
}
if (string.IsNullOrEmpty(name)) if (string.IsNullOrEmpty(name))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0106), nameof(name)); throw new ArgumentException(SR.GetResourceString(SR.ID0106), nameof(name));

2
src/OpenIddict.Client/OpenIddictClientOptions.cs

@ -19,7 +19,7 @@ public class OpenIddictClientOptions
/// Note: the list is automatically sorted based on the order assigned to each handler descriptor. /// Note: the list is automatically sorted based on the order assigned to each handler descriptor.
/// As such, it MUST NOT be mutated after options initialization to preserve the exact order. /// As such, it MUST NOT be mutated after options initialization to preserve the exact order.
/// </summary> /// </summary>
public List<OpenIddictClientHandlerDescriptor> Handlers { get; } = new(OpenIddictClientHandlers.DefaultHandlers); public List<OpenIddictClientHandlerDescriptor> Handlers { get; } = new(DefaultHandlers);
/// <summary> /// <summary>
/// Gets the list of encryption credentials used by the OpenIddict client services. /// Gets the list of encryption credentials used by the OpenIddict client services.

5
src/OpenIddict.Client/OpenIddictClientRetriever.cs

@ -16,7 +16,7 @@ public class OpenIddictClientRetriever : IConfigurationRetriever<OpenIddictConfi
/// Creates a new instance of the <see cref="OpenIddictClientRetriever"/> class. /// Creates a new instance of the <see cref="OpenIddictClientRetriever"/> class.
/// </summary> /// </summary>
/// <param name="service">The validation service.</param> /// <param name="service">The validation service.</param>
public OpenIddictClientRetriever(OpenIddictClientService service) public OpenIddictClientRetriever(OpenIddictClientService service!!)
=> _service = service; => _service = service;
/// <summary> /// <summary>
@ -26,7 +26,8 @@ public class OpenIddictClientRetriever : IConfigurationRetriever<OpenIddictConfi
/// <param name="retriever">The retriever used by IdentityModel.</param> /// <param name="retriever">The retriever used by IdentityModel.</param>
/// <param name="cancel">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancel">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The OpenID Connect server configuration retrieved from the remote server.</returns> /// <returns>The OpenID Connect server configuration retrieved from the remote server.</returns>
async Task<OpenIddictConfiguration> IConfigurationRetriever<OpenIddictConfiguration>.GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel) async Task<OpenIddictConfiguration> IConfigurationRetriever<OpenIddictConfiguration>.GetConfigurationAsync(
string address, IDocumentRetriever retriever, CancellationToken cancel)
{ {
if (string.IsNullOrEmpty(address)) if (string.IsNullOrEmpty(address))
{ {

37
src/OpenIddict.Client/OpenIddictClientService.cs

@ -19,7 +19,7 @@ public class OpenIddictClientService
/// Creates a new instance of the <see cref="OpenIddictClientService"/> class. /// Creates a new instance of the <see cref="OpenIddictClientService"/> class.
/// </summary> /// </summary>
/// <param name="provider">The service provider.</param> /// <param name="provider">The service provider.</param>
public OpenIddictClientService(IServiceProvider provider) public OpenIddictClientService(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>
@ -28,13 +28,8 @@ public class OpenIddictClientService
/// <param name="address">The address of the remote metadata endpoint.</param> /// <param name="address">The address of the remote metadata endpoint.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The OpenID Connect server configuration retrieved from the remote server.</returns> /// <returns>The OpenID Connect server configuration retrieved from the remote server.</returns>
public async ValueTask<OpenIddictConfiguration> GetConfigurationAsync(Uri address, CancellationToken cancellationToken = default) public async ValueTask<OpenIddictConfiguration> GetConfigurationAsync(Uri address!!, CancellationToken cancellationToken = default)
{ {
if (address is null)
{
throw new ArgumentNullException(nameof(address));
}
if (!address.IsAbsoluteUri) if (!address.IsAbsoluteUri)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(address)); throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(address));
@ -172,13 +167,8 @@ public class OpenIddictClientService
/// <param name="address">The address of the remote metadata endpoint.</param> /// <param name="address">The address of the remote metadata endpoint.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The security keys retrieved from the remote server.</returns> /// <returns>The security keys retrieved from the remote server.</returns>
public async ValueTask<JsonWebKeySet> GetSecurityKeysAsync(Uri address, CancellationToken cancellationToken = default) public async ValueTask<JsonWebKeySet> GetSecurityKeysAsync(Uri address!!, CancellationToken cancellationToken = default)
{ {
if (address is null)
{
throw new ArgumentNullException(nameof(address));
}
if (!address.IsAbsoluteUri) if (!address.IsAbsoluteUri)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(address)); throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(address));
@ -319,13 +309,8 @@ public class OpenIddictClientService
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The response and a merged principal containing the claims extracted from the tokens and userinfo response.</returns> /// <returns>The response and a merged principal containing the claims extracted from the tokens and userinfo response.</returns>
public async ValueTask<(OpenIddictResponse Response, ClaimsPrincipal Principal)> RefreshTokensAsync( public async ValueTask<(OpenIddictResponse Response, ClaimsPrincipal Principal)> RefreshTokensAsync(
OpenIddictClientRegistration registration, string token, CancellationToken cancellationToken = default) OpenIddictClientRegistration registration!!, string token, CancellationToken cancellationToken = default)
{ {
if (registration is null)
{
throw new ArgumentNullException(nameof(registration));
}
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0156), nameof(token)); throw new ArgumentException(SR.GetResourceString(SR.ID0156), nameof(token));
@ -442,13 +427,8 @@ public class OpenIddictClientService
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The token response.</returns> /// <returns>The token response.</returns>
public async ValueTask<OpenIddictResponse> SendTokenRequestAsync( public async ValueTask<OpenIddictResponse> SendTokenRequestAsync(
OpenIddictClientRegistration registration, OpenIddictRequest request, CancellationToken cancellationToken = default) OpenIddictClientRegistration registration!!, OpenIddictRequest request, CancellationToken cancellationToken = default)
{ {
if (registration is null)
{
throw new ArgumentNullException(nameof(registration));
}
var configuration = await registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await registration.ConfigurationManager.GetConfigurationAsync(default) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
@ -594,13 +574,8 @@ public class OpenIddictClientService
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The response and the principal extracted from the userinfo response or the userinfo token.</returns> /// <returns>The response and the principal extracted from the userinfo response or the userinfo token.</returns>
public async ValueTask<(OpenIddictResponse Response, (ClaimsPrincipal? Principal, string? Token))> SendUserinfoRequestAsync( public async ValueTask<(OpenIddictResponse Response, (ClaimsPrincipal? Principal, string? Token))> SendUserinfoRequestAsync(
OpenIddictClientRegistration registration, OpenIddictRequest request, CancellationToken cancellationToken = default) OpenIddictClientRegistration registration!!, OpenIddictRequest request, CancellationToken cancellationToken = default)
{ {
if (registration is null)
{
throw new ArgumentNullException(nameof(registration));
}
var configuration = await registration.ConfigurationManager.GetConfigurationAsync(default) ?? var configuration = await registration.ConfigurationManager.GetConfigurationAsync(default) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));

47
src/OpenIddict.Core/Caches/OpenIddictApplicationCache.cs

@ -24,8 +24,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
private readonly IOpenIddictApplicationStore<TApplication> _store; private readonly IOpenIddictApplicationStore<TApplication> _store;
public OpenIddictApplicationCache( public OpenIddictApplicationCache(
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictApplicationStoreResolver resolver) IOpenIddictApplicationStoreResolver resolver!!)
{ {
_cache = new MemoryCache(new MemoryCacheOptions _cache = new MemoryCache(new MemoryCacheOptions
{ {
@ -37,13 +37,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask AddAsync(TApplication application, CancellationToken cancellationToken) public async ValueTask AddAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
_cache.Remove(new _cache.Remove(new
{ {
Method = nameof(FindByClientIdAsync), Method = nameof(FindByClientIdAsync),
@ -114,10 +109,10 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
if (_cache.TryGetValue(parameters, out TApplication? application)) if (_cache.TryGetValue(parameters, out TApplication? application))
{ {
return new ValueTask<TApplication?>(application); return new(application);
} }
return new ValueTask<TApplication?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TApplication?> ExecuteAsync() async Task<TApplication?> ExecuteAsync()
{ {
@ -148,10 +143,10 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
if (_cache.TryGetValue(parameters, out TApplication? application)) if (_cache.TryGetValue(parameters, out TApplication? application))
{ {
return new ValueTask<TApplication?>(application); return new(application);
} }
return new ValueTask<TApplication?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TApplication?> ExecuteAsync() async Task<TApplication?> ExecuteAsync()
{ {
@ -249,13 +244,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask RemoveAsync(TApplication application, CancellationToken cancellationToken) public async ValueTask RemoveAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var identifier = await _store.GetIdAsync(application, cancellationToken); var identifier = await _store.GetIdAsync(application, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {
@ -276,13 +266,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
/// <param name="application">The application to store in the cache entry, if applicable.</param> /// <param name="application">The application to store in the cache entry, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync(object key, TApplication? application, CancellationToken cancellationToken) protected virtual async ValueTask CreateEntryAsync(object key!!, TApplication? application, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
if (application is not null) if (application is not null)
@ -308,13 +293,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync( protected virtual async ValueTask CreateEntryAsync(
object key, ImmutableArray<TApplication> applications, CancellationToken cancellationToken) object key!!, ImmutableArray<TApplication> applications, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
foreach (var application in applications) foreach (var application in applications)
@ -343,13 +323,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
/// whose result returns an expiration signal for the specified application. /// whose result returns an expiration signal for the specified application.
/// </returns> /// </returns>
protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync( protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(
TApplication application, CancellationToken cancellationToken) TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var identifier = await _store.GetIdAsync(application, cancellationToken); var identifier = await _store.GetIdAsync(application, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {

43
src/OpenIddict.Core/Caches/OpenIddictAuthorizationCache.cs

@ -24,8 +24,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
private readonly IOpenIddictAuthorizationStore<TAuthorization> _store; private readonly IOpenIddictAuthorizationStore<TAuthorization> _store;
public OpenIddictAuthorizationCache( public OpenIddictAuthorizationCache(
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictAuthorizationStoreResolver resolver) IOpenIddictAuthorizationStoreResolver resolver!!)
{ {
_cache = new MemoryCache(new MemoryCacheOptions _cache = new MemoryCache(new MemoryCacheOptions
{ {
@ -37,13 +37,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask AddAsync(TAuthorization authorization, CancellationToken cancellationToken) public async ValueTask AddAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
_cache.Remove(new _cache.Remove(new
{ {
Method = nameof(FindAsync), Method = nameof(FindAsync),
@ -365,10 +360,10 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
if (_cache.TryGetValue(parameters, out TAuthorization? authorization)) if (_cache.TryGetValue(parameters, out TAuthorization? authorization))
{ {
return new ValueTask<TAuthorization?>(authorization); return new(authorization);
} }
return new ValueTask<TAuthorization?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TAuthorization?> ExecuteAsync() async Task<TAuthorization?> ExecuteAsync()
{ {
@ -425,13 +420,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask RemoveAsync(TAuthorization authorization, CancellationToken cancellationToken) public async ValueTask RemoveAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var identifier = await _store.GetIdAsync(authorization, cancellationToken); var identifier = await _store.GetIdAsync(authorization, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {
@ -452,13 +442,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
/// <param name="authorization">The authorization to store in the cache entry, if applicable.</param> /// <param name="authorization">The authorization to store in the cache entry, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync(object key, TAuthorization? authorization, CancellationToken cancellationToken) protected virtual async ValueTask CreateEntryAsync(object key!!, TAuthorization? authorization, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
if (authorization is not null) if (authorization is not null)
@ -484,13 +469,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync( protected virtual async ValueTask CreateEntryAsync(
object key, ImmutableArray<TAuthorization> authorizations, CancellationToken cancellationToken) object key!!, ImmutableArray<TAuthorization> authorizations, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
foreach (var authorization in authorizations) foreach (var authorization in authorizations)
@ -519,13 +499,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
/// whose result returns an expiration signal for the specified authorization. /// whose result returns an expiration signal for the specified authorization.
/// </returns> /// </returns>
protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync( protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(
TAuthorization authorization, CancellationToken cancellationToken) TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var identifier = await _store.GetIdAsync(authorization, cancellationToken); var identifier = await _store.GetIdAsync(authorization, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {

49
src/OpenIddict.Core/Caches/OpenIddictScopeCache.cs

@ -24,8 +24,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
private readonly IOpenIddictScopeStore<TScope> _store; private readonly IOpenIddictScopeStore<TScope> _store;
public OpenIddictScopeCache( public OpenIddictScopeCache(
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictScopeStoreResolver resolver) IOpenIddictScopeStoreResolver resolver!!)
{ {
_cache = new MemoryCache(new MemoryCacheOptions _cache = new MemoryCache(new MemoryCacheOptions
{ {
@ -37,13 +37,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask AddAsync(TScope scope, CancellationToken cancellationToken) public async ValueTask AddAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
_cache.Remove(new _cache.Remove(new
{ {
Method = nameof(FindByIdAsync), Method = nameof(FindByIdAsync),
@ -105,10 +100,10 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
if (_cache.TryGetValue(parameters, out TScope? scope)) if (_cache.TryGetValue(parameters, out TScope? scope))
{ {
return new ValueTask<TScope?>(scope); return new(scope);
} }
return new ValueTask<TScope?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TScope?> ExecuteAsync() async Task<TScope?> ExecuteAsync()
{ {
@ -139,7 +134,7 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
if (_cache.TryGetValue(parameters, out TScope? scope)) if (_cache.TryGetValue(parameters, out TScope? scope))
{ {
return new ValueTask<TScope?>(scope); return new(scope);
} }
async Task<TScope?> ExecuteAsync() async Task<TScope?> ExecuteAsync()
@ -154,13 +149,13 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
return scope; return scope;
} }
return new ValueTask<TScope?>(ExecuteAsync()); return new(ExecuteAsync());
} }
/// <inheritdoc/> /// <inheritdoc/>
public IAsyncEnumerable<TScope> FindByNamesAsync(ImmutableArray<string> names, CancellationToken cancellationToken) public IAsyncEnumerable<TScope> FindByNamesAsync(ImmutableArray<string> names, CancellationToken cancellationToken)
{ {
if (names.Any(name => string.IsNullOrEmpty(name))) if (names.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
@ -222,13 +217,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask RemoveAsync(TScope scope, CancellationToken cancellationToken) public async ValueTask RemoveAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var identifier = await _store.GetIdAsync(scope, cancellationToken); var identifier = await _store.GetIdAsync(scope, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {
@ -249,13 +239,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
/// <param name="scope">The scope to store in the cache entry, if applicable.</param> /// <param name="scope">The scope to store in the cache entry, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync(object key, TScope? scope, CancellationToken cancellationToken) protected virtual async ValueTask CreateEntryAsync(object key!!, TScope? scope, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
if (scope is not null) if (scope is not null)
@ -281,13 +266,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync( protected virtual async ValueTask CreateEntryAsync(
object key, ImmutableArray<TScope> scopes, CancellationToken cancellationToken) object key!!, ImmutableArray<TScope> scopes, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
foreach (var scope in scopes) foreach (var scope in scopes)
@ -315,13 +295,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation,
/// whose result returns an expiration signal for the specified scope. /// whose result returns an expiration signal for the specified scope.
/// </returns> /// </returns>
protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(TScope scope, CancellationToken cancellationToken) protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var identifier = await _store.GetIdAsync(scope, cancellationToken); var identifier = await _store.GetIdAsync(scope, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {

47
src/OpenIddict.Core/Caches/OpenIddictTokenCache.cs

@ -24,8 +24,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
private readonly IOpenIddictTokenStore<TToken> _store; private readonly IOpenIddictTokenStore<TToken> _store;
public OpenIddictTokenCache( public OpenIddictTokenCache(
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictTokenStoreResolver resolver) IOpenIddictTokenStoreResolver resolver!!)
{ {
_cache = new MemoryCache(new MemoryCacheOptions _cache = new MemoryCache(new MemoryCacheOptions
{ {
@ -37,13 +37,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask AddAsync(TToken token, CancellationToken cancellationToken) public async ValueTask AddAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
_cache.Remove(new _cache.Remove(new
{ {
Method = nameof(FindAsync), Method = nameof(FindAsync),
@ -383,10 +378,10 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
if (_cache.TryGetValue(parameters, out TToken? token)) if (_cache.TryGetValue(parameters, out TToken? token))
{ {
return new ValueTask<TToken?>(token); return new(token);
} }
return new ValueTask<TToken?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TToken?> ExecuteAsync() async Task<TToken?> ExecuteAsync()
{ {
@ -417,10 +412,10 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
if (_cache.TryGetValue(parameters, out TToken? token)) if (_cache.TryGetValue(parameters, out TToken? token))
{ {
return new ValueTask<TToken?>(token); return new(token);
} }
return new ValueTask<TToken?>(ExecuteAsync()); return new(ExecuteAsync());
async Task<TToken?> ExecuteAsync() async Task<TToken?> ExecuteAsync()
{ {
@ -477,13 +472,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
} }
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask RemoveAsync(TToken token, CancellationToken cancellationToken) public async ValueTask RemoveAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var identifier = await _store.GetIdAsync(token, cancellationToken); var identifier = await _store.GetIdAsync(token, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {
@ -504,13 +494,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
/// <param name="token">The token to store in the cache entry, if applicable.</param> /// <param name="token">The token to store in the cache entry, if applicable.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync(object key, TToken? token, CancellationToken cancellationToken) protected virtual async ValueTask CreateEntryAsync(object key!!, TToken? token, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
if (token is not null) if (token is not null)
@ -536,13 +521,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns> /// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
protected virtual async ValueTask CreateEntryAsync( protected virtual async ValueTask CreateEntryAsync(
object key, ImmutableArray<TToken> tokens, CancellationToken cancellationToken) object key!!, ImmutableArray<TToken> tokens, CancellationToken cancellationToken)
{ {
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
using var entry = _cache.CreateEntry(key); using var entry = _cache.CreateEntry(key);
foreach (var token in tokens) foreach (var token in tokens)
@ -570,13 +550,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation,
/// whose result returns an expiration signal for the specified token. /// whose result returns an expiration signal for the specified token.
/// </returns> /// </returns>
protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(TToken token, CancellationToken cancellationToken) protected virtual async ValueTask<IChangeToken> CreateExpirationSignalAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var identifier = await _store.GetIdAsync(token, cancellationToken); var identifier = await _store.GetIdAsync(token, cancellationToken);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
{ {

330
src/OpenIddict.Core/Managers/OpenIddictApplicationManager.cs

@ -41,10 +41,10 @@ namespace OpenIddict.Core;
public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplicationManager where TApplication : class public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplicationManager where TApplication : class
{ {
public OpenIddictApplicationManager( public OpenIddictApplicationManager(
IOpenIddictApplicationCache<TApplication> cache, IOpenIddictApplicationCache<TApplication> cache!!,
ILogger<OpenIddictApplicationManager<TApplication>> logger, ILogger<OpenIddictApplicationManager<TApplication>> logger!!,
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictApplicationStoreResolver resolver) IOpenIddictApplicationStoreResolver resolver!!)
{ {
Cache = cache; Cache = cache;
Logger = logger; Logger = logger;
@ -94,15 +94,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the number of applications that match the specified query. /// whose result returns the number of applications that match the specified query.
/// </returns> /// </returns>
public virtual ValueTask<long> CountAsync<TResult>( public virtual ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => Store.CountAsync(query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.CountAsync(query, cancellationToken);
}
/// <summary> /// <summary>
/// Creates a new application. /// Creates a new application.
@ -126,13 +119,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask CreateAsync(TApplication application, string? secret, CancellationToken cancellationToken = default) public virtual async ValueTask CreateAsync(TApplication application!!, string? secret, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (!string.IsNullOrEmpty(await Store.GetClientSecretAsync(application, cancellationToken))) if (!string.IsNullOrEmpty(await Store.GetClientSecretAsync(application, cancellationToken)))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0206), nameof(application)); throw new ArgumentException(SR.GetResourceString(SR.ID0206), nameof(application));
@ -201,13 +189,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the unique identifier associated with the application. /// whose result returns the unique identifier associated with the application.
/// </returns> /// </returns>
public virtual async ValueTask<TApplication> CreateAsync( public virtual async ValueTask<TApplication> CreateAsync(
OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictApplicationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var application = await Store.InstantiateAsync(cancellationToken); var application = await Store.InstantiateAsync(cancellationToken);
if (application is null) if (application is null)
{ {
@ -238,13 +221,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask DeleteAsync(TApplication application, CancellationToken cancellationToken = default) public virtual async ValueTask DeleteAsync(TApplication application!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (!Options.CurrentValue.DisableEntityCaching) if (!Options.CurrentValue.DisableEntityCaching)
{ {
await Cache.RemoveAsync(application, cancellationToken); await Cache.RemoveAsync(application, cancellationToken);
@ -423,15 +401,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TResult>( public virtual ValueTask<TResult?> GetAsync<TResult>(
Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => GetAsync(static (applications, query) => query(applications), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return GetAsync(static (applications, query) => query(applications), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -446,16 +417,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TState, TResult>( public virtual ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.GetAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.GetAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the client identifier associated with an application. /// Retrieves the client identifier associated with an application.
@ -467,15 +431,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the client identifier associated with the application. /// whose result returns the client identifier associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetClientIdAsync( public virtual ValueTask<string?> GetClientIdAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetClientIdAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetClientIdAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the client type associated with an application. /// Retrieves the client type associated with an application.
@ -487,15 +444,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the client type of the application (by default, "public"). /// whose result returns the client type of the application (by default, "public").
/// </returns> /// </returns>
public virtual ValueTask<string?> GetClientTypeAsync( public virtual ValueTask<string?> GetClientTypeAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetClientTypeAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetClientTypeAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the consent type associated with an application. /// Retrieves the consent type associated with an application.
@ -507,13 +457,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the consent type of the application (by default, "explicit"). /// whose result returns the consent type of the application (by default, "explicit").
/// </returns> /// </returns>
public virtual async ValueTask<string?> GetConsentTypeAsync( public virtual async ValueTask<string?> GetConsentTypeAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var type = await Store.GetConsentTypeAsync(application, cancellationToken); var type = await Store.GetConsentTypeAsync(application, cancellationToken);
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
@ -533,15 +478,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the display name associated with the application. /// whose result returns the display name associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetDisplayNameAsync( public virtual ValueTask<string?> GetDisplayNameAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetDisplayNameAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetDisplayNameAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the localized display names associated with an application. /// Retrieves the localized display names associated with an application.
@ -553,21 +491,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the localized display names associated with the application. /// whose result returns all the localized display names associated with the application.
/// </returns> /// </returns>
public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync( public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => await Store.GetDisplayNamesAsync(application, cancellationToken) is { Count: > 0 } names ?
if (application is null) names : ImmutableDictionary.Create<CultureInfo, string>();
{
throw new ArgumentNullException(nameof(application));
}
var names = await Store.GetDisplayNamesAsync(application, cancellationToken);
if (names is null || names.Count == 0)
{
return ImmutableDictionary.Create<CultureInfo, string>();
}
return names;
}
/// <summary> /// <summary>
/// Retrieves the unique identifier associated with an application. /// Retrieves the unique identifier associated with an application.
@ -578,15 +504,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the application. /// whose result returns the unique identifier associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetIdAsync(TApplication application, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetIdAsync(TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetIdAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetIdAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the localized display name associated with an application /// Retrieves the localized display name associated with an application
@ -616,20 +535,10 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns the matching localized display name associated with the application. /// whose result returns the matching localized display name associated with the application.
/// </returns> /// </returns>
public virtual async ValueTask<string?> GetLocalizedDisplayNameAsync( public virtual async ValueTask<string?> GetLocalizedDisplayNameAsync(
TApplication application, CultureInfo culture, CancellationToken cancellationToken = default) TApplication application!!, CultureInfo culture!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (culture is null)
{
throw new ArgumentNullException(nameof(culture));
}
var names = await Store.GetDisplayNamesAsync(application, cancellationToken); var names = await Store.GetDisplayNamesAsync(application, cancellationToken);
if (names is null || names.IsEmpty) if (names is not { IsEmpty: false })
{ {
return await Store.GetDisplayNameAsync(application, cancellationToken); return await Store.GetDisplayNameAsync(application, cancellationToken);
} }
@ -659,15 +568,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the permissions associated with the application. /// whose result returns all the permissions associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync( public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetPermissionsAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetPermissionsAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the logout callback addresses associated with an application. /// Retrieves the logout callback addresses associated with an application.
@ -679,15 +581,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the post_logout_redirect_uri associated with the application. /// whose result returns all the post_logout_redirect_uri associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync( public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetPostLogoutRedirectUrisAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetPostLogoutRedirectUrisAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the additional properties associated with an application. /// Retrieves the additional properties associated with an application.
@ -699,15 +594,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the additional properties associated with the application. /// whose result returns all the additional properties associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync( public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetPropertiesAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetPropertiesAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the callback addresses associated with an application. /// Retrieves the callback addresses associated with an application.
@ -719,15 +607,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the redirect_uri associated with the application. /// whose result returns all the redirect_uri associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync( public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetRedirectUrisAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetRedirectUrisAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the requirements associated with an application. /// Retrieves the requirements associated with an application.
@ -739,15 +620,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns all the requirements associated with the application. /// whose result returns all the requirements associated with the application.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync( public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ => Store.GetRequirementsAsync(application, cancellationToken);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return Store.GetRequirementsAsync(application, cancellationToken);
}
/// <summary> /// <summary>
/// Determines whether a given application has the specified client type. /// Determines whether a given application has the specified client type.
@ -757,13 +631,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the application has the specified client type, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the application has the specified client type, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasClientTypeAsync( public virtual async ValueTask<bool> HasClientTypeAsync(
TApplication application, string type, CancellationToken cancellationToken = default) TApplication application!!, string type, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0209), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0209), nameof(type));
@ -780,13 +649,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the application has the specified consent type, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the application has the specified consent type, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasConsentTypeAsync( public virtual async ValueTask<bool> HasConsentTypeAsync(
TApplication application, string type, CancellationToken cancellationToken = default) TApplication application!!, string type, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0210), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0210), nameof(type));
@ -803,13 +667,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the application has been granted the specified permission, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the application has been granted the specified permission, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasPermissionAsync( public virtual async ValueTask<bool> HasPermissionAsync(
TApplication application, string permission, CancellationToken cancellationToken = default) TApplication application!!, string permission, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(permission)) if (string.IsNullOrEmpty(permission))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0211), nameof(permission)); throw new ArgumentException(SR.GetResourceString(SR.ID0211), nameof(permission));
@ -826,13 +685,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the requirement has been enforced for the specified application, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the requirement has been enforced for the specified application, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasRequirementAsync( public virtual async ValueTask<bool> HasRequirementAsync(
TApplication application, string requirement, CancellationToken cancellationToken = default) TApplication application!!, string requirement, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(requirement)) if (string.IsNullOrEmpty(requirement))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0212), nameof(requirement)); throw new ArgumentException(SR.GetResourceString(SR.ID0212), nameof(requirement));
@ -860,15 +714,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TResult>(
Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => ListAsync(static (applications, query) => query(applications), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ListAsync(static (applications, query) => query(applications), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns all the corresponding elements. /// Executes the specified query and returns all the corresponding elements.
@ -880,16 +727,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.ListAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.ListAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Populates the application using the specified descriptor. /// Populates the application using the specified descriptor.
@ -900,19 +740,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync(TApplication application, public virtual async ValueTask PopulateAsync(TApplication application!!,
OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictApplicationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await Store.SetClientIdAsync(application, descriptor.ClientId, cancellationToken); await Store.SetClientIdAsync(application, descriptor.ClientId, cancellationToken);
await Store.SetClientSecretAsync(application, descriptor.ClientSecret, cancellationToken); await Store.SetClientSecretAsync(application, descriptor.ClientSecret, cancellationToken);
await Store.SetClientTypeAsync(application, descriptor.Type, cancellationToken); await Store.SetClientTypeAsync(application, descriptor.Type, cancellationToken);
@ -938,19 +768,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync( public virtual async ValueTask PopulateAsync(
OpenIddictApplicationDescriptor descriptor, OpenIddictApplicationDescriptor descriptor!!,
TApplication application, CancellationToken cancellationToken = default) TApplication application!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
descriptor.ClientId = await Store.GetClientIdAsync(application, cancellationToken); descriptor.ClientId = await Store.GetClientIdAsync(application, cancellationToken);
descriptor.ClientSecret = await Store.GetClientSecretAsync(application, cancellationToken); descriptor.ClientSecret = await Store.GetClientSecretAsync(application, cancellationToken);
descriptor.ConsentType = await Store.GetConsentTypeAsync(application, cancellationToken); descriptor.ConsentType = await Store.GetConsentTypeAsync(application, cancellationToken);
@ -1018,13 +838,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TApplication application, CancellationToken cancellationToken = default) public virtual async ValueTask UpdateAsync(TApplication application!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var results = await GetValidationResultsAsync(application, cancellationToken); var results = await GetValidationResultsAsync(application, cancellationToken);
if (results.Any(result => result != ValidationResult.Success)) if (results.Any(result => result != ValidationResult.Success))
{ {
@ -1073,13 +888,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TApplication application, string? secret, CancellationToken cancellationToken = default) public virtual async ValueTask UpdateAsync(TApplication application!!, string? secret, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(secret)) if (string.IsNullOrEmpty(secret))
{ {
await Store.SetClientSecretAsync(application, null, cancellationToken); await Store.SetClientSecretAsync(application, null, cancellationToken);
@ -1103,18 +913,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TApplication application, public virtual async ValueTask UpdateAsync(TApplication application!!,
OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictApplicationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
// Store the original client secret for later comparison. // Store the original client secret for later comparison.
var comparand = await Store.GetClientSecretAsync(application, cancellationToken); var comparand = await Store.GetClientSecretAsync(application, cancellationToken);
@ -1139,12 +940,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The validation error encountered when validating the application.</returns> /// <returns>The validation error encountered when validating the application.</returns>
public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync( public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync(
TApplication application, [EnumeratorCancellation] CancellationToken cancellationToken = default) TApplication application!!, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
// Ensure the client_id is not null or empty and is not already used for a different application. // Ensure the client_id is not null or empty and is not already used for a different application.
var identifier = await Store.GetClientIdAsync(application, cancellationToken); var identifier = await Store.GetClientIdAsync(application, cancellationToken);
@ -1254,12 +1051,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns a boolean indicating whether the client secret was valid. /// whose result returns a boolean indicating whether the client secret was valid.
/// </returns> /// </returns>
public virtual async ValueTask<bool> ValidateClientSecretAsync( public virtual async ValueTask<bool> ValidateClientSecretAsync(
TApplication application, string secret, CancellationToken cancellationToken = default) TApplication application!!, string secret, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(secret)) if (string.IsNullOrEmpty(secret))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0216), nameof(secret)); throw new ArgumentException(SR.GetResourceString(SR.ID0216), nameof(secret));
@ -1301,13 +1094,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
/// whose result returns a boolean indicating whether the redirect_uri was valid. /// whose result returns a boolean indicating whether the redirect_uri was valid.
/// </returns> /// </returns>
public virtual async ValueTask<bool> ValidateRedirectUriAsync( public virtual async ValueTask<bool> ValidateRedirectUriAsync(
TApplication application, string address, CancellationToken cancellationToken = default) TApplication application!!, string address, CancellationToken cancellationToken = default)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(address)) if (string.IsNullOrEmpty(address))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0143), nameof(address)); throw new ArgumentException(SR.GetResourceString(SR.ID0143), nameof(address));
@ -1358,7 +1146,7 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
var hash = HashSecret(secret, salt, HashAlgorithmName.SHA256, iterations: 10_000, length: 256 / 8); var hash = HashSecret(secret, salt, HashAlgorithmName.SHA256, iterations: 10_000, length: 256 / 8);
return new ValueTask<string>( return new(
#if SUPPORTS_BASE64_SPAN_CONVERSION #if SUPPORTS_BASE64_SPAN_CONVERSION
Convert.ToBase64String(hash) Convert.ToBase64String(hash)
#else #else
@ -1431,14 +1219,14 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
try try
{ {
return new ValueTask<bool>(VerifyHashedSecret(comparand, secret)); return new(VerifyHashedSecret(comparand, secret));
} }
catch (Exception exception) catch (Exception exception)
{ {
Logger.LogWarning(exception, SR.GetResourceString(SR.ID6163)); Logger.LogWarning(exception, SR.GetResourceString(SR.ID6163));
return new ValueTask<bool>(false); return new(false);
} }
// Note: the following logic deliberately uses the same format as CryptoHelper (used in OpenIddict 1.x/2.x), // Note: the following logic deliberately uses the same format as CryptoHelper (used in OpenIddict 1.x/2.x),

267
src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs

@ -28,10 +28,10 @@ namespace OpenIddict.Core;
public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthorizationManager where TAuthorization : class public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthorizationManager where TAuthorization : class
{ {
public OpenIddictAuthorizationManager( public OpenIddictAuthorizationManager(
IOpenIddictAuthorizationCache<TAuthorization> cache, IOpenIddictAuthorizationCache<TAuthorization> cache!!,
ILogger<OpenIddictAuthorizationManager<TAuthorization>> logger, ILogger<OpenIddictAuthorizationManager<TAuthorization>> logger!!,
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictAuthorizationStoreResolver resolver) IOpenIddictAuthorizationStoreResolver resolver!!)
{ {
Cache = cache; Cache = cache;
Logger = logger; Logger = logger;
@ -81,15 +81,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the number of authorizations that match the specified query. /// whose result returns the number of authorizations that match the specified query.
/// </returns> /// </returns>
public virtual ValueTask<long> CountAsync<TResult>( public virtual ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => Store.CountAsync(query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.CountAsync(query, cancellationToken);
}
/// <summary> /// <summary>
/// Creates a new authorization. /// Creates a new authorization.
@ -99,13 +92,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask CreateAsync(TAuthorization authorization, CancellationToken cancellationToken = default) public virtual async ValueTask CreateAsync(TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
// If no status was explicitly specified, assume that the authorization is valid. // If no status was explicitly specified, assume that the authorization is valid.
if (string.IsNullOrEmpty(await Store.GetStatusAsync(authorization, cancellationToken))) if (string.IsNullOrEmpty(await Store.GetStatusAsync(authorization, cancellationToken)))
{ {
@ -157,13 +145,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the authorization. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the authorization.
/// </returns> /// </returns>
public virtual async ValueTask<TAuthorization> CreateAsync( public virtual async ValueTask<TAuthorization> CreateAsync(
OpenIddictAuthorizationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictAuthorizationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var authorization = await Store.InstantiateAsync(cancellationToken); var authorization = await Store.InstantiateAsync(cancellationToken);
if (authorization is null) if (authorization is null)
{ {
@ -189,14 +172,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the authorization. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the authorization.
/// </returns> /// </returns>
public virtual ValueTask<TAuthorization> CreateAsync( public virtual ValueTask<TAuthorization> CreateAsync(
ClaimsPrincipal principal, string subject, string client, ClaimsPrincipal principal!!, string subject, string client,
string type, ImmutableArray<string> scopes, CancellationToken cancellationToken = default) string type, ImmutableArray<string> scopes, CancellationToken cancellationToken = default)
{ {
if (principal is null)
{
throw new ArgumentNullException(nameof(principal));
}
if (string.IsNullOrEmpty(subject)) if (string.IsNullOrEmpty(subject))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject)); throw new ArgumentException(SR.GetResourceString(SR.ID0198), nameof(subject));
@ -235,13 +213,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask DeleteAsync(TAuthorization authorization, CancellationToken cancellationToken = default) public virtual async ValueTask DeleteAsync(TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (!Options.CurrentValue.DisableEntityCaching) if (!Options.CurrentValue.DisableEntityCaching)
{ {
await Cache.RemoveAsync(authorization, cancellationToken); await Cache.RemoveAsync(authorization, cancellationToken);
@ -614,15 +587,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the application identifier associated with the authorization. /// whose result returns the application identifier associated with the authorization.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetApplicationIdAsync( public virtual ValueTask<string?> GetApplicationIdAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetApplicationIdAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetApplicationIdAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -635,15 +601,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TResult>( public virtual ValueTask<TResult?> GetAsync<TResult>(
Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => GetAsync(static (authorizations, query) => query(authorizations), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return GetAsync(static (authorizations, query) => query(authorizations), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -658,16 +617,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TState, TResult>( public virtual ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.GetAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.GetAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the creation date associated with an authorization. /// Retrieves the creation date associated with an authorization.
@ -679,15 +631,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the creation date associated with the specified authorization. /// whose result returns the creation date associated with the specified authorization.
/// </returns> /// </returns>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync( public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetCreationDateAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetCreationDateAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the unique identifier associated with an authorization. /// Retrieves the unique identifier associated with an authorization.
@ -698,15 +643,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the authorization. /// whose result returns the unique identifier associated with the authorization.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetIdAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetIdAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the additional properties associated with an authorization. /// Retrieves the additional properties associated with an authorization.
@ -718,15 +656,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns all the additional properties associated with the authorization. /// whose result returns all the additional properties associated with the authorization.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync( public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetPropertiesAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetPropertiesAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the scopes associated with an authorization. /// Retrieves the scopes associated with an authorization.
@ -738,15 +669,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the scopes associated with the specified authorization. /// whose result returns the scopes associated with the specified authorization.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetScopesAsync( public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetScopesAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetScopesAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the status associated with an authorization. /// Retrieves the status associated with an authorization.
@ -758,15 +682,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the status associated with the specified authorization. /// whose result returns the status associated with the specified authorization.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetStatusAsync( public virtual ValueTask<string?> GetStatusAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetStatusAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetStatusAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the subject associated with an authorization. /// Retrieves the subject associated with an authorization.
@ -778,15 +695,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the subject associated with the specified authorization. /// whose result returns the subject associated with the specified authorization.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetSubjectAsync( public virtual ValueTask<string?> GetSubjectAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetSubjectAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetSubjectAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the type associated with an authorization. /// Retrieves the type associated with an authorization.
@ -798,15 +708,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// whose result returns the type associated with the specified authorization. /// whose result returns the type associated with the specified authorization.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetTypeAsync( public virtual ValueTask<string?> GetTypeAsync(
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ => Store.GetTypeAsync(authorization, cancellationToken);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return Store.GetTypeAsync(authorization, cancellationToken);
}
/// <summary> /// <summary>
/// Determines whether the specified scopes are included in the authorization. /// Determines whether the specified scopes are included in the authorization.
@ -815,17 +718,10 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="scopes">The scopes.</param> /// <param name="scopes">The scopes.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the scopes are included in the authorization, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the scopes are included in the authorization, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasScopesAsync(TAuthorization authorization, public virtual async ValueTask<bool> HasScopesAsync(TAuthorization authorization!!,
ImmutableArray<string> scopes, CancellationToken cancellationToken = default) ImmutableArray<string> scopes, CancellationToken cancellationToken = default)
{ => new HashSet<string>(await Store.GetScopesAsync(
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new HashSet<string>(await Store.GetScopesAsync(
authorization, cancellationToken), StringComparer.Ordinal).IsSupersetOf(scopes); authorization, cancellationToken), StringComparer.Ordinal).IsSupersetOf(scopes);
}
/// <summary> /// <summary>
/// Determines whether a given authorization has the specified status. /// Determines whether a given authorization has the specified status.
@ -834,14 +730,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="status">The expected status.</param> /// <param name="status">The expected status.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the authorization has the specified status, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the authorization has the specified status, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasStatusAsync(TAuthorization authorization, public virtual async ValueTask<bool> HasStatusAsync(TAuthorization authorization!!,
string status, CancellationToken cancellationToken = default) string status, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(status)) if (string.IsNullOrEmpty(status))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status)); throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status));
@ -858,13 +749,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the authorization has the specified type, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the authorization has the specified type, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasTypeAsync( public virtual async ValueTask<bool> HasTypeAsync(
TAuthorization authorization, string type, CancellationToken cancellationToken = default) TAuthorization authorization!!, string type, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0200), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0200), nameof(type));
@ -892,15 +778,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TResult>(
Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => ListAsync(static (authorizations, query) => query(authorizations), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ListAsync(static (authorizations, query) => query(authorizations), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns all the corresponding elements. /// Executes the specified query and returns all the corresponding elements.
@ -912,16 +791,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.ListAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.ListAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Populates the authorization using the specified descriptor. /// Populates the authorization using the specified descriptor.
@ -932,19 +804,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync(TAuthorization authorization, public virtual async ValueTask PopulateAsync(TAuthorization authorization!!,
OpenIddictAuthorizationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictAuthorizationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await Store.SetApplicationIdAsync(authorization, descriptor.ApplicationId, cancellationToken); await Store.SetApplicationIdAsync(authorization, descriptor.ApplicationId, cancellationToken);
await Store.SetCreationDateAsync(authorization, descriptor.CreationDate, cancellationToken); await Store.SetCreationDateAsync(authorization, descriptor.CreationDate, cancellationToken);
await Store.SetPropertiesAsync(authorization, descriptor.Properties.ToImmutableDictionary(), cancellationToken); await Store.SetPropertiesAsync(authorization, descriptor.Properties.ToImmutableDictionary(), cancellationToken);
@ -964,19 +826,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync( public virtual async ValueTask PopulateAsync(
OpenIddictAuthorizationDescriptor descriptor, OpenIddictAuthorizationDescriptor descriptor!!,
TAuthorization authorization, CancellationToken cancellationToken = default) TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
descriptor.ApplicationId = await Store.GetApplicationIdAsync(authorization, cancellationToken); descriptor.ApplicationId = await Store.GetApplicationIdAsync(authorization, cancellationToken);
descriptor.CreationDate = await Store.GetCreationDateAsync(authorization, cancellationToken); descriptor.CreationDate = await Store.GetCreationDateAsync(authorization, cancellationToken);
descriptor.Scopes.Clear(); descriptor.Scopes.Clear();
@ -1014,13 +866,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="authorization">The authorization to revoke.</param> /// <param name="authorization">The authorization to revoke.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the authorization was successfully revoked, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the authorization was successfully revoked, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> TryRevokeAsync(TAuthorization authorization, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> TryRevokeAsync(TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var status = await Store.GetStatusAsync(authorization, cancellationToken); var status = await Store.GetStatusAsync(authorization, cancellationToken);
if (string.Equals(status, Statuses.Revoked, StringComparison.OrdinalIgnoreCase)) if (string.Equals(status, Statuses.Revoked, StringComparison.OrdinalIgnoreCase))
{ {
@ -1061,13 +908,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TAuthorization authorization, CancellationToken cancellationToken = default) public virtual async ValueTask UpdateAsync(TAuthorization authorization!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var results = await GetValidationResultsAsync(authorization, cancellationToken); var results = await GetValidationResultsAsync(authorization, cancellationToken);
if (results.Any(result => result != ValidationResult.Success)) if (results.Any(result => result != ValidationResult.Success))
{ {
@ -1114,19 +956,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TAuthorization authorization, public virtual async ValueTask UpdateAsync(TAuthorization authorization!!,
OpenIddictAuthorizationDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictAuthorizationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await PopulateAsync(authorization, descriptor, cancellationToken); await PopulateAsync(authorization, descriptor, cancellationToken);
await UpdateAsync(authorization, cancellationToken); await UpdateAsync(authorization, cancellationToken);
} }
@ -1138,13 +970,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The validation error encountered when validating the authorization.</returns> /// <returns>The validation error encountered when validating the authorization.</returns>
public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync( public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync(
TAuthorization authorization, [EnumeratorCancellation] CancellationToken cancellationToken = default) TAuthorization authorization!!, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var type = await Store.GetTypeAsync(authorization, cancellationToken); var type = await Store.GetTypeAsync(authorization, cancellationToken);
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {

271
src/OpenIddict.Core/Managers/OpenIddictScopeManager.cs

@ -27,10 +27,10 @@ namespace OpenIddict.Core;
public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TScope : class public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TScope : class
{ {
public OpenIddictScopeManager( public OpenIddictScopeManager(
IOpenIddictScopeCache<TScope> cache, IOpenIddictScopeCache<TScope> cache!!,
ILogger<OpenIddictScopeManager<TScope>> logger, ILogger<OpenIddictScopeManager<TScope>> logger!!,
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictScopeStoreResolver resolver) IOpenIddictScopeStoreResolver resolver!!)
{ {
Cache = cache; Cache = cache;
Logger = logger; Logger = logger;
@ -80,15 +80,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns the number of scopes that match the specified query. /// whose result returns the number of scopes that match the specified query.
/// </returns> /// </returns>
public virtual ValueTask<long> CountAsync<TResult>( public virtual ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => Store.CountAsync(query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.CountAsync(query, cancellationToken);
}
/// <summary> /// <summary>
/// Creates a new scope. /// Creates a new scope.
@ -98,13 +91,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask CreateAsync(TScope scope, CancellationToken cancellationToken = default) public virtual async ValueTask CreateAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var results = await GetValidationResultsAsync(scope, cancellationToken); var results = await GetValidationResultsAsync(scope, cancellationToken);
if (results.Any(result => result != ValidationResult.Success)) if (results.Any(result => result != ValidationResult.Success))
{ {
@ -150,13 +138,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the scope. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the scope.
/// </returns> /// </returns>
public virtual async ValueTask<TScope> CreateAsync( public virtual async ValueTask<TScope> CreateAsync(
OpenIddictScopeDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictScopeDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var scope = await Store.InstantiateAsync(cancellationToken); var scope = await Store.InstantiateAsync(cancellationToken);
if (scope is null) if (scope is null)
{ {
@ -177,13 +160,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask DeleteAsync(TScope scope, CancellationToken cancellationToken = default) public virtual async ValueTask DeleteAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (!Options.CurrentValue.DisableEntityCaching) if (!Options.CurrentValue.DisableEntityCaching)
{ {
await Cache.RemoveAsync(scope, cancellationToken); await Cache.RemoveAsync(scope, cancellationToken);
@ -276,7 +254,7 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
public virtual IAsyncEnumerable<TScope> FindByNamesAsync( public virtual IAsyncEnumerable<TScope> FindByNamesAsync(
ImmutableArray<string> names, CancellationToken cancellationToken = default) ImmutableArray<string> names, CancellationToken cancellationToken = default)
{ {
if (names.Any(name => string.IsNullOrEmpty(name))) if (names.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
@ -361,15 +339,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TResult>( public virtual ValueTask<TResult?> GetAsync<TResult>(
Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => GetAsync(static (scopes, query) => query(scopes), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return GetAsync(static (scopes, query) => query(scopes), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -384,16 +355,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TState, TResult>( public virtual ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.GetAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.GetAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the description associated with a scope. /// Retrieves the description associated with a scope.
@ -404,15 +368,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the description associated with the specified scope. /// whose result returns the description associated with the specified scope.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetDescriptionAsync(TScope scope, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetDescriptionAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetDescriptionAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetDescriptionAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the localized descriptions associated with an scope. /// Retrieves the localized descriptions associated with an scope.
@ -424,21 +381,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns all the localized descriptions associated with the scope. /// whose result returns all the localized descriptions associated with the scope.
/// </returns> /// </returns>
public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync( public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(
TScope scope, CancellationToken cancellationToken = default) TScope scope!!, CancellationToken cancellationToken = default)
{ => await Store.GetDescriptionsAsync(scope, cancellationToken) is { Count: > 0 } descriptions ?
if (scope is null) descriptions : ImmutableDictionary.Create<CultureInfo, string>();
{
throw new ArgumentNullException(nameof(scope));
}
var descriptions = await Store.GetDescriptionsAsync(scope, cancellationToken);
if (descriptions is null || descriptions.Count == 0)
{
return ImmutableDictionary.Create<CultureInfo, string>();
}
return descriptions;
}
/// <summary> /// <summary>
/// Retrieves the display name associated with a scope. /// Retrieves the display name associated with a scope.
@ -449,15 +394,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the display name associated with the scope. /// whose result returns the display name associated with the scope.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetDisplayNameAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetDisplayNameAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the localized display names associated with an scope. /// Retrieves the localized display names associated with an scope.
@ -469,21 +407,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns all the localized display names associated with the scope. /// whose result returns all the localized display names associated with the scope.
/// </returns> /// </returns>
public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync( public virtual async ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(
TScope scope, CancellationToken cancellationToken = default) TScope scope!!, CancellationToken cancellationToken = default)
{ => await Store.GetDisplayNamesAsync(scope, cancellationToken) is { Count: > 0 } names ?
if (scope is null) names : ImmutableDictionary.Create<CultureInfo, string>();
{
throw new ArgumentNullException(nameof(scope));
}
var names = await Store.GetDisplayNamesAsync(scope, cancellationToken);
if (names is null || names.Count == 0)
{
return ImmutableDictionary.Create<CultureInfo, string>();
}
return names;
}
/// <summary> /// <summary>
/// Retrieves the unique identifier associated with a scope. /// Retrieves the unique identifier associated with a scope.
@ -494,15 +420,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the scope. /// whose result returns the unique identifier associated with the scope.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetIdAsync(TScope scope, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetIdAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetIdAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetIdAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the localized display name associated with an scope /// Retrieves the localized display name associated with an scope
@ -531,20 +450,10 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns the matching display name associated with the scope. /// whose result returns the matching display name associated with the scope.
/// </returns> /// </returns>
public virtual async ValueTask<string?> GetLocalizedDisplayNameAsync( public virtual async ValueTask<string?> GetLocalizedDisplayNameAsync(
TScope scope, CultureInfo culture, CancellationToken cancellationToken = default) TScope scope!!, CultureInfo culture!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (culture is null)
{
throw new ArgumentNullException(nameof(culture));
}
var names = await Store.GetDisplayNamesAsync(scope, cancellationToken); var names = await Store.GetDisplayNamesAsync(scope, cancellationToken);
if (names is null || names.IsEmpty) if (names is not { IsEmpty: false })
{ {
return await Store.GetDisplayNameAsync(scope, cancellationToken); return await Store.GetDisplayNameAsync(scope, cancellationToken);
} }
@ -591,20 +500,10 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns the matching localized description associated with the scope. /// whose result returns the matching localized description associated with the scope.
/// </returns> /// </returns>
public virtual async ValueTask<string?> GetLocalizedDescriptionAsync( public virtual async ValueTask<string?> GetLocalizedDescriptionAsync(
TScope scope, CultureInfo culture, CancellationToken cancellationToken = default) TScope scope!!, CultureInfo culture!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (culture is null)
{
throw new ArgumentNullException(nameof(culture));
}
var descriptions = await Store.GetDescriptionsAsync(scope, cancellationToken); var descriptions = await Store.GetDescriptionsAsync(scope, cancellationToken);
if (descriptions is null || descriptions.IsEmpty) if (descriptions is not { IsEmpty: false })
{ {
return await Store.GetDescriptionAsync(scope, cancellationToken); return await Store.GetDescriptionAsync(scope, cancellationToken);
} }
@ -633,15 +532,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the name associated with the specified scope. /// whose result returns the name associated with the specified scope.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetNameAsync(TScope scope, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetNameAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetNameAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetNameAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the additional properties associated with a scope. /// Retrieves the additional properties associated with a scope.
@ -653,15 +545,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns all the additional properties associated with the scope. /// whose result returns all the additional properties associated with the scope.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync( public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(
TScope scope, CancellationToken cancellationToken = default) TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetPropertiesAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetPropertiesAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the resources associated with a scope. /// Retrieves the resources associated with a scope.
@ -673,15 +558,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// whose result returns all the resources associated with the scope. /// whose result returns all the resources associated with the scope.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync( public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(
TScope scope, CancellationToken cancellationToken = default) TScope scope!!, CancellationToken cancellationToken = default)
{ => Store.GetResourcesAsync(scope, cancellationToken);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return Store.GetResourcesAsync(scope, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns all the corresponding elements. /// Executes the specified query and returns all the corresponding elements.
@ -702,15 +580,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TResult>(
Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => ListAsync(static (scopes, query) => query(scopes), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ListAsync(static (scopes, query) => query(scopes), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns all the corresponding elements. /// Executes the specified query and returns all the corresponding elements.
@ -722,16 +593,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.ListAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.ListAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Lists all the resources associated with the specified scopes. /// Lists all the resources associated with the specified scopes.
@ -764,19 +628,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync(TScope scope, public virtual async ValueTask PopulateAsync(TScope scope!!,
OpenIddictScopeDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictScopeDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await Store.SetDescriptionAsync(scope, descriptor.Description, cancellationToken); await Store.SetDescriptionAsync(scope, descriptor.Description, cancellationToken);
await Store.SetDescriptionsAsync(scope, descriptor.Descriptions.ToImmutableDictionary(), cancellationToken); await Store.SetDescriptionsAsync(scope, descriptor.Descriptions.ToImmutableDictionary(), cancellationToken);
await Store.SetDisplayNameAsync(scope, descriptor.DisplayName, cancellationToken); await Store.SetDisplayNameAsync(scope, descriptor.DisplayName, cancellationToken);
@ -796,19 +650,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync( public virtual async ValueTask PopulateAsync(
OpenIddictScopeDescriptor descriptor, OpenIddictScopeDescriptor descriptor!!,
TScope scope, CancellationToken cancellationToken = default) TScope scope!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
descriptor.Description = await Store.GetDescriptionAsync(scope, cancellationToken); descriptor.Description = await Store.GetDescriptionAsync(scope, cancellationToken);
descriptor.DisplayName = await Store.GetDisplayNameAsync(scope, cancellationToken); descriptor.DisplayName = await Store.GetDisplayNameAsync(scope, cancellationToken);
descriptor.Name = await Store.GetNameAsync(scope, cancellationToken); descriptor.Name = await Store.GetNameAsync(scope, cancellationToken);
@ -842,13 +686,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TScope scope, CancellationToken cancellationToken = default) public virtual async ValueTask UpdateAsync(TScope scope!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var results = await GetValidationResultsAsync(scope, cancellationToken); var results = await GetValidationResultsAsync(scope, cancellationToken);
if (results.Any(result => result != ValidationResult.Success)) if (results.Any(result => result != ValidationResult.Success))
{ {
@ -895,19 +734,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TScope scope, public virtual async ValueTask UpdateAsync(TScope scope!!,
OpenIddictScopeDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictScopeDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await PopulateAsync(scope, descriptor, cancellationToken); await PopulateAsync(scope, descriptor, cancellationToken);
await UpdateAsync(scope, cancellationToken); await UpdateAsync(scope, cancellationToken);
} }
@ -919,12 +748,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The validation error encountered when validating the scope.</returns> /// <returns>The validation error encountered when validating the scope.</returns>
public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync( public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync(
TScope scope, [EnumeratorCancellation] CancellationToken cancellationToken = default) TScope scope!!, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
// Ensure the name is not null or empty, does not contain a // Ensure the name is not null or empty, does not contain a
// space and is not already used for a different scope entity. // space and is not already used for a different scope entity.

316
src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs

@ -28,10 +28,10 @@ namespace OpenIddict.Core;
public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TToken : class public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TToken : class
{ {
public OpenIddictTokenManager( public OpenIddictTokenManager(
IOpenIddictTokenCache<TToken> cache, IOpenIddictTokenCache<TToken> cache!!,
ILogger<OpenIddictTokenManager<TToken>> logger, ILogger<OpenIddictTokenManager<TToken>> logger!!,
IOptionsMonitor<OpenIddictCoreOptions> options, IOptionsMonitor<OpenIddictCoreOptions> options!!,
IOpenIddictTokenStoreResolver resolver) IOpenIddictTokenStoreResolver resolver!!)
{ {
Cache = cache; Cache = cache;
Logger = logger; Logger = logger;
@ -81,15 +81,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// whose result returns the number of tokens that match the specified query. /// whose result returns the number of tokens that match the specified query.
/// </returns> /// </returns>
public virtual ValueTask<long> CountAsync<TResult>( public virtual ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => Store.CountAsync(query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.CountAsync(query, cancellationToken);
}
/// <summary> /// <summary>
/// Creates a new token. /// Creates a new token.
@ -99,13 +92,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask CreateAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If no status was explicitly specified, assume that the token is valid. // If no status was explicitly specified, assume that the token is valid.
if (string.IsNullOrEmpty(await Store.GetStatusAsync(token, cancellationToken))) if (string.IsNullOrEmpty(await Store.GetStatusAsync(token, cancellationToken)))
{ {
@ -165,13 +153,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the token. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation, whose result returns the token.
/// </returns> /// </returns>
public virtual async ValueTask<TToken> CreateAsync( public virtual async ValueTask<TToken> CreateAsync(
OpenIddictTokenDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictTokenDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
var token = await Store.InstantiateAsync(cancellationToken); var token = await Store.InstantiateAsync(cancellationToken);
if (token is null) if (token is null)
{ {
@ -192,13 +175,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask DeleteAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!Options.CurrentValue.DisableEntityCaching) if (!Options.CurrentValue.DisableEntityCaching)
{ {
await Cache.RemoveAsync(token, cancellationToken); await Cache.RemoveAsync(token, cancellationToken);
@ -579,15 +557,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the application identifier associated with the token. /// whose result returns the application identifier associated with the token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetApplicationIdAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetApplicationIdAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetApplicationIdAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -600,15 +571,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TResult>( public virtual ValueTask<TResult?> GetAsync<TResult>(
Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => GetAsync(static (tokens, query) => query(tokens), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return GetAsync(static (tokens, query) => query(tokens), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns the first element. /// Executes the specified query and returns the first element.
@ -623,16 +587,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// whose result returns the first element returned when executing the query. /// whose result returns the first element returned when executing the query.
/// </returns> /// </returns>
public virtual ValueTask<TResult?> GetAsync<TState, TResult>( public virtual ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.GetAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.GetAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the optional authorization identifier associated with a token. /// Retrieves the optional authorization identifier associated with a token.
@ -643,15 +600,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the authorization identifier associated with the token. /// whose result returns the authorization identifier associated with the token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetAuthorizationIdAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetAuthorizationIdAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetAuthorizationIdAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the creation date associated with a token. /// Retrieves the creation date associated with a token.
@ -662,15 +612,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the creation date associated with the specified token. /// whose result returns the creation date associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetCreationDateAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetCreationDateAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the expiration date associated with a token. /// Retrieves the expiration date associated with a token.
@ -681,15 +624,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the expiration date associated with the specified token. /// whose result returns the expiration date associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetExpirationDateAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetExpirationDateAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the unique identifier associated with a token. /// Retrieves the unique identifier associated with a token.
@ -700,15 +636,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the token. /// whose result returns the unique identifier associated with the token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetIdAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetIdAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetIdAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetIdAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the payload associated with a token. /// Retrieves the payload associated with a token.
@ -719,15 +648,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the payload associated with the specified token. /// whose result returns the payload associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetPayloadAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetPayloadAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetPayloadAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetPayloadAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the additional properties associated with a token. /// Retrieves the additional properties associated with a token.
@ -739,15 +661,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// whose result returns all the additional properties associated with the token. /// whose result returns all the additional properties associated with the token.
/// </returns> /// </returns>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync( public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(
TToken token, CancellationToken cancellationToken = default) TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetPropertiesAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetPropertiesAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the redemption date associated with a token. /// Retrieves the redemption date associated with a token.
@ -758,15 +673,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the redemption date associated with the specified token. /// whose result returns the redemption date associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetRedemptionDateAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetRedemptionDateAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the reference identifier associated with a token. /// Retrieves the reference identifier associated with a token.
@ -779,15 +687,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the reference identifier associated with the specified token. /// whose result returns the reference identifier associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetReferenceIdAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetReferenceIdAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetReferenceIdAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the status associated with a token. /// Retrieves the status associated with a token.
@ -798,15 +699,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the status associated with the specified token. /// whose result returns the status associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetStatusAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetStatusAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetStatusAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetStatusAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the subject associated with a token. /// Retrieves the subject associated with a token.
@ -817,15 +711,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the subject associated with the specified token. /// whose result returns the subject associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetSubjectAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetSubjectAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetSubjectAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetSubjectAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Retrieves the token type associated with a token. /// Retrieves the token type associated with a token.
@ -836,15 +723,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the token type associated with the specified token. /// whose result returns the token type associated with the specified token.
/// </returns> /// </returns>
public virtual ValueTask<string?> GetTypeAsync(TToken token, CancellationToken cancellationToken = default) public virtual ValueTask<string?> GetTypeAsync(TToken token!!, CancellationToken cancellationToken = default)
{ => Store.GetTypeAsync(token, cancellationToken);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return Store.GetTypeAsync(token, cancellationToken);
}
/// <summary> /// <summary>
/// Determines whether a given token has the specified status. /// Determines whether a given token has the specified status.
@ -853,13 +733,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="status">The expected status.</param> /// <param name="status">The expected status.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token has the specified status, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token has the specified status, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasStatusAsync(TToken token, string status, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> HasStatusAsync(TToken token!!, string status, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(status)) if (string.IsNullOrEmpty(status))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status)); throw new ArgumentException(SR.GetResourceString(SR.ID0199), nameof(status));
@ -875,13 +750,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="type">The expected type.</param> /// <param name="type">The expected type.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token has the specified type, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token has the specified type, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasTypeAsync(TToken token, string type, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> HasTypeAsync(TToken token!!, string type, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0200), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0200), nameof(type));
@ -897,13 +767,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="types">The expected types.</param> /// <param name="types">The expected types.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token has any of the specified types, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token has any of the specified types, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> HasTypeAsync(TToken token, ImmutableArray<string> types, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> HasTypeAsync(TToken token!!, ImmutableArray<string> types, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var type = await Store.GetTypeAsync(token, cancellationToken); var type = await Store.GetTypeAsync(token, cancellationToken);
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
@ -940,15 +805,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TResult>(
Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken = default) Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken = default)
{ => ListAsync(static (tokens, query) => query(tokens), query, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ListAsync(static (tokens, query) => query(tokens), query, cancellationToken);
}
/// <summary> /// <summary>
/// Executes the specified query and returns all the corresponding elements. /// Executes the specified query and returns all the corresponding elements.
@ -960,16 +818,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>All the elements returned when executing the specified query.</returns> /// <returns>All the elements returned when executing the specified query.</returns>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken = default) TState state, CancellationToken cancellationToken = default)
{ => Store.ListAsync(query, state, cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return Store.ListAsync(query, state, cancellationToken);
}
/// <summary> /// <summary>
/// Populates the token using the specified descriptor. /// Populates the token using the specified descriptor.
@ -980,19 +831,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync(TToken token, public virtual async ValueTask PopulateAsync(TToken token!!,
OpenIddictTokenDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictTokenDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
await Store.SetApplicationIdAsync(token, descriptor.ApplicationId, cancellationToken); await Store.SetApplicationIdAsync(token, descriptor.ApplicationId, cancellationToken);
await Store.SetAuthorizationIdAsync(token, descriptor.AuthorizationId, cancellationToken); await Store.SetAuthorizationIdAsync(token, descriptor.AuthorizationId, cancellationToken);
await Store.SetCreationDateAsync(token, descriptor.CreationDate, cancellationToken); await Store.SetCreationDateAsync(token, descriptor.CreationDate, cancellationToken);
@ -1016,19 +857,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask PopulateAsync( public virtual async ValueTask PopulateAsync(
OpenIddictTokenDescriptor descriptor, OpenIddictTokenDescriptor descriptor!!,
TToken token, CancellationToken cancellationToken = default) TToken token!!, CancellationToken cancellationToken = default)
{ {
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
descriptor.ApplicationId = await Store.GetApplicationIdAsync(token, cancellationToken); descriptor.ApplicationId = await Store.GetApplicationIdAsync(token, cancellationToken);
descriptor.AuthorizationId = await Store.GetAuthorizationIdAsync(token, cancellationToken); descriptor.AuthorizationId = await Store.GetAuthorizationIdAsync(token, cancellationToken);
descriptor.CreationDate = await Store.GetCreationDateAsync(token, cancellationToken); descriptor.CreationDate = await Store.GetCreationDateAsync(token, cancellationToken);
@ -1058,19 +889,15 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// </returns> /// </returns>
public virtual ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken = default) public virtual ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken = default)
=> Store.PruneAsync(threshold, cancellationToken); => Store.PruneAsync(threshold, cancellationToken);
/// <summary> /// <summary>
/// Tries to redeem a token. /// Tries to redeem a token.
/// </summary> /// </summary>
/// <param name="token">The token to redeem.</param> /// <param name="token">The token to redeem.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token was successfully redemeed, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token was successfully redemeed, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> TryRedeemAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> TryRedeemAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the token doesn't have a redemption date attached, this likely means it's // If the token doesn't have a redemption date attached, this likely means it's
// the first time the token is redeemed. In this case, attach the current date. // the first time the token is redeemed. In this case, attach the current date.
if (await Store.GetRedemptionDateAsync(token, cancellationToken) is null) if (await Store.GetRedemptionDateAsync(token, cancellationToken) is null)
@ -1110,13 +937,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="token">The token to reject.</param> /// <param name="token">The token to reject.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token was successfully redemeed, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token was successfully redemeed, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> TryRejectAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> TryRejectAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
await Store.SetStatusAsync(token, Statuses.Rejected, cancellationToken); await Store.SetStatusAsync(token, Statuses.Rejected, cancellationToken);
try try
@ -1149,13 +971,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="token">The token to revoke.</param> /// <param name="token">The token to revoke.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns><c>true</c> if the token was successfully revoked, <c>false</c> otherwise.</returns> /// <returns><c>true</c> if the token was successfully revoked, <c>false</c> otherwise.</returns>
public virtual async ValueTask<bool> TryRevokeAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask<bool> TryRevokeAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
await Store.SetStatusAsync(token, Statuses.Revoked, cancellationToken); await Store.SetStatusAsync(token, Statuses.Revoked, cancellationToken);
try try
@ -1190,13 +1007,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cancellationToken = default) public virtual async ValueTask UpdateAsync(TToken token!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var results = await GetValidationResultsAsync(token, cancellationToken); var results = await GetValidationResultsAsync(token, cancellationToken);
if (results.Any(result => result != ValidationResult.Success)) if (results.Any(result => result != ValidationResult.Success))
{ {
@ -1243,18 +1055,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <returns> /// <returns>
/// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation. /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
/// </returns> /// </returns>
public virtual async ValueTask UpdateAsync(TToken token, public virtual async ValueTask UpdateAsync(TToken token!!,
OpenIddictTokenDescriptor descriptor, CancellationToken cancellationToken = default) OpenIddictTokenDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (descriptor is null)
{
throw new ArgumentNullException(nameof(descriptor));
}
// Store the original reference identifier for later comparison. // Store the original reference identifier for later comparison.
var comparand = await Store.GetReferenceIdAsync(token, cancellationToken); var comparand = await Store.GetReferenceIdAsync(token, cancellationToken);
@ -1278,13 +1081,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The validation error encountered when validating the token.</returns> /// <returns>The validation error encountered when validating the token.</returns>
public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync( public virtual async IAsyncEnumerable<ValidationResult> ValidateAsync(
TToken token, [EnumeratorCancellation] CancellationToken cancellationToken = default) TToken token!!, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If a reference identifier was associated with the token, // If a reference identifier was associated with the token,
// ensure it's not already used for a different token. // ensure it's not already used for a different token.
var identifier = await Store.GetReferenceIdAsync(token, cancellationToken); var identifier = await Store.GetReferenceIdAsync(token, cancellationToken);
@ -1334,7 +1132,7 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
// Compute the digest of the generated identifier and use it as the hashed identifier of the reference token. // Compute the digest of the generated identifier and use it as the hashed identifier of the reference token.
// Doing that prevents token identifiers stolen from the database from being used as valid reference tokens. // Doing that prevents token identifiers stolen from the database from being used as valid reference tokens.
using var algorithm = SHA256.Create(); using var algorithm = SHA256.Create();
return new ValueTask<string>(Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(identifier)))); return new(Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(identifier))));
} }
/// <inheritdoc/> /// <inheritdoc/>

123
src/OpenIddict.Core/OpenIddictCoreBuilder.cs

@ -20,8 +20,8 @@ public class OpenIddictCoreBuilder
/// Initializes a new instance of <see cref="OpenIddictCoreBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictCoreBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictCoreBuilder(IServiceCollection services) public OpenIddictCoreBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -35,13 +35,8 @@ public class OpenIddictCoreBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder Configure(Action<OpenIddictCoreOptions> configuration) public OpenIddictCoreBuilder Configure(Action<OpenIddictCoreOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;
@ -69,13 +64,8 @@ public class OpenIddictCoreBuilder
/// <param name="type">The type of the custom store.</param> /// <param name="type">The type of the custom store.</param>
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder AddApplicationStore(Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) public OpenIddictCoreBuilder AddApplicationStore(Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictApplicationStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictApplicationStore<>));
if (root is null) if (root is null)
{ {
@ -125,13 +115,8 @@ public class OpenIddictCoreBuilder
/// <param name="type">The type of the custom store.</param> /// <param name="type">The type of the custom store.</param>
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder AddAuthorizationStore(Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) public OpenIddictCoreBuilder AddAuthorizationStore(Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictAuthorizationStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictAuthorizationStore<>));
if (root is null) if (root is null)
{ {
@ -181,13 +166,8 @@ public class OpenIddictCoreBuilder
/// <param name="type">The type of the custom store.</param> /// <param name="type">The type of the custom store.</param>
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder AddScopeStore(Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) public OpenIddictCoreBuilder AddScopeStore(Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictScopeStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictScopeStore<>));
if (root is null) if (root is null)
{ {
@ -237,13 +217,8 @@ public class OpenIddictCoreBuilder
/// <param name="type">The type of the custom store.</param> /// <param name="type">The type of the custom store.</param>
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder AddTokenStore(Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) public OpenIddictCoreBuilder AddTokenStore(Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictTokenStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictTokenStore<>));
if (root is null) if (root is null)
{ {
@ -291,13 +266,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the custom manager.</param> /// <param name="type">The type of the custom manager.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceApplicationManager(Type type) public OpenIddictCoreBuilder ReplaceApplicationManager(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictApplicationManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictApplicationManager<>));
if (root is null) if (root is null)
{ {
@ -348,13 +318,8 @@ public class OpenIddictCoreBuilder
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceApplicationStoreResolver( public OpenIddictCoreBuilder ReplaceApplicationStoreResolver(
Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(IOpenIddictApplicationStoreResolver).IsAssignableFrom(type)) if (!typeof(IOpenIddictApplicationStoreResolver).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -385,13 +350,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the custom manager.</param> /// <param name="type">The type of the custom manager.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceAuthorizationManager(Type type) public OpenIddictCoreBuilder ReplaceAuthorizationManager(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictAuthorizationManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictAuthorizationManager<>));
if (root is null) if (root is null)
{ {
@ -442,13 +402,8 @@ public class OpenIddictCoreBuilder
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceAuthorizationStoreResolver( public OpenIddictCoreBuilder ReplaceAuthorizationStoreResolver(
Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(IOpenIddictAuthorizationStoreResolver).IsAssignableFrom(type)) if (!typeof(IOpenIddictAuthorizationStoreResolver).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -479,13 +434,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the custom manager.</param> /// <param name="type">The type of the custom manager.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceScopeManager(Type type) public OpenIddictCoreBuilder ReplaceScopeManager(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictScopeManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictScopeManager<>));
if (root is null) if (root is null)
{ {
@ -536,13 +486,8 @@ public class OpenIddictCoreBuilder
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceScopeStoreResolver( public OpenIddictCoreBuilder ReplaceScopeStoreResolver(
Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(IOpenIddictScopeStoreResolver).IsAssignableFrom(type)) if (!typeof(IOpenIddictScopeStoreResolver).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -573,13 +518,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the custom manager.</param> /// <param name="type">The type of the custom manager.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceTokenManager(Type type) public OpenIddictCoreBuilder ReplaceTokenManager(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictTokenManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictTokenManager<>));
if (root is null) if (root is null)
{ {
@ -630,13 +570,8 @@ public class OpenIddictCoreBuilder
/// <param name="lifetime">The lifetime of the registered service.</param> /// <param name="lifetime">The lifetime of the registered service.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceTokenStoreResolver( public OpenIddictCoreBuilder ReplaceTokenStoreResolver(
Type type, ServiceLifetime lifetime = ServiceLifetime.Scoped) Type type!!, ServiceLifetime lifetime = ServiceLifetime.Scoped)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(IOpenIddictTokenStoreResolver).IsAssignableFrom(type)) if (!typeof(IOpenIddictTokenStoreResolver).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -679,13 +614,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The application entity type.</param> /// <param name="type">The application entity type.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder SetDefaultApplicationEntity(Type type) public OpenIddictCoreBuilder SetDefaultApplicationEntity(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsValueType) if (type.IsValueType)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -706,13 +636,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The authorization entity type.</param> /// <param name="type">The authorization entity type.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder SetDefaultAuthorizationEntity(Type type) public OpenIddictCoreBuilder SetDefaultAuthorizationEntity(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsValueType) if (type.IsValueType)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -733,13 +658,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The scope entity type.</param> /// <param name="type">The scope entity type.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder SetDefaultScopeEntity(Type type) public OpenIddictCoreBuilder SetDefaultScopeEntity(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsValueType) if (type.IsValueType)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
@ -760,13 +680,8 @@ public class OpenIddictCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The token entity type.</param> /// <param name="type">The token entity type.</param>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder SetDefaultTokenEntity(Type type) public OpenIddictCoreBuilder SetDefaultTokenEntity(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsValueType) if (type.IsValueType)
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));

19
src/OpenIddict.Core/OpenIddictCoreExtensions.cs

@ -22,13 +22,8 @@ public static class OpenIddictCoreExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictBuilder"/>.</returns>
public static OpenIddictCoreBuilder AddCore(this OpenIddictBuilder builder) public static OpenIddictCoreBuilder AddCore(this OpenIddictBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddLogging(); builder.Services.AddLogging();
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
builder.Services.AddOptions(); builder.Services.AddOptions();
@ -106,18 +101,8 @@ public static class OpenIddictCoreExtensions
/// <param name="configuration">The configuration delegate used to configure the core services.</param> /// <param name="configuration">The configuration delegate used to configure the core services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictBuilder"/>.</returns>
public static OpenIddictBuilder AddCore(this OpenIddictBuilder builder, Action<OpenIddictCoreBuilder> configuration) public static OpenIddictBuilder AddCore(this OpenIddictBuilder builder!!, Action<OpenIddictCoreBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.AddCore()); configuration(builder.AddCore());
return builder; return builder;

2
src/OpenIddict.Core/Resolvers/OpenIddictApplicationStoreResolver.cs

@ -9,7 +9,7 @@ public class OpenIddictApplicationStoreResolver : IOpenIddictApplicationStoreRes
{ {
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictApplicationStoreResolver(IServiceProvider provider) public OpenIddictApplicationStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.Core/Resolvers/OpenIddictAuthorizationStoreResolver.cs

@ -9,7 +9,7 @@ public class OpenIddictAuthorizationStoreResolver : IOpenIddictAuthorizationStor
{ {
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictAuthorizationStoreResolver(IServiceProvider provider) public OpenIddictAuthorizationStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.Core/Resolvers/OpenIddictScopeStoreResolver.cs

@ -9,7 +9,7 @@ public class OpenIddictScopeStoreResolver : IOpenIddictScopeStoreResolver
{ {
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictScopeStoreResolver(IServiceProvider provider) public OpenIddictScopeStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.Core/Resolvers/OpenIddictTokenStoreResolver.cs

@ -9,7 +9,7 @@ public class OpenIddictTokenStoreResolver : IOpenIddictTokenStoreResolver
{ {
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictTokenStoreResolver(IServiceProvider provider) public OpenIddictTokenStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

18
src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkBuilder.cs

@ -21,8 +21,8 @@ public class OpenIddictEntityFrameworkBuilder
/// Initializes a new instance of <see cref="OpenIddictEntityFrameworkBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictEntityFrameworkBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictEntityFrameworkBuilder(IServiceCollection services) public OpenIddictEntityFrameworkBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -36,13 +36,8 @@ public class OpenIddictEntityFrameworkBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns>
public OpenIddictEntityFrameworkBuilder Configure(Action<OpenIddictEntityFrameworkOptions> configuration) public OpenIddictEntityFrameworkBuilder Configure(Action<OpenIddictEntityFrameworkOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;
@ -94,13 +89,8 @@ public class OpenIddictEntityFrameworkBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the <see cref="DbContext"/> used by OpenIddict.</param> /// <param name="type">The type of the <see cref="DbContext"/> used by OpenIddict.</param>
/// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns>
public OpenIddictEntityFrameworkBuilder UseDbContext(Type type) public OpenIddictEntityFrameworkBuilder UseDbContext(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(DbContext).IsAssignableFrom(type)) if (!typeof(DbContext).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));

19
src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkExtensions.cs

@ -22,13 +22,8 @@ public static class OpenIddictEntityFrameworkExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkBuilder"/>.</returns>
public static OpenIddictEntityFrameworkBuilder UseEntityFramework(this OpenIddictCoreBuilder builder) public static OpenIddictEntityFrameworkBuilder UseEntityFramework(this OpenIddictCoreBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Since Entity Framework 6.x may be used with databases performing case-insensitive // Since Entity Framework 6.x may be used with databases performing case-insensitive
// or culture-sensitive comparisons, ensure the additional filtering logic is enforced // or culture-sensitive comparisons, ensure the additional filtering logic is enforced
// in case case-sensitive stores were registered before this extension was called. // in case case-sensitive stores were registered before this extension was called.
@ -66,18 +61,8 @@ public static class OpenIddictEntityFrameworkExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public static OpenIddictCoreBuilder UseEntityFramework( public static OpenIddictCoreBuilder UseEntityFramework(
this OpenIddictCoreBuilder builder, Action<OpenIddictEntityFrameworkBuilder> configuration) this OpenIddictCoreBuilder builder!!, Action<OpenIddictEntityFrameworkBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseEntityFramework()); configuration(builder.UseEntityFramework());
return builder; return builder;

14
src/OpenIddict.EntityFramework/OpenIddictEntityFrameworkHelpers.cs

@ -38,18 +38,13 @@ public static class OpenIddictEntityFrameworkHelpers
/// </remarks> /// </remarks>
/// <param name="builder">The builder used to configure the Entity Framework context.</param> /// <param name="builder">The builder used to configure the Entity Framework context.</param>
/// <returns>The Entity Framework context builder.</returns> /// <returns>The Entity Framework context builder.</returns>
public static DbModelBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(this DbModelBuilder builder) public static DbModelBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(this DbModelBuilder builder!!)
where TApplication : OpenIddictEntityFrameworkApplication<TKey, TAuthorization, TToken> where TApplication : OpenIddictEntityFrameworkApplication<TKey, TAuthorization, TToken>
where TAuthorization : OpenIddictEntityFrameworkAuthorization<TKey, TApplication, TToken> where TAuthorization : OpenIddictEntityFrameworkAuthorization<TKey, TApplication, TToken>
where TScope : OpenIddictEntityFrameworkScope<TKey> where TScope : OpenIddictEntityFrameworkScope<TKey>
where TToken : OpenIddictEntityFrameworkToken<TKey, TApplication, TAuthorization> where TToken : OpenIddictEntityFrameworkToken<TKey, TApplication, TAuthorization>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Configurations builder.Configurations
.Add(new OpenIddictEntityFrameworkApplicationConfiguration<TApplication, TAuthorization, TToken, TKey>()) .Add(new OpenIddictEntityFrameworkApplicationConfiguration<TApplication, TAuthorization, TToken, TKey>())
.Add(new OpenIddictEntityFrameworkAuthorizationConfiguration<TAuthorization, TApplication, TToken, TKey>()) .Add(new OpenIddictEntityFrameworkAuthorizationConfiguration<TAuthorization, TApplication, TToken, TKey>())
@ -66,13 +61,8 @@ public static class OpenIddictEntityFrameworkHelpers
/// <param name="source">The query source.</param> /// <param name="source">The query source.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The non-streamed async enumeration containing the results.</returns> /// <returns>The non-streamed async enumeration containing the results.</returns>
internal static IAsyncEnumerable<T> AsAsyncEnumerable<T>(this IQueryable<T> source, CancellationToken cancellationToken) internal static IAsyncEnumerable<T> AsAsyncEnumerable<T>(this IQueryable<T> source!!, CancellationToken cancellationToken)
{ {
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return ExecuteAsync(source, cancellationToken); return ExecuteAsync(source, cancellationToken);
static async IAsyncEnumerable<T> ExecuteAsync(IQueryable<T> source, [EnumeratorCancellation] CancellationToken cancellationToken) static async IAsyncEnumerable<T> ExecuteAsync(IQueryable<T> source, [EnumeratorCancellation] CancellationToken cancellationToken)

6
src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkApplicationStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkApplicationStoreResolver : IOpenIddictAppl
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkApplicationStoreResolver( public OpenIddictEntityFrameworkApplicationStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkAuthorizationStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkAuthorizationStoreResolver : IOpenIddictAu
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkAuthorizationStoreResolver( public OpenIddictEntityFrameworkAuthorizationStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkScopeStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkScopeStoreResolver : IOpenIddictScopeStore
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkScopeStoreResolver( public OpenIddictEntityFrameworkScopeStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkTokenStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkTokenStoreResolver : IOpenIddictTokenStore
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkTokenStoreResolver( public OpenIddictEntityFrameworkTokenStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

273
src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkApplicationStore.cs

@ -32,7 +32,7 @@ public class OpenIddictEntityFrameworkApplicationStore<TContext> :
public OpenIddictEntityFrameworkApplicationStore( public OpenIddictEntityFrameworkApplicationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -54,9 +54,9 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkApplicationStore( public OpenIddictEntityFrameworkApplicationStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -98,37 +98,20 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
=> await Applications.LongCountAsync(cancellationToken); => await Applications.LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Applications).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Applications).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
Applications.Add(application); Applications.Add(application);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
DbContextTransaction? CreateTransaction() DbContextTransaction? CreateTransaction()
{ {
try try
@ -303,83 +286,36 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(Applications, state).FirstOrDefaultAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Applications, state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientId);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientSecretAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientSecretAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientSecret);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientSecret);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.Type);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ConsentType);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ConsentType);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.DisplayName);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.DisplayName);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.DisplayNames)) if (string.IsNullOrEmpty(application.DisplayNames))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified display names is an expensive operation. // Note: parsing the stringified display names is an expensive operation.
@ -407,31 +343,19 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(names); return new(names);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(application.Id));
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(ConvertIdentifierToString(application.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Permissions)) if (string.IsNullOrEmpty(application.Permissions))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified permissions is an expensive operation. // Note: parsing the stringified permissions is an expensive operation.
@ -459,20 +383,15 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(permissions); return new(permissions);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.PostLogoutRedirectUris)) if (string.IsNullOrEmpty(application.PostLogoutRedirectUris))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified addresses is an expensive operation. // Note: parsing the stringified addresses is an expensive operation.
@ -500,20 +419,15 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(addresses); return new(addresses);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Properties)) if (string.IsNullOrEmpty(application.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -535,20 +449,15 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.RedirectUris)) if (string.IsNullOrEmpty(application.RedirectUris))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified addresses is an expensive operation. // Note: parsing the stringified addresses is an expensive operation.
@ -576,20 +485,15 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(addresses); return new(addresses);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Requirements)) if (string.IsNullOrEmpty(application.Requirements))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified requirements is an expensive operation. // Note: parsing the stringified requirements is an expensive operation.
@ -617,7 +521,7 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(requirements); return new(requirements);
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -625,12 +529,12 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
{ {
try try
{ {
return new ValueTask<TApplication>(Activator.CreateInstance<TApplication>()); return new(Activator.CreateInstance<TApplication>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TApplication>(Task.FromException<TApplication>( return new(Task.FromException<TApplication>(
new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception)));
} }
} }
@ -656,91 +560,56 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(Applications, state).AsAsyncEnumerable(cancellationToken); return query(Applications, state).AsAsyncEnumerable(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientIdAsync(TApplication application, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetClientIdAsync(TApplication application!!, string? identifier, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientId = identifier; application.ClientId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientSecretAsync(TApplication application, string? secret, CancellationToken cancellationToken) public virtual ValueTask SetClientSecretAsync(TApplication application!!, string? secret, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientSecret = secret; application.ClientSecret = secret;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientTypeAsync(TApplication application, string? type, CancellationToken cancellationToken) public virtual ValueTask SetClientTypeAsync(TApplication application!!, string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.Type = type; application.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetConsentTypeAsync(TApplication application, string? type, CancellationToken cancellationToken) public virtual ValueTask SetConsentTypeAsync(TApplication application!!, string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ConsentType = type; application.ConsentType = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TApplication application, string? name, CancellationToken cancellationToken) public virtual ValueTask SetDisplayNameAsync(TApplication application!!, string? name, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.DisplayName = name; application.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TApplication application, public virtual ValueTask SetDisplayNamesAsync(TApplication application!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (names is null || names.IsEmpty) if (names is null || names.IsEmpty)
{ {
application.DisplayNames = null; application.DisplayNames = null;
@ -772,13 +641,8 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPermissionsAsync(TApplication application, ImmutableArray<string> permissions, CancellationToken cancellationToken) public virtual ValueTask SetPermissionsAsync(TApplication application!!, ImmutableArray<string> permissions, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (permissions.IsDefaultOrEmpty) if (permissions.IsDefaultOrEmpty)
{ {
application.Permissions = null; application.Permissions = null;
@ -809,14 +673,9 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application, public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.PostLogoutRedirectUris = null; application.PostLogoutRedirectUris = null;
@ -847,15 +706,10 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TApplication application, public virtual ValueTask SetPropertiesAsync(TApplication application!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (application is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(application));
}
if (properties is null || properties.IsEmpty)
{ {
application.Properties = null; application.Properties = null;
@ -886,14 +740,9 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedirectUrisAsync(TApplication application, public virtual ValueTask SetRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.RedirectUris = null; application.RedirectUris = null;
@ -924,13 +773,8 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRequirementsAsync(TApplication application, ImmutableArray<string> requirements, CancellationToken cancellationToken) public virtual ValueTask SetRequirementsAsync(TApplication application!!, ImmutableArray<string> requirements, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (requirements.IsDefaultOrEmpty) if (requirements.IsDefaultOrEmpty)
{ {
application.Requirements = null; application.Requirements = null;
@ -961,13 +805,8 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
Applications.Attach(application); Applications.Attach(application);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

206
src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkAuthorizationStore.cs

@ -31,7 +31,7 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TContext> :
public OpenIddictEntityFrameworkAuthorizationStore( public OpenIddictEntityFrameworkAuthorizationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -53,9 +53,9 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkAuthorizationStore( public OpenIddictEntityFrameworkAuthorizationStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -97,37 +97,20 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
=> await Authorizations.LongCountAsync(cancellationToken); => await Authorizations.LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Authorizations).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Authorizations).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
Authorizations.Add(authorization); Authorizations.Add(authorization);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
DbContextTransaction? CreateTransaction() DbContextTransaction? CreateTransaction()
{ {
try try
@ -361,13 +344,8 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
// If the application is not attached to the authorization, try to load it manually. // If the application is not attached to the authorization, try to load it manually.
if (authorization.Application is null) if (authorization.Application is null)
{ {
@ -390,56 +368,25 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(
Authorizations.Include(authorization => authorization.Application), state).FirstOrDefaultAsync(cancellationToken); Authorizations.Include(authorization => authorization.Application), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(authorization.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(authorization.Id));
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(ConvertIdentifierToString(authorization.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(authorization.Properties)) if (string.IsNullOrEmpty(authorization.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -461,20 +408,15 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(authorization.Scopes)) if (string.IsNullOrEmpty(authorization.Scopes))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified scopes is an expensive operation. // Note: parsing the stringified scopes is an expensive operation.
@ -502,53 +444,32 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(scopes); return new(scopes);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Status);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Subject);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Type);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TAuthorization>(Activator.CreateInstance<TAuthorization>()); return new(Activator.CreateInstance<TAuthorization>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TAuthorization>(Task.FromException<TAuthorization>( return new(Task.FromException<TAuthorization>(
new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception)));
} }
} }
@ -575,16 +496,9 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(Authorizations.Include(authorization => authorization.Application), state).AsAsyncEnumerable(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(Authorizations.Include(authorization => authorization.Application), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken)
@ -668,14 +582,9 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetApplicationIdAsync(TAuthorization authorization, public virtual async ValueTask SetApplicationIdAsync(TAuthorization authorization!!,
string? identifier, CancellationToken cancellationToken) string? identifier, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier));
@ -706,29 +615,19 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TAuthorization authorization, public virtual ValueTask SetCreationDateAsync(TAuthorization authorization!!,
DateTimeOffset? date, CancellationToken cancellationToken) DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.CreationDate = date?.UtcDateTime; authorization.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TAuthorization authorization, public virtual ValueTask SetPropertiesAsync(TAuthorization authorization!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (authorization is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(authorization));
}
if (properties is null || properties.IsEmpty)
{ {
authorization.Properties = null; authorization.Properties = null;
@ -759,14 +658,9 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetScopesAsync(TAuthorization authorization, public virtual ValueTask SetScopesAsync(TAuthorization authorization!!,
ImmutableArray<string> scopes, CancellationToken cancellationToken) ImmutableArray<string> scopes, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (scopes.IsDefaultOrEmpty) if (scopes.IsDefaultOrEmpty)
{ {
authorization.Scopes = null; authorization.Scopes = null;
@ -797,52 +691,32 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TAuthorization authorization, string? status, CancellationToken cancellationToken) public virtual ValueTask SetStatusAsync(TAuthorization authorization!!, string? status, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Status = status; authorization.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TAuthorization authorization, string? subject, CancellationToken cancellationToken) public virtual ValueTask SetSubjectAsync(TAuthorization authorization!!, string? subject, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Subject = subject; authorization.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TAuthorization authorization, string? type, CancellationToken cancellationToken) public virtual ValueTask SetTypeAsync(TAuthorization authorization!!, string? type, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Type = type; authorization.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
Authorizations.Attach(authorization); Authorizations.Attach(authorization);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

205
src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkScopeStore.cs

@ -29,7 +29,7 @@ public class OpenIddictEntityFrameworkScopeStore<TContext> :
public OpenIddictEntityFrameworkScopeStore( public OpenIddictEntityFrameworkScopeStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -47,9 +47,9 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkScopeStore( public OpenIddictEntityFrameworkScopeStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -81,37 +81,20 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
=> await Scopes.LongCountAsync(cancellationToken); => await Scopes.LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Scopes).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Scopes).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Scopes.Add(scope); Scopes.Add(scope);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Scopes.Remove(scope); Scopes.Remove(scope);
try try
@ -160,7 +143,7 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
public virtual IAsyncEnumerable<TScope> FindByNamesAsync( public virtual IAsyncEnumerable<TScope> FindByNamesAsync(
ImmutableArray<string> names, CancellationToken cancellationToken) ImmutableArray<string> names, CancellationToken cancellationToken)
{ {
if (names.Any(name => string.IsNullOrEmpty(name))) if (names.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
@ -208,39 +191,20 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(Scopes, state).FirstOrDefaultAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Scopes, state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDescriptionAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDescriptionAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Description);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Description);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Descriptions)) if (string.IsNullOrEmpty(scope.Descriptions))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified descriptions is an expensive operation. // Note: parsing the stringified descriptions is an expensive operation.
@ -268,31 +232,21 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(descriptions); return new(descriptions);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null) return new(scope.DisplayName);
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.DisplayName);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.DisplayNames)) if (string.IsNullOrEmpty(scope.DisplayNames))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified display names is an expensive operation. // Note: parsing the stringified display names is an expensive operation.
@ -320,42 +274,23 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(names); return new(names);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(scope.Id));
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(ConvertIdentifierToString(scope.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Name);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Name);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Properties)) if (string.IsNullOrEmpty(scope.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -377,20 +312,15 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Resources)) if (string.IsNullOrEmpty(scope.Resources))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified resources is an expensive operation. // Note: parsing the stringified resources is an expensive operation.
@ -418,7 +348,7 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(resources); return new(resources);
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -426,12 +356,12 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
{ {
try try
{ {
return new ValueTask<TScope>(Activator.CreateInstance<TScope>()); return new(Activator.CreateInstance<TScope>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TScope>(Task.FromException<TScope>( return new(Task.FromException<TScope>(
new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception)));
} }
} }
@ -456,39 +386,22 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(Scopes, state).AsAsyncEnumerable(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(Scopes, state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionAsync(TScope scope, string? description, CancellationToken cancellationToken) public virtual ValueTask SetDescriptionAsync(TScope scope!!, string? description, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Description = description; scope.Description = description;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionsAsync(TScope scope, public virtual ValueTask SetDescriptionsAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (descriptions is null || descriptions.IsEmpty) if (descriptions is null || descriptions.IsEmpty)
{ {
scope.Descriptions = null; scope.Descriptions = null;
@ -520,27 +433,17 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetDisplayNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.DisplayName = name; scope.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TScope scope, public virtual ValueTask SetDisplayNamesAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (names is null || names.IsEmpty) if (names is null || names.IsEmpty)
{ {
scope.DisplayNames = null; scope.DisplayNames = null;
@ -572,28 +475,18 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Name = name; scope.Name = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TScope scope, public virtual ValueTask SetPropertiesAsync(TScope scope!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (scope is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(scope));
}
if (properties is null || properties.IsEmpty)
{ {
scope.Properties = null; scope.Properties = null;
@ -624,13 +517,8 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetResourcesAsync(TScope scope, ImmutableArray<string> resources, CancellationToken cancellationToken) public virtual ValueTask SetResourcesAsync(TScope scope!!, ImmutableArray<string> resources, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (resources.IsDefaultOrEmpty) if (resources.IsDefaultOrEmpty)
{ {
scope.Resources = null; scope.Resources = null;
@ -661,13 +549,8 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Scopes.Attach(scope); Scopes.Attach(scope);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

284
src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs

@ -30,7 +30,7 @@ public class OpenIddictEntityFrameworkTokenStore<TContext> :
public OpenIddictEntityFrameworkTokenStore( public OpenIddictEntityFrameworkTokenStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -52,9 +52,9 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkTokenStore( public OpenIddictEntityFrameworkTokenStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -96,37 +96,20 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
=> await Tokens.LongCountAsync(cancellationToken); => await Tokens.LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Tokens).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Tokens).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Tokens.Add(token); Tokens.Add(token);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Tokens.Remove(token); Tokens.Remove(token);
try try
@ -301,13 +284,8 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetApplicationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the application is not attached to the token, try to load it manually. // If the application is not attached to the token, try to load it manually.
if (token.Application is null) if (token.Application is null)
{ {
@ -330,27 +308,15 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(
Tokens.Include(token => token.Application) Tokens.Include(token => token.Application)
.Include(token => token.Authorization), state).FirstOrDefaultAsync(cancellationToken); .Include(token => token.Authorization), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetAuthorizationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the authorization is not attached to the token, try to load it manually. // If the authorization is not attached to the token, try to load it manually.
if (token.Authorization is null) if (token.Authorization is null)
{ {
@ -372,70 +338,27 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ExpirationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.ExpirationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.ExpirationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(token.Id));
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(ConvertIdentifierToString(token.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetPayloadAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetPayloadAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Payload);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Payload);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(token.Properties)) if (string.IsNullOrEmpty(token.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -457,80 +380,40 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.RedemptionDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.RedemptionDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.RedemptionDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetReferenceIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ReferenceId);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.ReferenceId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Status);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Subject);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Type);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TToken>(Activator.CreateInstance<TToken>()); return new(Activator.CreateInstance<TToken>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TToken>(Task.FromException<TToken>( return new(Task.FromException<TToken>(
new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception)));
} }
} }
@ -558,18 +441,11 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(
Tokens.Include(token => token.Application) Tokens.Include(token => token.Application)
.Include(token => token.Authorization), state).AsAsyncEnumerable(cancellationToken); .Include(token => token.Authorization), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken)
@ -650,13 +526,8 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetApplicationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual async ValueTask SetApplicationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier));
@ -687,13 +558,8 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetAuthorizationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual async ValueTask SetAuthorizationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var authorization = await Authorizations.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); var authorization = await Authorizations.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier));
@ -724,54 +590,34 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetCreationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.CreationDate = date?.UtcDateTime; token.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetExpirationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetExpirationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ExpirationDate = date?.UtcDateTime; token.ExpirationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPayloadAsync(TToken token, string? payload, CancellationToken cancellationToken) public virtual ValueTask SetPayloadAsync(TToken token!!, string? payload, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Payload = payload; token.Payload = payload;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TToken token, public virtual ValueTask SetPropertiesAsync(TToken token!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (token is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(token));
}
if (properties is null || properties.IsEmpty)
{ {
token.Properties = null; token.Properties = null;
@ -802,78 +648,48 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedemptionDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetRedemptionDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.RedemptionDate = date?.UtcDateTime; token.RedemptionDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetReferenceIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetReferenceIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ReferenceId = identifier; token.ReferenceId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TToken token, string? status, CancellationToken cancellationToken) public virtual ValueTask SetStatusAsync(TToken token!!, string? status, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Status = status; token.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TToken token, string? subject, CancellationToken cancellationToken) public virtual ValueTask SetSubjectAsync(TToken token!!, string? subject, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Subject = subject; token.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TToken token, string? type, CancellationToken cancellationToken) public virtual ValueTask SetTypeAsync(TToken token!!, string? type, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Type = type; token.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Tokens.Attach(token); Tokens.Attach(token);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

7
src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreApplicationConfiguration.cs

@ -24,13 +24,8 @@ public class OpenIddictEntityFrameworkCoreApplicationConfiguration<TApplication,
where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization> where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public void Configure(EntityTypeBuilder<TApplication> builder) public void Configure(EntityTypeBuilder<TApplication> builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Warning: optional foreign keys MUST NOT be added as CLR properties because // Warning: optional foreign keys MUST NOT be added as CLR properties because
// Entity Framework would throw an exception due to the TKey generic parameter // Entity Framework would throw an exception due to the TKey generic parameter
// being non-nullable when using value types like short, int, long or Guid. // being non-nullable when using value types like short, int, long or Guid.

7
src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreAuthorizationConfiguration.cs

@ -24,13 +24,8 @@ public class OpenIddictEntityFrameworkCoreAuthorizationConfiguration<TAuthorizat
where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization> where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public void Configure(EntityTypeBuilder<TAuthorization> builder) public void Configure(EntityTypeBuilder<TAuthorization> builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Warning: optional foreign keys MUST NOT be added as CLR properties because // Warning: optional foreign keys MUST NOT be added as CLR properties because
// Entity Framework would throw an exception due to the TKey generic parameter // Entity Framework would throw an exception due to the TKey generic parameter
// being non-nullable when using value types like short, int, long or Guid. // being non-nullable when using value types like short, int, long or Guid.

7
src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreScopeConfiguration.cs

@ -20,13 +20,8 @@ public class OpenIddictEntityFrameworkCoreScopeConfiguration<TScope, TKey> : IEn
where TScope : OpenIddictEntityFrameworkCoreScope<TKey> where TScope : OpenIddictEntityFrameworkCoreScope<TKey>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public void Configure(EntityTypeBuilder<TScope> builder) public void Configure(EntityTypeBuilder<TScope> builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Warning: optional foreign keys MUST NOT be added as CLR properties because // Warning: optional foreign keys MUST NOT be added as CLR properties because
// Entity Framework would throw an exception due to the TKey generic parameter // Entity Framework would throw an exception due to the TKey generic parameter
// being non-nullable when using value types like short, int, long or Guid. // being non-nullable when using value types like short, int, long or Guid.

7
src/OpenIddict.EntityFrameworkCore/Configurations/OpenIddictEntityFrameworkCoreTokenConfiguration.cs

@ -24,13 +24,8 @@ public class OpenIddictEntityFrameworkCoreTokenConfiguration<TToken, TApplicatio
where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken> where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public void Configure(EntityTypeBuilder<TToken> builder) public void Configure(EntityTypeBuilder<TToken> builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Warning: optional foreign keys MUST NOT be added as CLR properties because // Warning: optional foreign keys MUST NOT be added as CLR properties because
// Entity Framework would throw an exception due to the TKey generic parameter // Entity Framework would throw an exception due to the TKey generic parameter
// being non-nullable when using value types like short, int, long or Guid. // being non-nullable when using value types like short, int, long or Guid.

18
src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreBuilder.cs

@ -20,8 +20,8 @@ public class OpenIddictEntityFrameworkCoreBuilder
/// Initializes a new instance of <see cref="OpenIddictEntityFrameworkCoreBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictEntityFrameworkCoreBuilder(IServiceCollection services) public OpenIddictEntityFrameworkCoreBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -35,13 +35,8 @@ public class OpenIddictEntityFrameworkCoreBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns>
public OpenIddictEntityFrameworkCoreBuilder Configure(Action<OpenIddictEntityFrameworkCoreOptions> configuration) public OpenIddictEntityFrameworkCoreBuilder Configure(Action<OpenIddictEntityFrameworkCoreOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;
@ -96,13 +91,8 @@ public class OpenIddictEntityFrameworkCoreBuilder
/// </summary> /// </summary>
/// <param name="type">The type of the <see cref="DbContext"/> used by OpenIddict.</param> /// <param name="type">The type of the <see cref="DbContext"/> used by OpenIddict.</param>
/// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns>
public OpenIddictEntityFrameworkCoreBuilder UseDbContext(Type type) public OpenIddictEntityFrameworkCoreBuilder UseDbContext(Type type!!)
{ {
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (!typeof(DbContext).IsAssignableFrom(type)) if (!typeof(DbContext).IsAssignableFrom(type))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));

12
src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreCustomizer.cs

@ -25,18 +25,8 @@ public class OpenIddictEntityFrameworkCoreCustomizer<TApplication, TAuthorizatio
} }
/// <inheritdoc/> /// <inheritdoc/>
public override void Customize(ModelBuilder modelBuilder, DbContext context) public override void Customize(ModelBuilder modelBuilder!!, DbContext context!!)
{ {
if (modelBuilder is null)
{
throw new ArgumentNullException(nameof(modelBuilder));
}
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// Register the OpenIddict entity sets. // Register the OpenIddict entity sets.
modelBuilder.UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(); modelBuilder.UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>();

19
src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreExtensions.cs

@ -22,13 +22,8 @@ public static class OpenIddictEntityFrameworkCoreExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictEntityFrameworkCoreBuilder"/>.</returns>
public static OpenIddictEntityFrameworkCoreBuilder UseEntityFrameworkCore(this OpenIddictCoreBuilder builder) public static OpenIddictEntityFrameworkCoreBuilder UseEntityFrameworkCore(this OpenIddictCoreBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Since Entity Framework Core may be used with databases performing case-insensitive // Since Entity Framework Core may be used with databases performing case-insensitive
// or culture-sensitive comparisons, ensure the additional filtering logic is enforced // or culture-sensitive comparisons, ensure the additional filtering logic is enforced
// in case case-sensitive stores were registered before this extension was called. // in case case-sensitive stores were registered before this extension was called.
@ -66,18 +61,8 @@ public static class OpenIddictEntityFrameworkCoreExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public static OpenIddictCoreBuilder UseEntityFrameworkCore( public static OpenIddictCoreBuilder UseEntityFrameworkCore(
this OpenIddictCoreBuilder builder, Action<OpenIddictEntityFrameworkCoreBuilder> configuration) this OpenIddictCoreBuilder builder!!, Action<OpenIddictEntityFrameworkCoreBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseEntityFrameworkCore()); configuration(builder.UseEntityFrameworkCore());
return builder; return builder;

29
src/OpenIddict.EntityFrameworkCore/OpenIddictEntityFrameworkCoreHelpers.cs

@ -56,21 +56,14 @@ public static class OpenIddictEntityFrameworkCoreHelpers
/// <param name="builder">The builder used to configure the Entity Framework context.</param> /// <param name="builder">The builder used to configure the Entity Framework context.</param>
/// <returns>The Entity Framework context builder.</returns> /// <returns>The Entity Framework context builder.</returns>
public static DbContextOptionsBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>( public static DbContextOptionsBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(
this DbContextOptionsBuilder builder) this DbContextOptionsBuilder builder!!)
where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken> where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken>
where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken> where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken>
where TScope : OpenIddictEntityFrameworkCoreScope<TKey> where TScope : OpenIddictEntityFrameworkCoreScope<TKey>
where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization> where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ => builder.ReplaceService<IModelCustomizer, OpenIddictEntityFrameworkCoreCustomizer<
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
return builder.ReplaceService<IModelCustomizer, OpenIddictEntityFrameworkCoreCustomizer<
TApplication, TAuthorization, TScope, TToken, TKey>>(); TApplication, TAuthorization, TScope, TToken, TKey>>();
}
/// <summary> /// <summary>
/// Registers the OpenIddict entity sets in the Entity Framework Core context /// Registers the OpenIddict entity sets in the Entity Framework Core context
@ -110,24 +103,17 @@ public static class OpenIddictEntityFrameworkCoreHelpers
/// </remarks> /// </remarks>
/// <param name="builder">The builder used to configure the Entity Framework context.</param> /// <param name="builder">The builder used to configure the Entity Framework context.</param>
/// <returns>The Entity Framework context builder.</returns> /// <returns>The Entity Framework context builder.</returns>
public static ModelBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(this ModelBuilder builder) public static ModelBuilder UseOpenIddict<TApplication, TAuthorization, TScope, TToken, TKey>(this ModelBuilder builder!!)
where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken> where TApplication : OpenIddictEntityFrameworkCoreApplication<TKey, TAuthorization, TToken>
where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken> where TAuthorization : OpenIddictEntityFrameworkCoreAuthorization<TKey, TApplication, TToken>
where TScope : OpenIddictEntityFrameworkCoreScope<TKey> where TScope : OpenIddictEntityFrameworkCoreScope<TKey>
where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization> where TToken : OpenIddictEntityFrameworkCoreToken<TKey, TApplication, TAuthorization>
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ => builder
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
return builder
.ApplyConfiguration(new OpenIddictEntityFrameworkCoreApplicationConfiguration<TApplication, TAuthorization, TToken, TKey>()) .ApplyConfiguration(new OpenIddictEntityFrameworkCoreApplicationConfiguration<TApplication, TAuthorization, TToken, TKey>())
.ApplyConfiguration(new OpenIddictEntityFrameworkCoreAuthorizationConfiguration<TAuthorization, TApplication, TToken, TKey>()) .ApplyConfiguration(new OpenIddictEntityFrameworkCoreAuthorizationConfiguration<TAuthorization, TApplication, TToken, TKey>())
.ApplyConfiguration(new OpenIddictEntityFrameworkCoreScopeConfiguration<TScope, TKey>()) .ApplyConfiguration(new OpenIddictEntityFrameworkCoreScopeConfiguration<TScope, TKey>())
.ApplyConfiguration(new OpenIddictEntityFrameworkCoreTokenConfiguration<TToken, TApplication, TAuthorization, TKey>()); .ApplyConfiguration(new OpenIddictEntityFrameworkCoreTokenConfiguration<TToken, TApplication, TAuthorization, TKey>());
}
#if SUPPORTS_BCL_ASYNC_ENUMERABLE #if SUPPORTS_BCL_ASYNC_ENUMERABLE
/// <summary> /// <summary>
@ -146,13 +132,8 @@ public static class OpenIddictEntityFrameworkCoreHelpers
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The non-streamed async enumeration containing the results.</returns> /// <returns>The non-streamed async enumeration containing the results.</returns>
#endif #endif
internal static IAsyncEnumerable<T> AsAsyncEnumerable<T>(this IQueryable<T> source, CancellationToken cancellationToken) internal static IAsyncEnumerable<T> AsAsyncEnumerable<T>(this IQueryable<T> source!!, CancellationToken cancellationToken)
{ {
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return ExecuteAsync(source, cancellationToken); return ExecuteAsync(source, cancellationToken);
static async IAsyncEnumerable<T> ExecuteAsync(IQueryable<T> source, [EnumeratorCancellation] CancellationToken cancellationToken) static async IAsyncEnumerable<T> ExecuteAsync(IQueryable<T> source, [EnumeratorCancellation] CancellationToken cancellationToken)

6
src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreApplicationStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkCoreApplicationStoreResolver : IOpenIddict
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkCoreApplicationStoreResolver( public OpenIddictEntityFrameworkCoreApplicationStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreAuthorizationStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStoreResolver : IOpenIddi
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkCoreAuthorizationStoreResolver( public OpenIddictEntityFrameworkCoreAuthorizationStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreScopeStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkCoreScopeStoreResolver : IOpenIddictScopeS
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkCoreScopeStoreResolver( public OpenIddictEntityFrameworkCoreScopeStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

6
src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreTokenStoreResolver.cs

@ -22,9 +22,9 @@ public class OpenIddictEntityFrameworkCoreTokenStoreResolver : IOpenIddictTokenS
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictEntityFrameworkCoreTokenStoreResolver( public OpenIddictEntityFrameworkCoreTokenStoreResolver(
TypeResolutionCache cache, TypeResolutionCache cache!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options, IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_cache = cache; _cache = cache;
_options = options; _options = options;

279
src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreApplicationStore.cs

@ -31,7 +31,7 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TContext> :
public OpenIddictEntityFrameworkCoreApplicationStore( public OpenIddictEntityFrameworkCoreApplicationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -52,7 +52,7 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TContext, TKey> :
public OpenIddictEntityFrameworkCoreApplicationStore( public OpenIddictEntityFrameworkCoreApplicationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -74,9 +74,9 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkCoreApplicationStore( public OpenIddictEntityFrameworkCoreApplicationStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -118,37 +118,20 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
=> await Applications.AsQueryable().LongCountAsync(cancellationToken); => await Applications.AsQueryable().LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Applications).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Applications).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
Context.Add(application); Context.Add(application);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
async ValueTask<IDbContextTransaction?> CreateTransactionAsync() async ValueTask<IDbContextTransaction?> CreateTransactionAsync()
{ {
// Note: transactions that specify an explicit isolation level are only supported by // Note: transactions that specify an explicit isolation level are only supported by
@ -345,83 +328,36 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(Applications.AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Applications.AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientId);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientSecretAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientSecretAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientSecret);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientSecret);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.Type);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ConsentType);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ConsentType);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.DisplayName);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.DisplayName);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.DisplayNames)) if (string.IsNullOrEmpty(application.DisplayNames))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified display names is an expensive operation. // Note: parsing the stringified display names is an expensive operation.
@ -449,31 +385,19 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(names); return new(names);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(application.Id));
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(ConvertIdentifierToString(application.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Permissions)) if (string.IsNullOrEmpty(application.Permissions))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified permissions is an expensive operation. // Note: parsing the stringified permissions is an expensive operation.
@ -501,20 +425,15 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(permissions); return new(permissions);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.PostLogoutRedirectUris)) if (string.IsNullOrEmpty(application.PostLogoutRedirectUris))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified addresses is an expensive operation. // Note: parsing the stringified addresses is an expensive operation.
@ -542,20 +461,15 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(addresses); return new(addresses);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Properties)) if (string.IsNullOrEmpty(application.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -577,20 +491,15 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.RedirectUris)) if (string.IsNullOrEmpty(application.RedirectUris))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified addresses is an expensive operation. // Note: parsing the stringified addresses is an expensive operation.
@ -618,20 +527,15 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(addresses); return new(addresses);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (string.IsNullOrEmpty(application.Requirements)) if (string.IsNullOrEmpty(application.Requirements))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified requirements is an expensive operation. // Note: parsing the stringified requirements is an expensive operation.
@ -659,7 +563,7 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(requirements); return new(requirements);
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -667,12 +571,12 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
{ {
try try
{ {
return new ValueTask<TApplication>(Activator.CreateInstance<TApplication>()); return new(Activator.CreateInstance<TApplication>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TApplication>(Task.FromException<TApplication>( return new(Task.FromException<TApplication>(
new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception)));
} }
} }
@ -697,91 +601,54 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(Applications.AsTracking(), state).AsAsyncEnumerable(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(Applications.AsTracking(), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientIdAsync(TApplication application, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetClientIdAsync(TApplication application!!, string? identifier, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientId = identifier; application.ClientId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientSecretAsync(TApplication application, string? secret, CancellationToken cancellationToken) public virtual ValueTask SetClientSecretAsync(TApplication application!!, string? secret, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientSecret = secret; application.ClientSecret = secret;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientTypeAsync(TApplication application, string? type, CancellationToken cancellationToken) public virtual ValueTask SetClientTypeAsync(TApplication application!!, string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.Type = type; application.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetConsentTypeAsync(TApplication application, string? type, CancellationToken cancellationToken) public virtual ValueTask SetConsentTypeAsync(TApplication application!!, string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ConsentType = type; application.ConsentType = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TApplication application, string? name, CancellationToken cancellationToken) public virtual ValueTask SetDisplayNameAsync(TApplication application!!, string? name, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.DisplayName = name; application.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TApplication application, public virtual ValueTask SetDisplayNamesAsync(TApplication application!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (names is null || names.IsEmpty) if (names is null || names.IsEmpty)
{ {
application.DisplayNames = null; application.DisplayNames = null;
@ -813,13 +680,8 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPermissionsAsync(TApplication application, ImmutableArray<string> permissions, CancellationToken cancellationToken) public virtual ValueTask SetPermissionsAsync(TApplication application!!, ImmutableArray<string> permissions, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (permissions.IsDefaultOrEmpty) if (permissions.IsDefaultOrEmpty)
{ {
application.Permissions = null; application.Permissions = null;
@ -850,14 +712,9 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application, public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.PostLogoutRedirectUris = null; application.PostLogoutRedirectUris = null;
@ -888,15 +745,10 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TApplication application, public virtual ValueTask SetPropertiesAsync(TApplication application!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (application is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(application));
}
if (properties is null || properties.IsEmpty)
{ {
application.Properties = null; application.Properties = null;
@ -927,14 +779,9 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedirectUrisAsync(TApplication application, public virtual ValueTask SetRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.RedirectUris = null; application.RedirectUris = null;
@ -965,13 +812,8 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRequirementsAsync(TApplication application, ImmutableArray<string> requirements, CancellationToken cancellationToken) public virtual ValueTask SetRequirementsAsync(TApplication application!!, ImmutableArray<string> requirements, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (requirements.IsDefaultOrEmpty) if (requirements.IsDefaultOrEmpty)
{ {
application.Requirements = null; application.Requirements = null;
@ -1002,13 +844,8 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
Context.Attach(application); Context.Attach(application);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

204
src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreAuthorizationStore.cs

@ -30,7 +30,7 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TContext> :
public OpenIddictEntityFrameworkCoreAuthorizationStore( public OpenIddictEntityFrameworkCoreAuthorizationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -51,7 +51,7 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TContext, TKey> :
public OpenIddictEntityFrameworkCoreAuthorizationStore( public OpenIddictEntityFrameworkCoreAuthorizationStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -73,9 +73,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkCoreAuthorizationStore( public OpenIddictEntityFrameworkCoreAuthorizationStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -117,37 +117,20 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
=> await Authorizations.AsQueryable().LongCountAsync(cancellationToken); => await Authorizations.AsQueryable().LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Authorizations).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Authorizations).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
Context.Add(authorization); Context.Add(authorization);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
async ValueTask<IDbContextTransaction?> CreateTransactionAsync() async ValueTask<IDbContextTransaction?> CreateTransactionAsync()
{ {
// Note: transactions that specify an explicit isolation level are only supported by // Note: transactions that specify an explicit isolation level are only supported by
@ -426,13 +409,8 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
// If the application is not attached to the authorization, try to load it manually. // If the application is not attached to the authorization, try to load it manually.
if (authorization.Application is null) if (authorization.Application is null)
{ {
@ -455,57 +433,26 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(
Authorizations.Include(authorization => authorization.Application) Authorizations.Include(authorization => authorization.Application)
.AsTracking(), state).FirstOrDefaultAsync(cancellationToken); .AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(authorization.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(authorization.Id));
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(ConvertIdentifierToString(authorization.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(authorization.Properties)) if (string.IsNullOrEmpty(authorization.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -527,20 +474,15 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (string.IsNullOrEmpty(authorization.Scopes)) if (string.IsNullOrEmpty(authorization.Scopes))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified scopes is an expensive operation. // Note: parsing the stringified scopes is an expensive operation.
@ -568,53 +510,32 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(scopes); return new(scopes);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Status);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Subject);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Type);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TAuthorization>(Activator.CreateInstance<TAuthorization>()); return new(Activator.CreateInstance<TAuthorization>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TAuthorization>(Task.FromException<TAuthorization>( return new(Task.FromException<TAuthorization>(
new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception)));
} }
} }
@ -641,14 +562,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query( return query(
Authorizations.Include(authorization => authorization.Application) Authorizations.Include(authorization => authorization.Application)
.AsTracking(), state).AsAsyncEnumerable(cancellationToken); .AsTracking(), state).AsAsyncEnumerable(cancellationToken);
@ -746,14 +662,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetApplicationIdAsync(TAuthorization authorization, public virtual async ValueTask SetApplicationIdAsync(TAuthorization authorization!!,
string? identifier, CancellationToken cancellationToken) string? identifier, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var key = ConvertIdentifierFromString(identifier); var key = ConvertIdentifierFromString(identifier);
@ -792,29 +703,19 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TAuthorization authorization, public virtual ValueTask SetCreationDateAsync(TAuthorization authorization!!,
DateTimeOffset? date, CancellationToken cancellationToken) DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.CreationDate = date?.UtcDateTime; authorization.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TAuthorization authorization, public virtual ValueTask SetPropertiesAsync(TAuthorization authorization!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (authorization is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(authorization));
}
if (properties is null || properties.IsEmpty)
{ {
authorization.Properties = null; authorization.Properties = null;
@ -845,14 +746,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetScopesAsync(TAuthorization authorization, public virtual ValueTask SetScopesAsync(TAuthorization authorization!!,
ImmutableArray<string> scopes, CancellationToken cancellationToken) ImmutableArray<string> scopes, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (scopes.IsDefaultOrEmpty) if (scopes.IsDefaultOrEmpty)
{ {
authorization.Scopes = null; authorization.Scopes = null;
@ -883,55 +779,35 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TAuthorization authorization, public virtual ValueTask SetStatusAsync(TAuthorization authorization!!,
string? status, CancellationToken cancellationToken) string? status, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Status = status; authorization.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TAuthorization authorization, public virtual ValueTask SetSubjectAsync(TAuthorization authorization!!,
string? subject, CancellationToken cancellationToken) string? subject, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Subject = subject; authorization.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TAuthorization authorization, public virtual ValueTask SetTypeAsync(TAuthorization authorization!!,
string? type, CancellationToken cancellationToken) string? type, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Type = type; authorization.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
Context.Attach(authorization); Context.Attach(authorization);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

209
src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreScopeStore.cs

@ -27,7 +27,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TContext> : OpenIddictEntit
public OpenIddictEntityFrameworkCoreScopeStore( public OpenIddictEntityFrameworkCoreScopeStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -45,7 +45,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TContext, TKey> : OpenIddic
public OpenIddictEntityFrameworkCoreScopeStore( public OpenIddictEntityFrameworkCoreScopeStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -63,9 +63,9 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkCoreScopeStore( public OpenIddictEntityFrameworkCoreScopeStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -97,37 +97,20 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
=> await Scopes.AsQueryable().LongCountAsync(cancellationToken); => await Scopes.AsQueryable().LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Scopes).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Scopes).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Scopes.Add(scope); Scopes.Add(scope);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Context.Remove(scope); Context.Remove(scope);
try try
@ -176,7 +159,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
public virtual IAsyncEnumerable<TScope> FindByNamesAsync( public virtual IAsyncEnumerable<TScope> FindByNamesAsync(
ImmutableArray<string> names, CancellationToken cancellationToken) ImmutableArray<string> names, CancellationToken cancellationToken)
{ {
if (names.Any(name => string.IsNullOrEmpty(name))) if (names.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
@ -224,39 +207,20 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(Scopes.AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Scopes.AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDescriptionAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDescriptionAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Description);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Description);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Descriptions)) if (string.IsNullOrEmpty(scope.Descriptions))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified descriptions is an expensive operation. // Note: parsing the stringified descriptions is an expensive operation.
@ -284,31 +248,19 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(descriptions); return new(descriptions);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.DisplayName);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.DisplayName);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.DisplayNames)) if (string.IsNullOrEmpty(scope.DisplayNames))
{ {
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>()); return new(ImmutableDictionary.Create<CultureInfo, string>());
} }
// Note: parsing the stringified display names is an expensive operation. // Note: parsing the stringified display names is an expensive operation.
@ -336,42 +288,23 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(names); return new(names);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(scope.Id));
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(ConvertIdentifierToString(scope.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Name);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Name);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Properties)) if (string.IsNullOrEmpty(scope.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -393,20 +326,15 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (string.IsNullOrEmpty(scope.Resources)) if (string.IsNullOrEmpty(scope.Resources))
{ {
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>()); return new(ImmutableArray.Create<string>());
} }
// Note: parsing the stringified resources is an expensive operation. // Note: parsing the stringified resources is an expensive operation.
@ -434,7 +362,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableArray<string>>(resources); return new(resources);
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -442,12 +370,12 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
{ {
try try
{ {
return new ValueTask<TScope>(Activator.CreateInstance<TScope>()); return new(Activator.CreateInstance<TScope>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TScope>(Task.FromException<TScope>( return new(Task.FromException<TScope>(
new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception)));
} }
} }
@ -472,39 +400,22 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(Scopes.AsTracking(), state).AsAsyncEnumerable(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(Scopes.AsTracking(), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionAsync(TScope scope, string? description, CancellationToken cancellationToken) public virtual ValueTask SetDescriptionAsync(TScope scope!!, string? description, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Description = description; scope.Description = description;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionsAsync(TScope scope, public virtual ValueTask SetDescriptionsAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (descriptions is null || descriptions.IsEmpty) if (descriptions is null || descriptions.IsEmpty)
{ {
scope.Descriptions = null; scope.Descriptions = null;
@ -536,27 +447,17 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetDisplayNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.DisplayName = name; scope.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TScope scope, public virtual ValueTask SetDisplayNamesAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (names is null || names.IsEmpty) if (names is null || names.IsEmpty)
{ {
scope.DisplayNames = null; scope.DisplayNames = null;
@ -588,28 +489,18 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Name = name; scope.Name = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TScope scope, public virtual ValueTask SetPropertiesAsync(TScope scope!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (scope is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(scope));
}
if (properties is null || properties.IsEmpty)
{ {
scope.Properties = null; scope.Properties = null;
@ -640,13 +531,8 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetResourcesAsync(TScope scope, ImmutableArray<string> resources, CancellationToken cancellationToken) public virtual ValueTask SetResourcesAsync(TScope scope!!, ImmutableArray<string> resources, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (resources.IsDefaultOrEmpty) if (resources.IsDefaultOrEmpty)
{ {
scope.Resources = null; scope.Resources = null;
@ -677,13 +563,8 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
Context.Attach(scope); Context.Attach(scope);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

286
src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreTokenStore.cs

@ -29,7 +29,7 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TContext> :
public OpenIddictEntityFrameworkCoreTokenStore( public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -50,7 +50,7 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TContext, TKey> :
public OpenIddictEntityFrameworkCoreTokenStore( public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache, IMemoryCache cache,
TContext context, TContext context,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
: base(cache, context, options) : base(cache, context, options)
{ {
} }
@ -72,9 +72,9 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
where TKey : notnull, IEquatable<TKey> where TKey : notnull, IEquatable<TKey>
{ {
public OpenIddictEntityFrameworkCoreTokenStore( public OpenIddictEntityFrameworkCoreTokenStore(
IMemoryCache cache, IMemoryCache cache!!,
TContext context, TContext context!!,
IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options) IOptionsMonitor<OpenIddictEntityFrameworkCoreOptions> options!!)
{ {
Cache = cache; Cache = cache;
Context = context; Context = context;
@ -116,37 +116,20 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
=> await Tokens.AsQueryable().LongCountAsync(cancellationToken); => await Tokens.AsQueryable().LongCountAsync(cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken) public virtual async ValueTask<long> CountAsync<TResult>(Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ => await query(Tokens).LongCountAsync(cancellationToken);
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Tokens).LongCountAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Context.Add(token); Context.Add(token);
await Context.SaveChangesAsync(cancellationToken); await Context.SaveChangesAsync(cancellationToken);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Context.Remove(token); Context.Remove(token);
try try
@ -350,13 +333,8 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetApplicationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the application is not attached to the token, try to load it manually. // If the application is not attached to the token, try to load it manually.
if (token.Application is null) if (token.Application is null)
{ {
@ -379,27 +357,15 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => await query(Tokens.Include(token => token.Application)
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return await query(Tokens.Include(token => token.Application)
.Include(token => token.Authorization) .Include(token => token.Authorization)
.AsTracking(), state).FirstOrDefaultAsync(cancellationToken); .AsTracking(), state).FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<string?> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask<string?> GetAuthorizationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// If the authorization is not attached to the token, try to load it manually. // If the authorization is not attached to the token, try to load it manually.
if (token.Authorization is null) if (token.Authorization is null)
{ {
@ -421,70 +387,27 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ExpirationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.ExpirationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.ExpirationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(ConvertIdentifierToString(token.Id));
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(ConvertIdentifierToString(token.Id));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetPayloadAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetPayloadAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Payload);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Payload);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (string.IsNullOrEmpty(token.Properties)) if (string.IsNullOrEmpty(token.Properties))
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
// Note: parsing the stringified properties is an expensive operation. // Note: parsing the stringified properties is an expensive operation.
@ -506,80 +429,40 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
return builder.ToImmutable(); return builder.ToImmutable();
}); });
return new ValueTask<ImmutableDictionary<string, JsonElement>>(properties); return new(properties);
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.RedemptionDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.RedemptionDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.RedemptionDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetReferenceIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ReferenceId);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.ReferenceId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Status);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Subject);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Type);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TToken>(Activator.CreateInstance<TToken>()); return new(Activator.CreateInstance<TToken>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TToken>(Task.FromException<TToken>( return new(Task.FromException<TToken>(
new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception)));
} }
} }
@ -607,19 +490,12 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ => query(
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return query(
Tokens.Include(token => token.Application) Tokens.Include(token => token.Application)
.Include(token => token.Authorization) .Include(token => token.Authorization)
.AsTracking(), state).AsAsyncEnumerable(cancellationToken); .AsTracking(), state).AsAsyncEnumerable(cancellationToken);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken) public virtual async ValueTask PruneAsync(DateTimeOffset threshold, CancellationToken cancellationToken)
@ -710,13 +586,8 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetApplicationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual async ValueTask SetApplicationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var key = ConvertIdentifierFromString(identifier); var key = ConvertIdentifierFromString(identifier);
@ -755,13 +626,8 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask SetAuthorizationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual async ValueTask SetAuthorizationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var key = ConvertIdentifierFromString(identifier); var key = ConvertIdentifierFromString(identifier);
@ -800,54 +666,34 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetCreationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.CreationDate = date?.UtcDateTime; token.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetExpirationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetExpirationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ExpirationDate = date?.UtcDateTime; token.ExpirationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPayloadAsync(TToken token, string? payload, CancellationToken cancellationToken) public virtual ValueTask SetPayloadAsync(TToken token!!, string? payload, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Payload = payload; token.Payload = payload;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TToken token, public virtual ValueTask SetPropertiesAsync(TToken token!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (token is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(token));
}
if (properties is null || properties.IsEmpty)
{ {
token.Properties = null; token.Properties = null;
@ -878,78 +724,48 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedemptionDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetRedemptionDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.RedemptionDate = date?.UtcDateTime; token.RedemptionDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetReferenceIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetReferenceIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ReferenceId = identifier; token.ReferenceId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TToken token, string? status, CancellationToken cancellationToken) public virtual ValueTask SetStatusAsync(TToken token!!, string? status, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Status = status; token.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TToken token, string? subject, CancellationToken cancellationToken) public virtual ValueTask SetSubjectAsync(TToken token!!, string? subject, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Subject = subject; token.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TToken token, string? type, CancellationToken cancellationToken) public virtual ValueTask SetTypeAsync(TToken token!!, string? type, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Type = type; token.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
Context.Attach(token); Context.Attach(token);
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it

18
src/OpenIddict.MongoDb/OpenIddictMongoDbBuilder.cs

@ -20,8 +20,8 @@ public class OpenIddictMongoDbBuilder
/// Initializes a new instance of <see cref="OpenIddictMongoDbBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictMongoDbBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictMongoDbBuilder(IServiceCollection services) public OpenIddictMongoDbBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -35,13 +35,8 @@ public class OpenIddictMongoDbBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns>
public OpenIddictMongoDbBuilder Configure(Action<OpenIddictMongoDbOptions> configuration) public OpenIddictMongoDbBuilder Configure(Action<OpenIddictMongoDbOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;
@ -161,13 +156,8 @@ public class OpenIddictMongoDbBuilder
/// </summary> /// </summary>
/// <param name="database">The <see cref="IMongoDatabase"/>.</param> /// <param name="database">The <see cref="IMongoDatabase"/>.</param>
/// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns>
public OpenIddictMongoDbBuilder UseDatabase(IMongoDatabase database) public OpenIddictMongoDbBuilder UseDatabase(IMongoDatabase database!!)
{ {
if (database is null)
{
throw new ArgumentNullException(nameof(database));
}
return Configure(options => options.Database = database); return Configure(options => options.Database = database);
} }

10
src/OpenIddict.MongoDb/OpenIddictMongoDbContext.cs

@ -16,8 +16,8 @@ public class OpenIddictMongoDbContext : IOpenIddictMongoDbContext
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictMongoDbContext( public OpenIddictMongoDbContext(
IOptionsMonitor<OpenIddictMongoDbOptions> options, IOptionsMonitor<OpenIddictMongoDbOptions> options!!,
IServiceProvider provider) IServiceProvider provider!!)
{ {
_options = options; _options = options;
_provider = provider; _provider = provider;
@ -28,7 +28,7 @@ public class OpenIddictMongoDbContext : IOpenIddictMongoDbContext
{ {
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
{ {
return new ValueTask<IMongoDatabase>(Task.FromCanceled<IMongoDatabase>(cancellationToken)); return new(Task.FromCanceled<IMongoDatabase>(cancellationToken));
} }
var database = _options.CurrentValue.Database; var database = _options.CurrentValue.Database;
@ -39,10 +39,10 @@ public class OpenIddictMongoDbContext : IOpenIddictMongoDbContext
if (database is null) if (database is null)
{ {
return new ValueTask<IMongoDatabase>(Task.FromException<IMongoDatabase>( return new(Task.FromException<IMongoDatabase>(
new InvalidOperationException(SR.GetResourceString(SR.ID0262)))); new InvalidOperationException(SR.GetResourceString(SR.ID0262))));
} }
return new ValueTask<IMongoDatabase>(database); return new(database);
} }
} }

19
src/OpenIddict.MongoDb/OpenIddictMongoDbExtensions.cs

@ -22,13 +22,8 @@ public static class OpenIddictMongoDbExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictMongoDbBuilder"/>.</returns>
public static OpenIddictMongoDbBuilder UseMongoDb(this OpenIddictCoreBuilder builder) public static OpenIddictMongoDbBuilder UseMongoDb(this OpenIddictCoreBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
// Note: Mongo uses simple binary comparison checks by default so the additional // Note: Mongo uses simple binary comparison checks by default so the additional
// query filtering applied by the default OpenIddict managers can be safely disabled. // query filtering applied by the default OpenIddict managers can be safely disabled.
builder.DisableAdditionalFiltering(); builder.DisableAdditionalFiltering();
@ -64,18 +59,8 @@ public static class OpenIddictMongoDbExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public static OpenIddictCoreBuilder UseMongoDb( public static OpenIddictCoreBuilder UseMongoDb(
this OpenIddictCoreBuilder builder, Action<OpenIddictMongoDbBuilder> configuration) this OpenIddictCoreBuilder builder!!, Action<OpenIddictMongoDbBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseMongoDb()); configuration(builder.UseMongoDb());
return builder; return builder;

18
src/OpenIddict.MongoDb/OpenIddictMongoDbHelpers.cs

@ -20,13 +20,8 @@ internal static class OpenIddictMongoDbHelpers
/// <param name="source">The query source.</param> /// <param name="source">The query source.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The streamed async enumeration containing the results.</returns> /// <returns>The streamed async enumeration containing the results.</returns>
internal static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IAsyncCursorSource<T> source, CancellationToken cancellationToken) internal static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IAsyncCursorSource<T> source!!, CancellationToken cancellationToken)
{ {
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return ExecuteAsync(source, cancellationToken); return ExecuteAsync(source, cancellationToken);
static async IAsyncEnumerable<T> ExecuteAsync(IAsyncCursorSource<T> source, [EnumeratorCancellation] CancellationToken cancellationToken) static async IAsyncEnumerable<T> ExecuteAsync(IAsyncCursorSource<T> source, [EnumeratorCancellation] CancellationToken cancellationToken)
@ -50,13 +45,6 @@ internal static class OpenIddictMongoDbHelpers
/// <param name="source">The query source.</param> /// <param name="source">The query source.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The streamed async enumeration containing the results.</returns> /// <returns>The streamed async enumeration containing the results.</returns>
internal static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IQueryable<T> source, CancellationToken cancellationToken) internal static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IQueryable<T> source!!, CancellationToken cancellationToken)
{ => ((IAsyncCursorSource<T>) source).ToAsyncEnumerable(cancellationToken);
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return ((IAsyncCursorSource<T>) source).ToAsyncEnumerable(cancellationToken);
}
} }

2
src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbApplicationStoreResolver.cs

@ -18,7 +18,7 @@ public class OpenIddictMongoDbApplicationStoreResolver : IOpenIddictApplicationS
private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>(); private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>();
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictMongoDbApplicationStoreResolver(IServiceProvider provider) public OpenIddictMongoDbApplicationStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbAuthorizationStoreResolver.cs

@ -18,7 +18,7 @@ public class OpenIddictMongoDbAuthorizationStoreResolver : IOpenIddictAuthorizat
private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>(); private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>();
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictMongoDbAuthorizationStoreResolver(IServiceProvider provider) public OpenIddictMongoDbAuthorizationStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbScopeStoreResolver.cs

@ -18,7 +18,7 @@ public class OpenIddictMongoDbScopeStoreResolver : IOpenIddictScopeStoreResolver
private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>(); private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>();
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictMongoDbScopeStoreResolver(IServiceProvider provider) public OpenIddictMongoDbScopeStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

2
src/OpenIddict.MongoDb/Resolvers/OpenIddictMongoDbTokenStoreResolver.cs

@ -18,7 +18,7 @@ public class OpenIddictMongoDbTokenStoreResolver : IOpenIddictTokenStoreResolver
private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>(); private readonly ConcurrentDictionary<Type, Type> _cache = new ConcurrentDictionary<Type, Type>();
private readonly IServiceProvider _provider; private readonly IServiceProvider _provider;
public OpenIddictMongoDbTokenStoreResolver(IServiceProvider provider) public OpenIddictMongoDbTokenStoreResolver(IServiceProvider provider!!)
=> _provider = provider; => _provider = provider;
/// <summary> /// <summary>

295
src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbApplicationStore.cs

@ -23,8 +23,8 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
where TApplication : OpenIddictMongoDbApplication where TApplication : OpenIddictMongoDbApplication
{ {
public OpenIddictMongoDbApplicationStore( public OpenIddictMongoDbApplicationStore(
IOpenIddictMongoDbContext context, IOpenIddictMongoDbContext context!!,
IOptionsMonitor<OpenIddictMongoDbOptions> options) IOptionsMonitor<OpenIddictMongoDbOptions> options!!)
{ {
Context = context; Context = context;
Options = options; Options = options;
@ -51,13 +51,8 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>( public virtual async ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken) Func<IQueryable<TApplication>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName); var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName);
@ -65,13 +60,8 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName); var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName);
@ -79,13 +69,8 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName); var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName);
@ -135,8 +120,7 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TApplication> FindByPostLogoutRedirectUriAsync( public virtual IAsyncEnumerable<TApplication> FindByPostLogoutRedirectUriAsync(string address, CancellationToken cancellationToken)
string address, CancellationToken cancellationToken)
{ {
if (string.IsNullOrEmpty(address)) if (string.IsNullOrEmpty(address))
{ {
@ -159,8 +143,7 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TApplication> FindByRedirectUriAsync( public virtual IAsyncEnumerable<TApplication> FindByRedirectUriAsync(string address, CancellationToken cancellationToken)
string address, CancellationToken cancellationToken)
{ {
if (string.IsNullOrEmpty(address)) if (string.IsNullOrEmpty(address))
{ {
@ -184,14 +167,9 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName); var collection = database.GetCollection<TApplication>(Options.CurrentValue.ApplicationsCollectionName);
@ -199,132 +177,47 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientId);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientSecretAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientSecretAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ClientSecret);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ClientSecret);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetClientTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetClientTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.Type);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetConsentTypeAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.ConsentType);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.ConsentType);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.DisplayName);
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.DisplayName);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.DisplayNames is { Count: > 0 } names ? names.ToImmutableDictionary() : ImmutableDictionary.Create<CultureInfo, string>());
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.DisplayNames is null || application.DisplayNames.Count == 0)
{
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>());
}
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(application.DisplayNames.ToImmutableDictionary());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.Id.ToString());
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string?>(application.Id.ToString());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync( public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application!!, CancellationToken cancellationToken)
TApplication application, CancellationToken cancellationToken) => new(application.Permissions is { Count: > 0 } permissions ? permissions.ToImmutableArray() : ImmutableArray.Create<string>());
{
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.Permissions is null || application.Permissions.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(application.Permissions.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync( public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
TApplication application, CancellationToken cancellationToken) => new(application.PostLogoutRedirectUris is { Count: > 0 } addresses ? addresses.ToImmutableArray() : ImmutableArray.Create<string>());
{
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.PostLogoutRedirectUris is null || application.PostLogoutRedirectUris.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(application.PostLogoutRedirectUris.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.Properties is null) if (application.Properties is null)
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
using var document = JsonDocument.Parse(application.Properties.ToJson()); using var document = JsonDocument.Parse(application.Properties.ToJson());
@ -335,53 +228,28 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
builder[property.Name] = property.Value.Clone(); builder[property.Name] = property.Value.Clone();
} }
return new ValueTask<ImmutableDictionary<string, JsonElement>>(builder.ToImmutable()); return new(builder.ToImmutable());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync( public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application!!, CancellationToken cancellationToken)
TApplication application, CancellationToken cancellationToken) => new(application.RedirectUris is { Count: > 0 } addresses ? addresses.ToImmutableArray() : ImmutableArray.Create<string>());
{
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.RedirectUris is null || application.RedirectUris.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(application.RedirectUris.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetRequirementsAsync(TApplication application!!, CancellationToken cancellationToken)
{ => new(application.Requirements is { Count: > 0 } requirements ? requirements.ToImmutableArray() : ImmutableArray.Create<string>());
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (application.Requirements is null || application.Requirements.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(application.Requirements.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TApplication> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TApplication> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TApplication>(Activator.CreateInstance<TApplication>()); return new(Activator.CreateInstance<TApplication>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TApplication>(Task.FromException<TApplication>( return new(Task.FromException<TApplication>(
new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0240), exception)));
} }
} }
@ -413,14 +281,9 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query, Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ExecuteAsync(cancellationToken); return ExecuteAsync(cancellationToken);
async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken) async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken)
@ -436,97 +299,62 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientIdAsync(TApplication application, public virtual ValueTask SetClientIdAsync(TApplication application!!,
string? identifier, CancellationToken cancellationToken) string? identifier, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientId = identifier; application.ClientId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientSecretAsync(TApplication application, public virtual ValueTask SetClientSecretAsync(TApplication application!!,
string? secret, CancellationToken cancellationToken) string? secret, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientSecret = secret; application.ClientSecret = secret;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetClientTypeAsync(TApplication application, public virtual ValueTask SetClientTypeAsync(TApplication application!!,
string? type, CancellationToken cancellationToken) string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.Type = type; application.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetConsentTypeAsync(TApplication application, public virtual ValueTask SetConsentTypeAsync(TApplication application!!,
string? type, CancellationToken cancellationToken) string? type, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.ConsentType = type; application.ConsentType = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TApplication application, public virtual ValueTask SetDisplayNameAsync(TApplication application!!,
string? name, CancellationToken cancellationToken) string? name, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.DisplayName = name; application.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TApplication application, public virtual ValueTask SetDisplayNamesAsync(TApplication application!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
application.DisplayNames = names; application.DisplayNames = names;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPermissionsAsync(TApplication application, ImmutableArray<string> permissions, CancellationToken cancellationToken) public virtual ValueTask SetPermissionsAsync(TApplication application!!, ImmutableArray<string> permissions, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (permissions.IsDefaultOrEmpty) if (permissions.IsDefaultOrEmpty)
{ {
application.Permissions = ImmutableList.Create<string>(); application.Permissions = ImmutableList.Create<string>();
@ -540,14 +368,9 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application, public virtual ValueTask SetPostLogoutRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.PostLogoutRedirectUris = ImmutableList.Create<string>(); application.PostLogoutRedirectUris = ImmutableList.Create<string>();
@ -561,15 +384,10 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TApplication application, public virtual ValueTask SetPropertiesAsync(TApplication application!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (application is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(application));
}
if (properties is null || properties.IsEmpty)
{ {
application.Properties = null; application.Properties = null;
@ -600,14 +418,9 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedirectUrisAsync(TApplication application, public virtual ValueTask SetRedirectUrisAsync(TApplication application!!,
ImmutableArray<string> addresses, CancellationToken cancellationToken) ImmutableArray<string> addresses, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (addresses.IsDefaultOrEmpty) if (addresses.IsDefaultOrEmpty)
{ {
application.RedirectUris = ImmutableList.Create<string>(); application.RedirectUris = ImmutableList.Create<string>();
@ -621,14 +434,9 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRequirementsAsync(TApplication application, public virtual ValueTask SetRequirementsAsync(TApplication application!!,
ImmutableArray<string> requirements, CancellationToken cancellationToken) ImmutableArray<string> requirements, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
if (requirements.IsDefaultOrEmpty) if (requirements.IsDefaultOrEmpty)
{ {
application.Requirements = ImmutableList.Create<string>(); application.Requirements = ImmutableList.Create<string>();
@ -642,13 +450,8 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TApplication application, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TApplication application!!, CancellationToken cancellationToken)
{ {
if (application is null)
{
throw new ArgumentNullException(nameof(application));
}
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it
// to the application before persisting the changes. // to the application before persisting the changes.
var timestamp = application.ConcurrencyToken; var timestamp = application.ConcurrencyToken;

199
src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbAuthorizationStore.cs

@ -22,8 +22,8 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
where TAuthorization : OpenIddictMongoDbAuthorization where TAuthorization : OpenIddictMongoDbAuthorization
{ {
public OpenIddictMongoDbAuthorizationStore( public OpenIddictMongoDbAuthorizationStore(
IOpenIddictMongoDbContext context, IOpenIddictMongoDbContext context!!,
IOptionsMonitor<OpenIddictMongoDbOptions> options) IOptionsMonitor<OpenIddictMongoDbOptions> options!!)
{ {
Context = context; Context = context;
Options = options; Options = options;
@ -50,13 +50,8 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>( public virtual async ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TAuthorization>, IQueryable<TResult>> query, CancellationToken cancellationToken) Func<IQueryable<TAuthorization>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName); var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName);
@ -64,13 +59,8 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName); var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName);
@ -78,13 +68,8 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName); var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName);
@ -321,31 +306,21 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetApplicationIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.ApplicationId == ObjectId.Empty) if (authorization.ApplicationId == ObjectId.Empty)
{ {
return new ValueTask<string?>(result: null); return new(result: null);
} }
return new ValueTask<string?>(authorization.ApplicationId.ToString()); return new(authorization.ApplicationId.ToString());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName); var collection = database.GetCollection<TAuthorization>(Options.CurrentValue.AuthorizationsCollectionName);
@ -353,43 +328,19 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(authorization.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Id.ToString());
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Id.ToString());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.Properties is null) if (authorization.Properties is null)
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
using var document = JsonDocument.Parse(authorization.Properties.ToJson()); using var document = JsonDocument.Parse(authorization.Properties.ToJson());
@ -400,69 +351,36 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
builder[property.Name] = property.Value.Clone(); builder[property.Name] = property.Value.Clone();
} }
return new ValueTask<ImmutableDictionary<string, JsonElement>>(builder.ToImmutable()); return new(builder.ToImmutable());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetScopesAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Scopes is { Count: > 0 } scopes ? scopes.ToImmutableArray() : ImmutableArray.Create<string>());
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (authorization.Scopes is null || authorization.Scopes.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(authorization.Scopes.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Status);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Subject);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ => new(authorization.Type);
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
return new ValueTask<string?>(authorization.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TAuthorization> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TAuthorization>(Activator.CreateInstance<TAuthorization>()); return new(Activator.CreateInstance<TAuthorization>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TAuthorization>(Task.FromException<TAuthorization>( return new(Task.FromException<TAuthorization>(
new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0242), exception)));
} }
} }
@ -494,14 +412,9 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query, Func<IQueryable<TAuthorization>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ExecuteAsync(cancellationToken); return ExecuteAsync(cancellationToken);
async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken) async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken)
@ -567,14 +480,9 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetApplicationIdAsync(TAuthorization authorization, public virtual ValueTask SetApplicationIdAsync(TAuthorization authorization!!,
string? identifier, CancellationToken cancellationToken) string? identifier, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
authorization.ApplicationId = ObjectId.Parse(identifier); authorization.ApplicationId = ObjectId.Parse(identifier);
@ -589,29 +497,19 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TAuthorization authorization, public virtual ValueTask SetCreationDateAsync(TAuthorization authorization!!,
DateTimeOffset? date, CancellationToken cancellationToken) DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.CreationDate = date?.UtcDateTime; authorization.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TAuthorization authorization, public virtual ValueTask SetPropertiesAsync(TAuthorization authorization!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (authorization is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(authorization));
}
if (properties is null || properties.IsEmpty)
{ {
authorization.Properties = null; authorization.Properties = null;
@ -642,14 +540,9 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetScopesAsync(TAuthorization authorization, public virtual ValueTask SetScopesAsync(TAuthorization authorization!!,
ImmutableArray<string> scopes, CancellationToken cancellationToken) ImmutableArray<string> scopes, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
if (scopes.IsDefaultOrEmpty) if (scopes.IsDefaultOrEmpty)
{ {
authorization.Scopes = ImmutableList.Create<string>(); authorization.Scopes = ImmutableList.Create<string>();
@ -663,52 +556,32 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TAuthorization authorization, string? status, CancellationToken cancellationToken) public virtual ValueTask SetStatusAsync(TAuthorization authorization!!, string? status, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Status = status; authorization.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TAuthorization authorization, string? subject, CancellationToken cancellationToken) public virtual ValueTask SetSubjectAsync(TAuthorization authorization!!, string? subject, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Subject = subject; authorization.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TAuthorization authorization, string? type, CancellationToken cancellationToken) public virtual ValueTask SetTypeAsync(TAuthorization authorization!!, string? type, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
authorization.Type = type; authorization.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TAuthorization authorization, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TAuthorization authorization!!, CancellationToken cancellationToken)
{ {
if (authorization is null)
{
throw new ArgumentNullException(nameof(authorization));
}
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it
// to the authorization before persisting the changes. // to the authorization before persisting the changes.
var timestamp = authorization.ConcurrencyToken; var timestamp = authorization.ConcurrencyToken;

206
src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbScopeStore.cs

@ -23,8 +23,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
where TScope : OpenIddictMongoDbScope where TScope : OpenIddictMongoDbScope
{ {
public OpenIddictMongoDbScopeStore( public OpenIddictMongoDbScopeStore(
IOpenIddictMongoDbContext context, IOpenIddictMongoDbContext context!!,
IOptionsMonitor<OpenIddictMongoDbOptions> options) IOptionsMonitor<OpenIddictMongoDbOptions> options!!)
{ {
Context = context; Context = context;
Options = options; Options = options;
@ -51,13 +51,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>( public virtual async ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TScope>, IQueryable<TResult>> query, CancellationToken cancellationToken) Func<IQueryable<TScope>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName); var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName);
@ -65,13 +60,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName); var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName);
@ -79,13 +69,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName); var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName);
@ -128,7 +113,7 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TScope> FindByNamesAsync(ImmutableArray<string> names, CancellationToken cancellationToken) public virtual IAsyncEnumerable<TScope> FindByNamesAsync(ImmutableArray<string> names, CancellationToken cancellationToken)
{ {
if (names.Any(name => string.IsNullOrEmpty(name))) if (names.Any(string.IsNullOrEmpty))
{ {
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
@ -173,14 +158,9 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName); var collection = database.GetCollection<TScope>(Options.CurrentValue.ScopesCollectionName);
@ -188,92 +168,35 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDescriptionAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDescriptionAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Description);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Description);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDescriptionsAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Descriptions is { Count: > 0 } descriptions ? descriptions.ToImmutableDictionary() : ImmutableDictionary.Create<CultureInfo, string>());
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (scope.Descriptions is null || scope.Descriptions.Count == 0)
{
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>());
}
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(scope.Descriptions.ToImmutableDictionary());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetDisplayNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.DisplayName);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.DisplayName);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<CultureInfo, string>> GetDisplayNamesAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.DisplayNames is { Count: > 0 } names ? names.ToImmutableDictionary() : ImmutableDictionary.Create<CultureInfo, string>());
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (scope.DisplayNames is null || scope.DisplayNames.Count == 0)
{
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(ImmutableDictionary.Create<CultureInfo, string>());
}
return new ValueTask<ImmutableDictionary<CultureInfo, string>>(scope.DisplayNames.ToImmutableDictionary());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Id.ToString());
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Id.ToString());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetNameAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<string?> GetNameAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Name);
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
return new ValueTask<string?>(scope.Name);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (scope.Properties is null) if (scope.Properties is null)
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
using var document = JsonDocument.Parse(scope.Properties.ToJson()); using var document = JsonDocument.Parse(scope.Properties.ToJson());
@ -284,36 +207,24 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
builder[property.Name] = property.Value.Clone(); builder[property.Name] = property.Value.Clone();
} }
return new ValueTask<ImmutableDictionary<string, JsonElement>>(builder.ToImmutable()); return new(builder.ToImmutable());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope, CancellationToken cancellationToken) public virtual ValueTask<ImmutableArray<string>> GetResourcesAsync(TScope scope!!, CancellationToken cancellationToken)
{ => new(scope.Resources is { Count: > 0 } resources ? resources.ToImmutableArray() : ImmutableArray.Create<string>());
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (scope.Resources is null || scope.Resources.Count == 0)
{
return new ValueTask<ImmutableArray<string>>(ImmutableArray.Create<string>());
}
return new ValueTask<ImmutableArray<string>>(scope.Resources.ToImmutableArray());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TScope> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TScope> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TScope>(Activator.CreateInstance<TScope>()); return new(Activator.CreateInstance<TScope>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TScope>(Task.FromException<TScope>( return new(Task.FromException<TScope>(
new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0246), exception)));
} }
} }
@ -345,14 +256,9 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TScope>, TState, IQueryable<TResult>> query, Func<IQueryable<TScope>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ExecuteAsync(cancellationToken); return ExecuteAsync(cancellationToken);
async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken) async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken)
@ -368,82 +274,52 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionAsync(TScope scope, string? description, CancellationToken cancellationToken) public virtual ValueTask SetDescriptionAsync(TScope scope!!, string? description, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Description = description; scope.Description = description;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDescriptionsAsync(TScope scope, public virtual ValueTask SetDescriptionsAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> descriptions, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Descriptions = descriptions; scope.Descriptions = descriptions;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNamesAsync(TScope scope, public virtual ValueTask SetDisplayNamesAsync(TScope scope!!,
ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken) ImmutableDictionary<CultureInfo, string> names, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.DisplayNames = names; scope.DisplayNames = names;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetDisplayNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetDisplayNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.DisplayName = name; scope.DisplayName = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetNameAsync(TScope scope, string? name, CancellationToken cancellationToken) public virtual ValueTask SetNameAsync(TScope scope!!, string? name, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
scope.Name = name; scope.Name = name;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TScope scope, public virtual ValueTask SetPropertiesAsync(TScope scope!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (scope is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(scope));
}
if (properties is null || properties.IsEmpty)
{ {
scope.Properties = null; scope.Properties = null;
@ -474,13 +350,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetResourcesAsync(TScope scope, ImmutableArray<string> resources, CancellationToken cancellationToken) public virtual ValueTask SetResourcesAsync(TScope scope!!, ImmutableArray<string> resources, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
if (resources.IsDefaultOrEmpty) if (resources.IsDefaultOrEmpty)
{ {
scope.Resources = ImmutableList.Create<string>(); scope.Resources = ImmutableList.Create<string>();
@ -494,13 +365,8 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TScope scope, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TScope scope!!, CancellationToken cancellationToken)
{ {
if (scope is null)
{
throw new ArgumentNullException(nameof(scope));
}
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it
// to the scope before persisting the changes. // to the scope before persisting the changes.
var timestamp = scope.ConcurrencyToken; var timestamp = scope.ConcurrencyToken;

276
src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbTokenStore.cs

@ -22,8 +22,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
where TToken : OpenIddictMongoDbToken where TToken : OpenIddictMongoDbToken
{ {
public OpenIddictMongoDbTokenStore( public OpenIddictMongoDbTokenStore(
IOpenIddictMongoDbContext context, IOpenIddictMongoDbContext context!!,
IOptionsMonitor<OpenIddictMongoDbOptions> options) IOptionsMonitor<OpenIddictMongoDbOptions> options!!)
{ {
Context = context; Context = context;
Options = options; Options = options;
@ -50,13 +50,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<long> CountAsync<TResult>( public virtual async ValueTask<long> CountAsync<TResult>(
Func<IQueryable<TToken>, IQueryable<TResult>> query, CancellationToken cancellationToken) Func<IQueryable<TToken>, IQueryable<TResult>> query!!, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName); var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName);
@ -64,13 +59,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask CreateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask CreateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName); var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName);
@ -78,13 +68,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask DeleteAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask DeleteAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName); var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName);
@ -303,31 +288,21 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetApplicationIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetApplicationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.ApplicationId == ObjectId.Empty) if (token.ApplicationId == ObjectId.Empty)
{ {
return new ValueTask<string?>(result: null); return new(result: null);
} }
return new ValueTask<string?>(token.ApplicationId.ToString()); return new(token.ApplicationId.ToString());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask<TResult?> GetAsync<TState, TResult>( public virtual async ValueTask<TResult?> GetAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
var database = await Context.GetDatabaseAsync(cancellationToken); var database = await Context.GetDatabaseAsync(cancellationToken);
var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName); var collection = database.GetCollection<TToken>(Options.CurrentValue.TokensCollectionName);
@ -335,86 +310,38 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetAuthorizationIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetAuthorizationIdAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.AuthorizationId == ObjectId.Empty) if (token.AuthorizationId == ObjectId.Empty)
{ {
return new ValueTask<string?>(result: null); return new(result: null);
} }
return new ValueTask<string?>(token.AuthorizationId.ToString()); return new(token.AuthorizationId.ToString());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetCreationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.CreationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.CreationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.CreationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetExpirationDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ExpirationDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.ExpirationDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.ExpirationDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Id.ToString());
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Id.ToString());
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetPayloadAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetPayloadAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Payload);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Payload);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<ImmutableDictionary<string, JsonElement>> GetPropertiesAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.Properties is null) if (token.Properties is null)
{ {
return new ValueTask<ImmutableDictionary<string, JsonElement>>(ImmutableDictionary.Create<string, JsonElement>()); return new(ImmutableDictionary.Create<string, JsonElement>());
} }
using var document = JsonDocument.Parse(token.Properties.ToJson()); using var document = JsonDocument.Parse(token.Properties.ToJson());
@ -425,80 +352,40 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
builder[property.Name] = property.Value.Clone(); builder[property.Name] = property.Value.Clone();
} }
return new ValueTask<ImmutableDictionary<string, JsonElement>>(builder.ToImmutable()); return new(builder.ToImmutable());
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<DateTimeOffset?> GetRedemptionDateAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.RedemptionDate is DateTime date ? DateTime.SpecifyKind(date, DateTimeKind.Utc) : null);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (token.RedemptionDate is null)
{
return new ValueTask<DateTimeOffset?>(result: null);
}
return new ValueTask<DateTimeOffset?>(DateTime.SpecifyKind(token.RedemptionDate.Value, DateTimeKind.Utc));
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetReferenceIdAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetReferenceIdAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.ReferenceId);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.ReferenceId);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetStatusAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetStatusAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Status);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Status);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetSubjectAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetSubjectAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Subject);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Subject);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<string?> GetTypeAsync(TToken token, CancellationToken cancellationToken) public virtual ValueTask<string?> GetTypeAsync(TToken token!!, CancellationToken cancellationToken)
{ => new(token.Type);
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
return new ValueTask<string?>(token.Type);
}
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken) public virtual ValueTask<TToken> InstantiateAsync(CancellationToken cancellationToken)
{ {
try try
{ {
return new ValueTask<TToken>(Activator.CreateInstance<TToken>()); return new(Activator.CreateInstance<TToken>());
} }
catch (MemberAccessException exception) catch (MemberAccessException exception)
{ {
return new ValueTask<TToken>(Task.FromException<TToken>( return new(Task.FromException<TToken>(
new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception))); new InvalidOperationException(SR.GetResourceString(SR.ID0248), exception)));
} }
} }
@ -530,14 +417,9 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
/// <inheritdoc/> /// <inheritdoc/>
public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>( public virtual IAsyncEnumerable<TResult> ListAsync<TState, TResult>(
Func<IQueryable<TToken>, TState, IQueryable<TResult>> query, Func<IQueryable<TToken>, TState, IQueryable<TResult>> query!!,
TState state, CancellationToken cancellationToken) TState state, CancellationToken cancellationToken)
{ {
if (query is null)
{
throw new ArgumentNullException(nameof(query));
}
return ExecuteAsync(cancellationToken); return ExecuteAsync(cancellationToken);
async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken) async IAsyncEnumerable<TResult> ExecuteAsync([EnumeratorCancellation] CancellationToken cancellationToken)
@ -604,13 +486,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetApplicationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetApplicationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
token.ApplicationId = ObjectId.Parse(identifier); token.ApplicationId = ObjectId.Parse(identifier);
@ -625,13 +502,8 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetAuthorizationIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetAuthorizationIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
token.AuthorizationId = ObjectId.Parse(identifier); token.AuthorizationId = ObjectId.Parse(identifier);
@ -646,54 +518,34 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetCreationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetCreationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.CreationDate = date?.UtcDateTime; token.CreationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetExpirationDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetExpirationDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ExpirationDate = date?.UtcDateTime; token.ExpirationDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPayloadAsync(TToken token, string? payload, CancellationToken cancellationToken) public virtual ValueTask SetPayloadAsync(TToken token!!, string? payload, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Payload = payload; token.Payload = payload;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetPropertiesAsync(TToken token, public virtual ValueTask SetPropertiesAsync(TToken token!!,
ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken) ImmutableDictionary<string, JsonElement> properties, CancellationToken cancellationToken)
{ {
if (token is null) if (properties is not { IsEmpty: false })
{
throw new ArgumentNullException(nameof(token));
}
if (properties is null || properties.IsEmpty)
{ {
token.Properties = null; token.Properties = null;
@ -724,78 +576,48 @@ public class OpenIddictMongoDbTokenStore<TToken> : IOpenIddictTokenStore<TToken>
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetRedemptionDateAsync(TToken token, DateTimeOffset? date, CancellationToken cancellationToken) public virtual ValueTask SetRedemptionDateAsync(TToken token!!, DateTimeOffset? date, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.RedemptionDate = date?.UtcDateTime; token.RedemptionDate = date?.UtcDateTime;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetReferenceIdAsync(TToken token, string? identifier, CancellationToken cancellationToken) public virtual ValueTask SetReferenceIdAsync(TToken token!!, string? identifier, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.ReferenceId = identifier; token.ReferenceId = identifier;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetStatusAsync(TToken token, string? status, CancellationToken cancellationToken) public virtual ValueTask SetStatusAsync(TToken token!!, string? status, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Status = status; token.Status = status;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetSubjectAsync(TToken token, string? subject, CancellationToken cancellationToken) public virtual ValueTask SetSubjectAsync(TToken token!!, string? subject, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Subject = subject; token.Subject = subject;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual ValueTask SetTypeAsync(TToken token, string? type, CancellationToken cancellationToken) public virtual ValueTask SetTypeAsync(TToken token!!, string? type, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
token.Type = type; token.Type = type;
return default; return default;
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async ValueTask UpdateAsync(TToken token, CancellationToken cancellationToken) public virtual async ValueTask UpdateAsync(TToken token!!, CancellationToken cancellationToken)
{ {
if (token is null)
{
throw new ArgumentNullException(nameof(token));
}
// Generate a new concurrency token and attach it // Generate a new concurrency token and attach it
// to the token before persisting the changes. // to the token before persisting the changes.
var timestamp = token.ConcurrencyToken; var timestamp = token.ConcurrencyToken;

11
src/OpenIddict.Quartz/OpenIddictQuartzBuilder.cs

@ -18,8 +18,8 @@ public class OpenIddictQuartzBuilder
/// Initializes a new instance of <see cref="OpenIddictQuartzBuilder"/>. /// Initializes a new instance of <see cref="OpenIddictQuartzBuilder"/>.
/// </summary> /// </summary>
/// <param name="services">The services collection.</param> /// <param name="services">The services collection.</param>
public OpenIddictQuartzBuilder(IServiceCollection services) public OpenIddictQuartzBuilder(IServiceCollection services!!)
=> Services = services ?? throw new ArgumentNullException(nameof(services)); => Services = services;
/// <summary> /// <summary>
/// Gets the services collection. /// Gets the services collection.
@ -33,13 +33,8 @@ public class OpenIddictQuartzBuilder
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param> /// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictQuartzBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictQuartzBuilder"/>.</returns>
public OpenIddictQuartzBuilder Configure(Action<OpenIddictQuartzOptions> configuration) public OpenIddictQuartzBuilder Configure(Action<OpenIddictQuartzOptions> configuration!!)
{ {
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration); Services.Configure(configuration);
return this; return this;

7
src/OpenIddict.Quartz/OpenIddictQuartzConfiguration.cs

@ -14,13 +14,8 @@ namespace OpenIddict.Quartz;
public class OpenIddictQuartzConfiguration : IConfigureOptions<QuartzOptions> public class OpenIddictQuartzConfiguration : IConfigureOptions<QuartzOptions>
{ {
/// <inheritdoc/> /// <inheritdoc/>
public void Configure(QuartzOptions options) public void Configure(QuartzOptions options!!)
{ {
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
options.AddJob<OpenIddictQuartzJob>(builder => options.AddJob<OpenIddictQuartzJob>(builder =>
{ {
builder.StoreDurably() builder.StoreDurably()

19
src/OpenIddict.Quartz/OpenIddictQuartzExtensions.cs

@ -21,13 +21,8 @@ public static class OpenIddictQuartzExtensions
/// <param name="builder">The services builder used by OpenIddict to register new services.</param> /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictQuartzBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictQuartzBuilder"/>.</returns>
public static OpenIddictQuartzBuilder UseQuartz(this OpenIddictCoreBuilder builder) public static OpenIddictQuartzBuilder UseQuartz(this OpenIddictCoreBuilder builder!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddQuartz(); builder.Services.AddQuartz();
// The OpenIddict job is registered as a service to allow // The OpenIddict job is registered as a service to allow
@ -49,18 +44,8 @@ public static class OpenIddictQuartzExtensions
/// <remarks>This extension can be safely called multiple times.</remarks> /// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public static OpenIddictCoreBuilder UseQuartz( public static OpenIddictCoreBuilder UseQuartz(
this OpenIddictCoreBuilder builder, Action<OpenIddictQuartzBuilder> configuration) this OpenIddictCoreBuilder builder!!, Action<OpenIddictQuartzBuilder> configuration!!)
{ {
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
if (configuration is null)
{
throw new ArgumentNullException(nameof(configuration));
}
configuration(builder.UseQuartz()); configuration(builder.UseQuartz());
return builder; return builder;

9
src/OpenIddict.Quartz/OpenIddictQuartzJob.cs

@ -28,7 +28,7 @@ public class OpenIddictQuartzJob : IJob
/// </summary> /// </summary>
/// <param name="options">The OpenIddict Quartz.NET options.</param> /// <param name="options">The OpenIddict Quartz.NET options.</param>
/// <param name="provider">The service provider.</param> /// <param name="provider">The service provider.</param>
public OpenIddictQuartzJob(IOptionsMonitor<OpenIddictQuartzOptions> options, IServiceProvider provider) public OpenIddictQuartzJob(IOptionsMonitor<OpenIddictQuartzOptions> options!!, IServiceProvider provider!!)
{ {
_options = options; _options = options;
_provider = provider; _provider = provider;
@ -42,13 +42,8 @@ public class OpenIddictQuartzJob : IJob
group: typeof(OpenIddictQuartzJob).Assembly.GetName().Name!); group: typeof(OpenIddictQuartzJob).Assembly.GetName().Name!);
/// <inheritdoc/> /// <inheritdoc/>
public async Task Execute(IJobExecutionContext context) public async Task Execute(IJobExecutionContext context!!)
{ {
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
List<Exception>? exceptions = null; List<Exception>? exceptions = null;
// Note: this job is registered as a transient service. As such, it cannot directly depend on scoped services // Note: this job is registered as a transient service. As such, it cannot directly depend on scoped services

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save