Browse Source

Fix incorrect error messages in the client stack and use ?? for null checks where appropriate

pull/1413/head
Kévin Chalet 4 years ago
parent
commit
255fc64caf
  1. 8
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 2
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
  3. 10
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  4. 60
      src/OpenIddict.Client/OpenIddictClientBuilder.cs
  5. 2
      src/OpenIddict.Client/OpenIddictClientConfiguration.cs
  6. 15
      src/OpenIddict.Client/OpenIddictClientDispatcher.cs
  7. 20
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  8. 14
      src/OpenIddict.Client/OpenIddictClientService.cs
  9. 18
      src/OpenIddict.Core/Caches/OpenIddictApplicationCache.cs
  10. 18
      src/OpenIddict.Core/Caches/OpenIddictAuthorizationCache.cs
  11. 18
      src/OpenIddict.Core/Caches/OpenIddictScopeCache.cs
  12. 18
      src/OpenIddict.Core/Caches/OpenIddictTokenCache.cs
  13. 5
      src/OpenIddict.Core/Managers/OpenIddictApplicationManager.cs
  14. 5
      src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs
  15. 5
      src/OpenIddict.Core/Managers/OpenIddictScopeManager.cs
  16. 5
      src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs
  17. 40
      src/OpenIddict.Core/OpenIddictCoreBuilder.cs
  18. 40
      src/OpenIddict.Core/OpenIddictCoreExtensions.cs
  19. 10
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkApplicationStoreResolver.cs
  20. 10
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkAuthorizationStoreResolver.cs
  21. 10
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkScopeStoreResolver.cs
  22. 10
      src/OpenIddict.EntityFramework/Resolvers/OpenIddictEntityFrameworkTokenStoreResolver.cs
  23. 4
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkApplicationStore.cs
  24. 10
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkAuthorizationStore.cs
  25. 6
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkScopeStore.cs
  26. 16
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs
  27. 10
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreApplicationStoreResolver.cs
  28. 10
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreAuthorizationStoreResolver.cs
  29. 10
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreScopeStoreResolver.cs
  30. 10
      src/OpenIddict.EntityFrameworkCore/Resolvers/OpenIddictEntityFrameworkCoreTokenStoreResolver.cs
  31. 4
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreApplicationStore.cs
  32. 15
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreAuthorizationStore.cs
  33. 6
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreScopeStore.cs
  34. 26
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreTokenStore.cs
  35. 2
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbApplicationStore.cs
  36. 2
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbAuthorizationStore.cs
  37. 2
      src/OpenIddict.MongoDb/Stores/OpenIddictMongoDbScopeStore.cs
  38. 2
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
  39. 5
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs
  40. 5
      src/OpenIddict.Server.Owin/OpenIddictServerOwinMiddlewareFactory.cs
  41. 59
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  42. 15
      src/OpenIddict.Server/OpenIddictServerDispatcher.cs
  43. 35
      src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs
  44. 25
      src/OpenIddict.Server/OpenIddictServerHandlers.Device.cs
  45. 2
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  46. 30
      src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
  47. 20
      src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs
  48. 20
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  49. 15
      src/OpenIddict.Server/OpenIddictServerHandlers.Revocation.cs
  50. 22
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  51. 5
      src/OpenIddict.Validation.Owin/OpenIddictValidationOwinMiddlewareFactory.cs
  52. 10
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs
  53. 29
      src/OpenIddict.Validation/OpenIddictValidationBuilder.cs
  54. 15
      src/OpenIddict.Validation/OpenIddictValidationDispatcher.cs
  55. 5
      src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs
  56. 21
      src/OpenIddict.Validation/OpenIddictValidationService.cs
  57. 2
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs

8
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -1197,6 +1197,14 @@ To apply redirection responses, create a class implementing 'IOpenIddictClientHa
<data name="ID0311" xml:space="preserve"> <data name="ID0311" xml:space="preserve">
<value>A refresh token must be specified when using the refresh token grant.</value> <value>A refresh token must be specified when using the refresh token grant.</value>
</data> </data>
<data name="ID0312" xml:space="preserve">
<value>The event handler of type '{0}' couldn't be resolved.
This may indicate that it was not properly registered in the dependency injection container. To register an event handler, use 'services.AddOpenIddict().AddClient().AddEventHandler()'.</value>
</data>
<data name="ID0313" xml:space="preserve">
<value>A discovery client must be registered when using server discovery.
Reference the 'OpenIddict.Client.SystemNetHttp' package and call 'services.AddOpenIddict().AddClient().UseSystemNetHttp()' to register the default System.Net.Http-based integration.</value>
</data>
<data name="ID2000" xml:space="preserve"> <data name="ID2000" xml:space="preserve">
<value>The security token is missing.</value> <value>The security token is missing.</value>
</data> </data>

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

@ -698,7 +698,7 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// If it was not registered or enabled, let the default OpenIddict client handlers render // If it was not registered or enabled, let the default OpenIddict client handlers render
// a default error page instead of delegating the rendering to the status code middleware. // a default error page instead of delegating the rendering to the status code middleware.
var feature = response.HttpContext.Features.Get<IStatusCodePagesFeature>(); var feature = response.HttpContext.Features.Get<IStatusCodePagesFeature>();
if (feature is null || !feature.Enabled) if (feature is not { Enabled: true })
{ {
return default; return default;
} }

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

@ -222,21 +222,15 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
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!) ??
if (client is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0174)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0174));
}
#if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION #if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION
// If supported, import the HTTP version from the client instance. // If supported, import the HTTP version from the client instance.
request.Version = client.DefaultRequestVersion; request.Version = client.DefaultRequestVersion;
#endif #endif
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead); var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead) ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0175)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0175));
}
// Store the HttpResponseMessage in the transaction properties. // Store the HttpResponseMessage in the transaction properties.
context.Transaction.SetProperty(typeof(HttpResponseMessage).FullName!, response); context.Transaction.SetProperty(typeof(HttpResponseMessage).FullName!, response);

60
src/OpenIddict.Client/OpenIddictClientBuilder.cs

@ -372,11 +372,8 @@ public class OpenIddictClientBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
} }
using var stream = assembly.GetManifestResourceStream(resource); using var stream = assembly.GetManifestResourceStream(resource) ??
if (stream is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
}
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -429,13 +426,10 @@ public class OpenIddictClientBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint));
} }
var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); return AddEncryptionCertificate(
if (certificate is null) GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
{ GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
return AddEncryptionCertificate(certificate);
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -465,16 +459,10 @@ public class OpenIddictClientBuilder
using var store = new X509Store(name, location); using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly); store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) return AddEncryptionCertificate(
.OfType<X509Certificate2>() store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.SingleOrDefault(); .OfType<X509Certificate2>()
.SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
if (certificate is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066));
}
return AddEncryptionCertificate(certificate);
} }
/// <summary> /// <summary>
@ -780,11 +768,8 @@ public class OpenIddictClientBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
} }
using var stream = assembly.GetManifestResourceStream(resource); using var stream = assembly.GetManifestResourceStream(resource) ??
if (stream is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
}
return AddSigningCertificate(stream, password, flags); return AddSigningCertificate(stream, password, flags);
} }
@ -837,13 +822,10 @@ public class OpenIddictClientBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint));
} }
var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); return AddSigningCertificate(
if (certificate is null) GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
{ GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
return AddSigningCertificate(certificate);
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -873,16 +855,10 @@ public class OpenIddictClientBuilder
using var store = new X509Store(name, location); using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly); store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) return AddSigningCertificate(
.OfType<X509Certificate2>() store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.SingleOrDefault(); .OfType<X509Certificate2>()
.SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
if (certificate is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066));
}
return AddSigningCertificate(certificate);
} }
/// <summary> /// <summary>

2
src/OpenIddict.Client/OpenIddictClientConfiguration.cs

@ -49,7 +49,7 @@ public class OpenIddictClientConfiguration : IPostConfigureOptions<OpenIddictCli
if (!options.Handlers.Any(descriptor => descriptor.ContextType == typeof(ApplyConfigurationRequestContext)) || if (!options.Handlers.Any(descriptor => descriptor.ContextType == typeof(ApplyConfigurationRequestContext)) ||
!options.Handlers.Any(descriptor => descriptor.ContextType == typeof(ApplyCryptographyRequestContext))) !options.Handlers.Any(descriptor => descriptor.ContextType == typeof(ApplyCryptographyRequestContext)))
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0135)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0313));
} }
if (registration.MetadataAddress is null) if (registration.MetadataAddress is null)

15
src/OpenIddict.Client/OpenIddictClientDispatcher.cs

@ -93,16 +93,15 @@ public class OpenIddictClientDispatcher : IOpenIddictClientDispatcher
continue; continue;
} }
var handler = descriptor.ServiceDescriptor.ImplementationInstance is not null ? yield return descriptor.ServiceDescriptor switch
descriptor.ServiceDescriptor.ImplementationInstance as IOpenIddictClientHandler<TContext> :
_provider.GetService(descriptor.ServiceDescriptor.ServiceType) as IOpenIddictClientHandler<TContext>;
if (handler is null)
{ {
throw new InvalidOperationException(SR.FormatID0138(descriptor.ServiceDescriptor.ServiceType)); { ImplementationInstance: IOpenIddictClientHandler<TContext> handler } => handler,
}
_ when _provider.GetService(descriptor.ServiceDescriptor.ServiceType)
is IOpenIddictClientHandler<TContext> handler => handler,
yield return handler; _ => throw new InvalidOperationException(SR.FormatID0312(descriptor.ServiceDescriptor.ServiceType))
};
} }
} }

20
src/OpenIddict.Client/OpenIddictClientHandlers.cs

@ -362,11 +362,8 @@ public static partial class OpenIddictClientHandlers
// 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
// be used to authenticate users. In this case, throw an exception to abort the flow. // be used to authenticate users. In this case, throw an exception to abort the flow.
var registration = context.Options.Registrations.Find(registration => registration.Issuer == issuer); var registration = context.Options.Registrations.Find(registration => registration.Issuer == issuer) ??
if (registration is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0292)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0292));
}
context.Issuer = issuer; context.Issuer = issuer;
context.Registration = registration; context.Registration = registration;
@ -1096,11 +1093,7 @@ public static partial class OpenIddictClientHandlers
// Resolve the hash algorithm corresponding to the signing algorithm. If an // Resolve the hash algorithm corresponding to the signing algorithm. If an
// instance of the BCL hash algorithm cannot be resolved, throw an exception. // instance of the BCL hash algorithm cannot be resolved, throw an exception.
var algorithm = GetHashAlgorithm(name); var algorithm = GetHashAlgorithm(name) ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0293));
if (algorithm is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0293));
}
// If a frontchannel access token was returned in the authorization response, // If a frontchannel access token was returned in the authorization response,
// ensure the at_hash claim matches the hash of the actual access token. // ensure the at_hash claim matches the hash of the actual access token.
@ -1988,11 +1981,7 @@ public static partial class OpenIddictClientHandlers
// Resolve the hash algorithm corresponding to the signing algorithm. If an // Resolve the hash algorithm corresponding to the signing algorithm. If an
// instance of the BCL hash algorithm cannot be resolved, throw an exception. // instance of the BCL hash algorithm cannot be resolved, throw an exception.
var algorithm = GetHashAlgorithm(name); var algorithm = GetHashAlgorithm(name) ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0295));
if (algorithm is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0295));
}
var hash = context.BackchannelIdentityTokenPrincipal.GetClaim(Claims.AccessTokenHash); var hash = context.BackchannelIdentityTokenPrincipal.GetClaim(Claims.AccessTokenHash);
if (string.IsNullOrEmpty(hash)) if (string.IsNullOrEmpty(hash))
@ -2404,7 +2393,8 @@ public static partial class OpenIddictClientHandlers
/// <inheritdoc/> /// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context!!) public async ValueTask HandleAsync(ProcessAuthenticationContext context!!)
{ {
if (context.UserinfoTokenPrincipal is not null || string.IsNullOrEmpty(context.UserinfoToken)) if (context.UserinfoTokenPrincipal is not null ||
string.IsNullOrEmpty(context.UserinfoToken))
{ {
return; return;
} }

14
src/OpenIddict.Client/OpenIddictClientService.cs

@ -55,13 +55,8 @@ public class OpenIddictClientService
request = await ApplyConfigurationRequestAsync(); request = await ApplyConfigurationRequestAsync();
var response = await ExtractConfigurationResponseAsync(); var response = await ExtractConfigurationResponseAsync();
var configuration = await HandleConfigurationResponseAsync(); return await HandleConfigurationResponseAsync() ??
if (configuration is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
}
return configuration;
async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync() async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync()
{ {
@ -195,13 +190,8 @@ public class OpenIddictClientService
var response = await ExtractCryptographyResponseAsync(); var response = await ExtractCryptographyResponseAsync();
var keys = await HandleCryptographyResponseAsync(); return await HandleCryptographyResponseAsync() ??
if (keys is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
}
return keys;
async ValueTask<OpenIddictRequest> PrepareCryptographyRequestAsync() async ValueTask<OpenIddictRequest> PrepareCryptographyRequestAsync()
{ {

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

@ -272,13 +272,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
if (application is not null) if (application is not null)
{ {
var signal = await CreateExpirationSignalAsync(application, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(1L); entry.SetSize(1L);
@ -299,13 +294,8 @@ public class OpenIddictApplicationCache<TApplication> : IOpenIddictApplicationCa
foreach (var application in applications) foreach (var application in applications)
{ {
var signal = await CreateExpirationSignalAsync(application, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(applications.Length); entry.SetSize(applications.Length);

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

@ -448,13 +448,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
if (authorization is not null) if (authorization is not null)
{ {
var signal = await CreateExpirationSignalAsync(authorization, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(1L); entry.SetSize(1L);
@ -475,13 +470,8 @@ public class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAuthoriza
foreach (var authorization in authorizations) foreach (var authorization in authorizations)
{ {
var signal = await CreateExpirationSignalAsync(authorization, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(authorizations.Length); entry.SetSize(authorizations.Length);

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

@ -245,13 +245,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
if (scope is not null) if (scope is not null)
{ {
var signal = await CreateExpirationSignalAsync(scope, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(scope, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(1L); entry.SetSize(1L);
@ -272,13 +267,8 @@ public class OpenIddictScopeCache<TScope> : IOpenIddictScopeCache<TScope>, IDisp
foreach (var scope in scopes) foreach (var scope in scopes)
{ {
var signal = await CreateExpirationSignalAsync(scope, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(scope, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(scopes.Length); entry.SetSize(scopes.Length);

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

@ -500,13 +500,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
if (token is not null) if (token is not null)
{ {
var signal = await CreateExpirationSignalAsync(token, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(token, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(1L); entry.SetSize(1L);
@ -527,13 +522,8 @@ public class OpenIddictTokenCache<TToken> : IOpenIddictTokenCache<TToken>, IDisp
foreach (var token in tokens) foreach (var token in tokens)
{ {
var signal = await CreateExpirationSignalAsync(token, cancellationToken); entry.AddExpirationToken(await CreateExpirationSignalAsync(token, cancellationToken) ??
if (signal is null) throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197));
}
entry.AddExpirationToken(signal);
} }
entry.SetSize(tokens.Length); entry.SetSize(tokens.Length);

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

@ -191,11 +191,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
public virtual async ValueTask<TApplication> CreateAsync( public virtual async ValueTask<TApplication> CreateAsync(
OpenIddictApplicationDescriptor descriptor!!, CancellationToken cancellationToken = default) OpenIddictApplicationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
var application = await Store.InstantiateAsync(cancellationToken); var application = await Store.InstantiateAsync(cancellationToken) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
}
await PopulateAsync(application, descriptor, cancellationToken); await PopulateAsync(application, descriptor, cancellationToken);

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

@ -147,11 +147,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
public virtual async ValueTask<TAuthorization> CreateAsync( public virtual async ValueTask<TAuthorization> CreateAsync(
OpenIddictAuthorizationDescriptor descriptor!!, CancellationToken cancellationToken = default) OpenIddictAuthorizationDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
var authorization = await Store.InstantiateAsync(cancellationToken); var authorization = await Store.InstantiateAsync(cancellationToken) ??
if (authorization is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0220)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0220));
}
await PopulateAsync(authorization, descriptor, cancellationToken); await PopulateAsync(authorization, descriptor, cancellationToken);
await CreateAsync(authorization, cancellationToken); await CreateAsync(authorization, cancellationToken);

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

@ -140,11 +140,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
public virtual async ValueTask<TScope> CreateAsync( public virtual async ValueTask<TScope> CreateAsync(
OpenIddictScopeDescriptor descriptor!!, CancellationToken cancellationToken = default) OpenIddictScopeDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
var scope = await Store.InstantiateAsync(cancellationToken); var scope = await Store.InstantiateAsync(cancellationToken) ??
if (scope is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0223)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0223));
}
await PopulateAsync(scope, descriptor, cancellationToken); await PopulateAsync(scope, descriptor, cancellationToken);
await CreateAsync(scope, cancellationToken); await CreateAsync(scope, cancellationToken);

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

@ -155,11 +155,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
public virtual async ValueTask<TToken> CreateAsync( public virtual async ValueTask<TToken> CreateAsync(
OpenIddictTokenDescriptor descriptor!!, CancellationToken cancellationToken = default) OpenIddictTokenDescriptor descriptor!!, CancellationToken cancellationToken = default)
{ {
var token = await Store.InstantiateAsync(cancellationToken); var token = await Store.InstantiateAsync(cancellationToken) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0226)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0226));
}
await PopulateAsync(token, descriptor, cancellationToken); await PopulateAsync(token, descriptor, cancellationToken);
await CreateAsync(token, cancellationToken); await CreateAsync(token, cancellationToken);

40
src/OpenIddict.Core/OpenIddictCoreBuilder.cs

@ -66,11 +66,8 @@ public class OpenIddictCoreBuilder
/// <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)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictApplicationStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictApplicationStore<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictApplicationStore<>) // Note: managers can be either open generics (e.g OpenIddictApplicationStore<>)
// or closed generics (e.g OpenIddictApplicationStore<OpenIddictApplication>). // or closed generics (e.g OpenIddictApplicationStore<OpenIddictApplication>).
@ -117,11 +114,8 @@ public class OpenIddictCoreBuilder
/// <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)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictAuthorizationStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictAuthorizationStore<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictAuthorizationStore<>) // Note: managers can be either open generics (e.g OpenIddictAuthorizationStore<>)
// or closed generics (e.g OpenIddictAuthorizationStore<OpenIddictAuthorization>). // or closed generics (e.g OpenIddictAuthorizationStore<OpenIddictAuthorization>).
@ -168,11 +162,8 @@ public class OpenIddictCoreBuilder
/// <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)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictScopeStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictScopeStore<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictScopeStore<>) // Note: managers can be either open generics (e.g OpenIddictScopeStore<>)
// or closed generics (e.g OpenIddictScopeStore<OpenIddictScope>). // or closed generics (e.g OpenIddictScopeStore<OpenIddictScope>).
@ -219,11 +210,8 @@ public class OpenIddictCoreBuilder
/// <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)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictTokenStore<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(IOpenIddictTokenStore<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictTokenStore<>) // Note: managers can be either open generics (e.g OpenIddictTokenStore<>)
// or closed generics (e.g OpenIddictTokenStore<OpenIddictToken>). // or closed generics (e.g OpenIddictTokenStore<OpenIddictToken>).
@ -268,11 +256,8 @@ public class OpenIddictCoreBuilder
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceApplicationManager(Type type!!) public OpenIddictCoreBuilder ReplaceApplicationManager(Type type!!)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictApplicationManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictApplicationManager<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictApplicationManager<>) // Note: managers can be either open generics (e.g OpenIddictApplicationManager<>)
// or closed generics (e.g OpenIddictApplicationManager<OpenIddictApplication>). // or closed generics (e.g OpenIddictApplicationManager<OpenIddictApplication>).
@ -352,11 +337,8 @@ public class OpenIddictCoreBuilder
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceAuthorizationManager(Type type!!) public OpenIddictCoreBuilder ReplaceAuthorizationManager(Type type!!)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictAuthorizationManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictAuthorizationManager<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictAuthorizationManager<>) // Note: managers can be either open generics (e.g OpenIddictAuthorizationManager<>)
// or closed generics (e.g OpenIddictAuthorizationManager<OpenIddictAuthorization>). // or closed generics (e.g OpenIddictAuthorizationManager<OpenIddictAuthorization>).
@ -436,11 +418,8 @@ public class OpenIddictCoreBuilder
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceScopeManager(Type type!!) public OpenIddictCoreBuilder ReplaceScopeManager(Type type!!)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictScopeManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictScopeManager<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictScopeManager<>) // Note: managers can be either open generics (e.g OpenIddictScopeManager<>)
// or closed generics (e.g OpenIddictScopeManager<OpenIddictScope>). // or closed generics (e.g OpenIddictScopeManager<OpenIddictScope>).
@ -520,11 +499,8 @@ public class OpenIddictCoreBuilder
/// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns> /// <returns>The <see cref="OpenIddictCoreBuilder"/>.</returns>
public OpenIddictCoreBuilder ReplaceTokenManager(Type type!!) public OpenIddictCoreBuilder ReplaceTokenManager(Type type!!)
{ {
var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictTokenManager<>)); var root = OpenIddictHelpers.FindGenericBaseType(type, typeof(OpenIddictTokenManager<>)) ??
if (root is null)
{
throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type)); throw new ArgumentException(SR.GetResourceString(SR.ID0232), nameof(type));
}
// Note: managers can be either open generics (e.g OpenIddictTokenManager<>) // Note: managers can be either open generics (e.g OpenIddictTokenManager<>)
// or closed generics (e.g OpenIddictTokenManager<OpenIddictToken>). // or closed generics (e.g OpenIddictTokenManager<OpenIddictToken>).

40
src/OpenIddict.Core/OpenIddictCoreExtensions.cs

@ -43,52 +43,44 @@ public static class OpenIddictCoreExtensions
builder.Services.TryAddScoped<IOpenIddictScopeStoreResolver, OpenIddictScopeStoreResolver>(); builder.Services.TryAddScoped<IOpenIddictScopeStoreResolver, OpenIddictScopeStoreResolver>();
builder.Services.TryAddScoped<IOpenIddictTokenStoreResolver, OpenIddictTokenStoreResolver>(); builder.Services.TryAddScoped<IOpenIddictTokenStoreResolver, OpenIddictTokenStoreResolver>();
builder.Services.TryAddScoped(provider => builder.Services.TryAddScoped(static provider =>
{ {
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>().CurrentValue; var type = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>()
if (options.DefaultApplicationType is null) .CurrentValue?.DefaultApplicationType ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0273)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0273));
}
return (IOpenIddictApplicationManager) provider.GetRequiredService( return (IOpenIddictApplicationManager) provider.GetRequiredService(
typeof(OpenIddictApplicationManager<>).MakeGenericType(options.DefaultApplicationType)); typeof(OpenIddictApplicationManager<>).MakeGenericType(type));
}); });
builder.Services.TryAddScoped(provider => builder.Services.TryAddScoped(static provider =>
{ {
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>().CurrentValue; var type = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>()
if (options.DefaultAuthorizationType is null) .CurrentValue?.DefaultAuthorizationType ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0274)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0274));
}
return (IOpenIddictAuthorizationManager) provider.GetRequiredService( return (IOpenIddictAuthorizationManager) provider.GetRequiredService(
typeof(OpenIddictAuthorizationManager<>).MakeGenericType(options.DefaultAuthorizationType)); typeof(OpenIddictAuthorizationManager<>).MakeGenericType(type));
}); });
builder.Services.TryAddScoped(provider => builder.Services.TryAddScoped(static provider =>
{ {
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>().CurrentValue; var type = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>()
if (options.DefaultScopeType is null) .CurrentValue?.DefaultScopeType ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0275)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0275));
}
return (IOpenIddictScopeManager) provider.GetRequiredService( return (IOpenIddictScopeManager) provider.GetRequiredService(
typeof(OpenIddictScopeManager<>).MakeGenericType(options.DefaultScopeType)); typeof(OpenIddictScopeManager<>).MakeGenericType(type));
}); });
builder.Services.TryAddScoped(provider => builder.Services.TryAddScoped(static provider =>
{ {
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>().CurrentValue; var type = provider.GetRequiredService<IOptionsMonitor<OpenIddictCoreOptions>>()
if (options.DefaultTokenType is null) .CurrentValue?.DefaultTokenType ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0276)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0276));
}
return (IOpenIddictTokenManager) provider.GetRequiredService( return (IOpenIddictTokenManager) provider.GetRequiredService(
typeof(OpenIddictTokenManager<>).MakeGenericType(options.DefaultTokenType)); typeof(OpenIddictTokenManager<>).MakeGenericType(type));
}); });
return new OpenIddictCoreBuilder(builder.Services); return new OpenIddictCoreBuilder(builder.Services);

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkApplicationStoreResolver : IOpenIddictAppl
var type = _cache.GetOrAdd(typeof(TApplication), key => var type = _cache.GetOrAdd(typeof(TApplication), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkApplication<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkApplication<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0234)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0234));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0235)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0235));
}
return typeof(OpenIddictEntityFrameworkApplicationStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkApplicationStore<,,,,>).MakeGenericType(
/* TApplication: */ key, /* TApplication: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkAuthorizationStoreResolver : IOpenIddictAu
var type = _cache.GetOrAdd(typeof(TAuthorization), key => var type = _cache.GetOrAdd(typeof(TAuthorization), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkAuthorization<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkAuthorization<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0236)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0236));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0235)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0235));
}
return typeof(OpenIddictEntityFrameworkAuthorizationStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkAuthorizationStore<,,,,>).MakeGenericType(
/* TAuthorization: */ key, /* TAuthorization: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkScopeStoreResolver : IOpenIddictScopeStore
var type = _cache.GetOrAdd(typeof(TScope), key => var type = _cache.GetOrAdd(typeof(TScope), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkScope<>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkScope<>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0237)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0237));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0235)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0235));
}
return typeof(OpenIddictEntityFrameworkScopeStore<,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkScopeStore<,,>).MakeGenericType(
/* TScope: */ key, /* TScope: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkTokenStoreResolver : IOpenIddictTokenStore
var type = _cache.GetOrAdd(typeof(TToken), key => var type = _cache.GetOrAdd(typeof(TToken), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkToken<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkToken<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0238)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0238));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0235)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0235));
}
return typeof(OpenIddictEntityFrameworkTokenStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkTokenStore<,,,,>).MakeGenericType(
/* TToken: */ key, /* TToken: */ key,

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

@ -610,7 +610,7 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
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 (names is null || names.IsEmpty) if (names is not { Count: > 0 })
{ {
application.DisplayNames = null; application.DisplayNames = null;
@ -709,7 +709,7 @@ public class OpenIddictEntityFrameworkApplicationStore<TApplication, TAuthorizat
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
application.Properties = null; application.Properties = null;

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

@ -587,13 +587,9 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
{ {
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); authorization.Application = await Applications.FindAsync(
if (application is null) cancellationToken, ConvertIdentifierFromString(identifier)) ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0244)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0244));
}
authorization.Application = application;
} }
else else
@ -627,7 +623,7 @@ public class OpenIddictEntityFrameworkAuthorizationStore<TAuthorization, TApplic
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
authorization.Properties = null; authorization.Properties = null;

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

@ -402,7 +402,7 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
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 (descriptions is null || descriptions.IsEmpty) if (descriptions is not { Count: > 0 })
{ {
scope.Descriptions = null; scope.Descriptions = null;
@ -444,7 +444,7 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
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 (names is null || names.IsEmpty) if (names is not { Count: > 0 })
{ {
scope.DisplayNames = null; scope.DisplayNames = null;
@ -486,7 +486,7 @@ public class OpenIddictEntityFrameworkScopeStore<TScope, TContext, TKey> : IOpen
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
scope.Properties = null; scope.Properties = null;

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

@ -530,13 +530,9 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
{ {
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var application = await Applications.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); token.Application = await Applications.FindAsync(
if (application is null) cancellationToken, ConvertIdentifierFromString(identifier)) ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0250)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0250));
}
token.Application = application;
} }
else else
@ -562,13 +558,9 @@ public class OpenIddictEntityFrameworkTokenStore<TToken, TApplication, TAuthoriz
{ {
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
var authorization = await Authorizations.FindAsync(cancellationToken, ConvertIdentifierFromString(identifier)); token.Authorization = await Authorizations.FindAsync(
if (authorization is null) cancellationToken, ConvertIdentifierFromString(identifier)) ??
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0251)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0251));
}
token.Authorization = authorization;
} }
else else

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkCoreApplicationStoreResolver : IOpenIddict
var type = _cache.GetOrAdd(typeof(TApplication), key => var type = _cache.GetOrAdd(typeof(TApplication), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreApplication<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreApplication<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0252)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0252));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0253)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0253));
}
return typeof(OpenIddictEntityFrameworkCoreApplicationStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkCoreApplicationStore<,,,,>).MakeGenericType(
/* TApplication: */ key, /* TApplication: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStoreResolver : IOpenIddi
var type = _cache.GetOrAdd(typeof(TAuthorization), key => var type = _cache.GetOrAdd(typeof(TAuthorization), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreAuthorization<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreAuthorization<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0254)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0254));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0253)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0253));
}
return typeof(OpenIddictEntityFrameworkCoreAuthorizationStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkCoreAuthorizationStore<,,,,>).MakeGenericType(
/* TAuthorization: */ key, /* TAuthorization: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkCoreScopeStoreResolver : IOpenIddictScopeS
var type = _cache.GetOrAdd(typeof(TScope), key => var type = _cache.GetOrAdd(typeof(TScope), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreScope<>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreScope<>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0255)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0255));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0253)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0253));
}
return typeof(OpenIddictEntityFrameworkCoreScopeStore<,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkCoreScopeStore<,,>).MakeGenericType(
/* TScope: */ key, /* TScope: */ key,

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

@ -47,17 +47,11 @@ public class OpenIddictEntityFrameworkCoreTokenStoreResolver : IOpenIddictTokenS
var type = _cache.GetOrAdd(typeof(TToken), key => var type = _cache.GetOrAdd(typeof(TToken), key =>
{ {
var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreToken<,,>)); var root = OpenIddictHelpers.FindGenericBaseType(key, typeof(OpenIddictEntityFrameworkCoreToken<,,>)) ??
if (root is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0256)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0256));
}
var context = _options.CurrentValue.DbContextType; var context = _options.CurrentValue.DbContextType ??
if (context is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0253)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0253));
}
return typeof(OpenIddictEntityFrameworkCoreTokenStore<,,,,>).MakeGenericType( return typeof(OpenIddictEntityFrameworkCoreTokenStore<,,,,>).MakeGenericType(
/* TToken: */ key, /* TToken: */ key,

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

@ -649,7 +649,7 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
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 (names is null || names.IsEmpty) if (names is not { Count: > 0 })
{ {
application.DisplayNames = null; application.DisplayNames = null;
@ -748,7 +748,7 @@ public class OpenIddictEntityFrameworkCoreApplicationStore<TApplication, TAuthor
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
application.Properties = null; application.Properties = null;

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

@ -671,17 +671,10 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
// Warning: FindAsync() is deliberately not used to work around a breaking change introduced // Warning: FindAsync() is deliberately not used to work around a breaking change introduced
// in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned). // in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned).
var application = authorization.Application = await Applications.AsQueryable()
await Applications.AsQueryable() .AsTracking()
.AsTracking() .FirstOrDefaultAsync(application => application.Id!.Equals(key), cancellationToken) ??
.FirstOrDefaultAsync(application => application.Id!.Equals(key), cancellationToken);
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0244)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0244));
}
authorization.Application = application;
} }
else else
@ -715,7 +708,7 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<TAuthorization, TAp
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
authorization.Properties = null; authorization.Properties = null;

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

@ -416,7 +416,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
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 (descriptions is null || descriptions.IsEmpty) if (descriptions is not { Count: > 0 })
{ {
scope.Descriptions = null; scope.Descriptions = null;
@ -458,7 +458,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
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 (names is null || names.IsEmpty) if (names is not { Count: > 0 })
{ {
scope.DisplayNames = null; scope.DisplayNames = null;
@ -500,7 +500,7 @@ public class OpenIddictEntityFrameworkCoreScopeStore<TScope, TContext, TKey> : I
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
scope.Properties = null; scope.Properties = null;

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

@ -594,17 +594,10 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
// Warning: FindAsync() is deliberately not used to work around a breaking change introduced // Warning: FindAsync() is deliberately not used to work around a breaking change introduced
// in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned). // in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned).
var application = token.Application = await Applications.AsQueryable()
await Applications.AsQueryable() .AsTracking()
.AsTracking() .FirstOrDefaultAsync(application => application.Id!.Equals(key), cancellationToken) ??
.FirstOrDefaultAsync(application => application.Id!.Equals(key), cancellationToken);
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0250)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0250));
}
token.Application = application;
} }
else else
@ -634,17 +627,10 @@ public class OpenIddictEntityFrameworkCoreTokenStore<TToken, TApplication, TAuth
// Warning: FindAsync() is deliberately not used to work around a breaking change introduced // Warning: FindAsync() is deliberately not used to work around a breaking change introduced
// in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned). // in Entity Framework Core 3.x (where a ValueTask instead of a Task is now returned).
var authorization = token.Authorization = await Authorizations.AsQueryable()
await Authorizations.AsQueryable() .AsTracking()
.AsTracking() .FirstOrDefaultAsync(authorization => authorization.Id!.Equals(key), cancellationToken) ??
.FirstOrDefaultAsync(authorization => authorization.Id!.Equals(key), cancellationToken);
if (authorization is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0251)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0251));
}
token.Authorization = authorization;
} }
else else

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

@ -387,7 +387,7 @@ public class OpenIddictMongoDbApplicationStore<TApplication> : IOpenIddictApplic
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
application.Properties = null; application.Properties = null;

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

@ -509,7 +509,7 @@ public class OpenIddictMongoDbAuthorizationStore<TAuthorization> : IOpenIddictAu
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
authorization.Properties = null; authorization.Properties = null;

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

@ -319,7 +319,7 @@ public class OpenIddictMongoDbScopeStore<TScope> : IOpenIddictScopeStore<TScope>
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 (properties is not { IsEmpty: false }) if (properties is not { Count: > 0 })
{ {
scope.Properties = null; scope.Properties = null;

2
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs

@ -1134,7 +1134,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// If it was not registered or enabled, let the default OpenIddict server handlers render // If it was not registered or enabled, let the default OpenIddict server handlers render
// a default error page instead of delegating the rendering to the status code middleware. // a default error page instead of delegating the rendering to the status code middleware.
var feature = response.HttpContext.Features.Get<IStatusCodePagesFeature>(); var feature = response.HttpContext.Features.Get<IStatusCodePagesFeature>();
if (feature is null || !feature.Enabled) if (feature is not { Enabled: true })
{ {
return default; return default;
} }

5
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs

@ -109,11 +109,8 @@ public class OpenIddictServerOwinHandler : AuthenticationHandler<OpenIddictServe
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync() protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync()
{ {
var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName); var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ??
if (transaction is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
}
// Note: in many cases, the authentication token was already validated by the time this action is called // Note: in many cases, the authentication token was already validated by the time this action is called
// (generally later in the pipeline, when using the pass-through mode). To avoid having to re-validate it, // (generally later in the pipeline, when using the pass-through mode). To avoid having to re-validate it,

5
src/OpenIddict.Server.Owin/OpenIddictServerOwinMiddlewareFactory.cs

@ -35,11 +35,8 @@ public class OpenIddictServerOwinMiddlewareFactory : OwinMiddleware
/// </returns> /// </returns>
public override Task Invoke(IOwinContext context!!) public override Task Invoke(IOwinContext context!!)
{ {
var provider = context.Get<IServiceProvider>(typeof(IServiceProvider).FullName); var provider = context.Get<IServiceProvider>(typeof(IServiceProvider).FullName) ??
if (provider is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0121)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0121));
}
// Note: the Microsoft.Extensions.DependencyInjection container doesn't support resolving services // Note: the Microsoft.Extensions.DependencyInjection container doesn't support resolving services
// with arbitrary parameters, which prevents the server OWIN middleware from being resolved directly // with arbitrary parameters, which prevents the server OWIN middleware from being resolved directly

59
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -381,11 +381,8 @@ public class OpenIddictServerBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
} }
using var stream = assembly.GetManifestResourceStream(resource); using var stream = assembly.GetManifestResourceStream(resource) ??
if (stream is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
}
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -438,13 +435,10 @@ public class OpenIddictServerBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint));
} }
var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); return AddEncryptionCertificate(
if (certificate is null) GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
{ GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
return AddEncryptionCertificate(certificate);
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -474,16 +468,10 @@ public class OpenIddictServerBuilder
using var store = new X509Store(name, location); using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly); store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) return AddEncryptionCertificate(
.OfType<X509Certificate2>() store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.SingleOrDefault(); .OfType<X509Certificate2>()
.SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
if (certificate is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066));
}
return AddEncryptionCertificate(certificate);
} }
/// <summary> /// <summary>
@ -789,11 +777,8 @@ public class OpenIddictServerBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
} }
using var stream = assembly.GetManifestResourceStream(resource); using var stream = assembly.GetManifestResourceStream(resource) ??
if (stream is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
}
return AddSigningCertificate(stream, password, flags); return AddSigningCertificate(stream, password, flags);
} }
@ -846,13 +831,10 @@ public class OpenIddictServerBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint));
} }
var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); return AddSigningCertificate(
if (certificate is null) GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
{ GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
return AddSigningCertificate(certificate);
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -882,16 +864,11 @@ public class OpenIddictServerBuilder
using var store = new X509Store(name, location); using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly); store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.OfType<X509Certificate2>()
.SingleOrDefault();
if (certificate is null) return AddSigningCertificate(
{ store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); .OfType<X509Certificate2>()
} .SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
return AddSigningCertificate(certificate);
} }
/// <summary> /// <summary>

15
src/OpenIddict.Server/OpenIddictServerDispatcher.cs

@ -93,16 +93,15 @@ public class OpenIddictServerDispatcher : IOpenIddictServerDispatcher
continue; continue;
} }
var handler = descriptor.ServiceDescriptor.ImplementationInstance is not null ? yield return descriptor.ServiceDescriptor switch
descriptor.ServiceDescriptor.ImplementationInstance as IOpenIddictServerHandler<TContext> :
_provider.GetService(descriptor.ServiceDescriptor.ServiceType) as IOpenIddictServerHandler<TContext>;
if (handler is null)
{ {
throw new InvalidOperationException(SR.FormatID0098(descriptor.ServiceDescriptor.ServiceType)); { ImplementationInstance: IOpenIddictServerHandler<TContext> handler } => handler,
}
_ when _provider.GetService(descriptor.ServiceDescriptor.ServiceType)
is IOpenIddictServerHandler<TContext> handler => handler,
yield return handler; _ => throw new InvalidOperationException(SR.FormatID0098(descriptor.ServiceDescriptor.ServiceType))
};
} }
} }

35
src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs

@ -1001,11 +1001,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// To prevent downgrade attacks, ensure that authorization requests returning an access token directly // To prevent downgrade attacks, ensure that authorization requests returning an access token directly
// from the authorization endpoint are rejected if the client_id corresponds to a confidential application // from the authorization endpoint are rejected if the client_id corresponds to a confidential application
@ -1061,11 +1058,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// If no explicit redirect_uri was specified, retrieve the addresses associated with // If no explicit redirect_uri was specified, retrieve the addresses associated with
// the client and ensure exactly one redirect_uri was attached to the client definition. // the client and ensure exactly one redirect_uri was attached to the client definition.
@ -1208,11 +1202,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the authorization endpoint. // Reject the request if the application is not allowed to use the authorization endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Authorization)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Authorization))
@ -1259,11 +1250,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the authorization code grant. // Reject the request if the application is not allowed to use the authorization code grant.
if (context.Request.IsAuthorizationCodeFlow() && if (context.Request.IsAuthorizationCodeFlow() &&
@ -1355,11 +1343,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject requests that specify a response_type for which no permission was granted. // Reject requests that specify a response_type for which no permission was granted.
if (!await HasPermissionAsync(context.Request.GetResponseTypes())) if (!await HasPermissionAsync(context.Request.GetResponseTypes()))
@ -1433,11 +1418,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
foreach (var scope in context.Request.GetScopes()) foreach (var scope in context.Request.GetScopes())
{ {
@ -1501,11 +1483,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.ProofKeyForCodeExchange)) if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.ProofKeyForCodeExchange))
{ {

25
src/OpenIddict.Server/OpenIddictServerHandlers.Device.cs

@ -527,11 +527,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
{ {
@ -596,11 +593,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// If the application is a public client, don't validate the client secret. // If the application is a public client, don't validate the client secret.
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
@ -656,11 +650,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the device endpoint. // Reject the request if the application is not allowed to use the device endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Device)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Device))
@ -707,11 +698,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the device code grant. // Reject the request if the application is not allowed to use the device code grant.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.GrantTypes.DeviceCode)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.GrantTypes.DeviceCode))
@ -775,11 +763,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
foreach (var scope in context.Request.GetScopes()) foreach (var scope in context.Request.GetScopes())
{ {

2
src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs

@ -1170,7 +1170,7 @@ public static partial class OpenIddictServerHandlers
return certificate.GetCertHash(algorithm); return certificate.GetCertHash(algorithm);
#else #else
using var hash = CryptoConfig.CreateFromName(algorithm.Name!) as HashAlgorithm; using var hash = CryptoConfig.CreateFromName(algorithm.Name!) as HashAlgorithm;
if (hash is null || hash is KeyedHashAlgorithm) if (hash is null or KeyedHashAlgorithm)
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0217)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0217));
} }

30
src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs

@ -801,11 +801,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
{ {
@ -883,11 +880,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// If the application is a public client, don't validate the client secret. // If the application is a public client, don't validate the client secret.
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
@ -943,11 +937,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the token endpoint. // Reject the request if the application is not allowed to use the token endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Token)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Token))
@ -996,11 +987,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the specified grant type. // Reject the request if the application is not allowed to use the specified grant type.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Prefixes.GrantType + context.Request.GrantType)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Prefixes.GrantType + context.Request.GrantType))
@ -1064,11 +1052,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
foreach (var scope in context.Request.GetScopes()) foreach (var scope in context.Request.GetScopes())
{ {
@ -1138,11 +1123,8 @@ public static partial class OpenIddictServerHandlers
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.ProofKeyForCodeExchange)) if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.ProofKeyForCodeExchange))
{ {

20
src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs

@ -458,11 +458,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
{ {
@ -527,11 +524,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// If the application is a public client, don't validate the client secret. // If the application is a public client, don't validate the client secret.
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
@ -587,11 +581,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the introspection endpoint. // Reject the request if the application is not allowed to use the introspection endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Introspection)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Introspection))
@ -887,11 +878,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Public clients are not allowed to access sensitive claims as authentication cannot be enforced. // Public clients are not allowed to access sensitive claims as authentication cannot be enforced.
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))

20
src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs

@ -545,11 +545,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var token = await _tokenManager.FindByIdAsync(context.TokenId); var token = await _tokenManager.FindByIdAsync(context.TokenId) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
}
// Restore the creation/expiration dates/identifiers from the token entry metadata. // Restore the creation/expiration dates/identifiers from the token entry metadata.
context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token)) context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token))
@ -1060,20 +1057,14 @@ public static partial class OpenIddictServerHandlers
// If the client application is known, associate it with the token. // If the client application is known, associate it with the token.
if (!string.IsNullOrEmpty(context.ClientId)) if (!string.IsNullOrEmpty(context.ClientId))
{ {
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
}
descriptor.ApplicationId = await _applicationManager.GetIdAsync(application); descriptor.ApplicationId = await _applicationManager.GetIdAsync(application);
} }
var token = await _tokenManager.CreateAsync(descriptor); var token = await _tokenManager.CreateAsync(descriptor) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0019)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0019));
}
var identifier = await _tokenManager.GetIdAsync(token); var identifier = await _tokenManager.GetIdAsync(token);
@ -1237,11 +1228,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0009)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0009));
} }
var token = await _tokenManager.FindByIdAsync(identifier); var token = await _tokenManager.FindByIdAsync(identifier) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
}
var descriptor = new OpenIddictTokenDescriptor(); var descriptor = new OpenIddictTokenDescriptor();
await _tokenManager.PopulateAsync(descriptor, token); await _tokenManager.PopulateAsync(descriptor, token);

15
src/OpenIddict.Server/OpenIddictServerHandlers.Revocation.cs

@ -405,11 +405,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
{ {
@ -474,11 +471,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// If the application is a public client, don't validate the client secret. // If the application is a public client, don't validate the client secret.
if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public)) if (await _applicationManager.HasClientTypeAsync(application, ClientTypes.Public))
@ -534,11 +528,8 @@ public static partial class OpenIddictServerHandlers
{ {
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var application = await _applicationManager.FindByClientIdAsync(context.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
}
// Reject the request if the application is not allowed to use the revocation endpoint. // Reject the request if the application is not allowed to use the revocation endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Revocation)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.Revocation))

22
src/OpenIddict.Server/OpenIddictServerHandlers.cs

@ -1427,20 +1427,14 @@ public static partial class OpenIddictServerHandlers
// If the client application is known, associate it to the authorization. // If the client application is known, associate it to the authorization.
if (!string.IsNullOrEmpty(context.Request.ClientId)) if (!string.IsNullOrEmpty(context.Request.ClientId))
{ {
var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId); var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId) ??
if (application is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
}
descriptor.ApplicationId = await _applicationManager.GetIdAsync(application); descriptor.ApplicationId = await _applicationManager.GetIdAsync(application);
} }
var authorization = await _authorizationManager.CreateAsync(descriptor); var authorization = await _authorizationManager.CreateAsync(descriptor) ??
if (authorization is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0018)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0018));
}
var identifier = await _authorizationManager.GetIdAsync(authorization); var identifier = await _authorizationManager.GetIdAsync(authorization);
@ -2368,11 +2362,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0008)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0008));
} }
var token = await _tokenManager.FindByIdAsync(identifier); var token = await _tokenManager.FindByIdAsync(identifier) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0265)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0265));
}
// Replace the device code details by the payload derived from the new device code principal, // Replace the device code details by the payload derived from the new device code principal,
// that includes all the user claims populated by the application after authenticating the user. // that includes all the user claims populated by the application after authenticating the user.
@ -2423,14 +2414,11 @@ public static partial class OpenIddictServerHandlers
} }
var credentials = context.Options.SigningCredentials.Find( var credentials = context.Options.SigningCredentials.Find(
credentials => credentials.Key is AsymmetricSecurityKey); credentials => credentials.Key is AsymmetricSecurityKey) ??
if (credentials is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0266)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0266));
}
using var algorithm = GetHashAlgorithm(credentials); using var algorithm = GetHashAlgorithm(credentials);
if (algorithm is null || algorithm is KeyedHashAlgorithm) if (algorithm is null or KeyedHashAlgorithm)
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0267)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0267));
} }

5
src/OpenIddict.Validation.Owin/OpenIddictValidationOwinMiddlewareFactory.cs

@ -35,11 +35,8 @@ public class OpenIddictValidationOwinMiddlewareFactory : OwinMiddleware
/// </returns> /// </returns>
public override Task Invoke(IOwinContext context!!) public override Task Invoke(IOwinContext context!!)
{ {
var provider = context.Get<IServiceProvider>(typeof(IServiceProvider).FullName); var provider = context.Get<IServiceProvider>(typeof(IServiceProvider).FullName) ??
if (provider is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0168)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0168));
}
// Note: the Microsoft.Extensions.DependencyInjection container doesn't support resolving services // Note: the Microsoft.Extensions.DependencyInjection container doesn't support resolving services
// with arbitrary parameters, which prevents the validation OWIN middleware from being resolved directly // with arbitrary parameters, which prevents the validation OWIN middleware from being resolved directly

10
src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs

@ -221,21 +221,15 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
var assembly = typeof(OpenIddictValidationSystemNetHttpOptions).Assembly.GetName(); var assembly = typeof(OpenIddictValidationSystemNetHttpOptions).Assembly.GetName();
using var client = _factory.CreateClient(assembly.Name!); using var client = _factory.CreateClient(assembly.Name!) ??
if (client is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0174)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0174));
}
#if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION #if SUPPORTS_HTTP_CLIENT_DEFAULT_REQUEST_VERSION
// If supported, import the HTTP version from the client instance. // If supported, import the HTTP version from the client instance.
request.Version = client.DefaultRequestVersion; request.Version = client.DefaultRequestVersion;
#endif #endif
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead); var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead) ??
if (response is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0175)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0175));
}
// Store the HttpResponseMessage in the transaction properties. // Store the HttpResponseMessage in the transaction properties.
context.Transaction.SetProperty(typeof(HttpResponseMessage).FullName!, response); context.Transaction.SetProperty(typeof(HttpResponseMessage).FullName!, response);

29
src/OpenIddict.Validation/OpenIddictValidationBuilder.cs

@ -202,11 +202,8 @@ public class OpenIddictValidationBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource)); throw new ArgumentException(SR.GetResourceString(SR.ID0062), nameof(resource));
} }
using var stream = assembly.GetManifestResourceStream(resource); using var stream = assembly.GetManifestResourceStream(resource) ??
if (stream is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
}
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -260,13 +257,10 @@ public class OpenIddictValidationBuilder
throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint)); throw new ArgumentException(SR.GetResourceString(SR.ID0065), nameof(thumbprint));
} }
var certificate = GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint); return AddEncryptionCertificate(
if (certificate is null) GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
{ GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
return AddEncryptionCertificate(certificate);
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -297,16 +291,11 @@ public class OpenIddictValidationBuilder
using var store = new X509Store(name, location); using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly); store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.OfType<X509Certificate2>()
.SingleOrDefault();
if (certificate is null) return AddEncryptionCertificate(
{ store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)); .OfType<X509Certificate2>()
} .SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
return AddEncryptionCertificate(certificate);
} }
/// <summary> /// <summary>

15
src/OpenIddict.Validation/OpenIddictValidationDispatcher.cs

@ -93,16 +93,15 @@ public class OpenIddictValidationDispatcher : IOpenIddictValidationDispatcher
continue; continue;
} }
var handler = descriptor.ServiceDescriptor.ImplementationInstance is not null ? yield return descriptor.ServiceDescriptor switch
descriptor.ServiceDescriptor.ImplementationInstance as IOpenIddictValidationHandler<TContext> :
_provider.GetService(descriptor.ServiceDescriptor.ServiceType) as IOpenIddictValidationHandler<TContext>;
if (handler is null)
{ {
throw new InvalidOperationException(SR.FormatID0138(descriptor.ServiceDescriptor.ServiceType)); { ImplementationInstance: IOpenIddictValidationHandler<TContext> handler } => handler,
}
_ when _provider.GetService(descriptor.ServiceDescriptor.ServiceType)
is IOpenIddictValidationHandler<TContext> handler => handler,
yield return handler; _ => throw new InvalidOperationException(SR.FormatID0138(descriptor.ServiceDescriptor.ServiceType))
};
} }
} }

5
src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs

@ -545,11 +545,8 @@ public static partial class OpenIddictValidationHandlers
return; return;
} }
var token = await _tokenManager.FindByIdAsync(context.TokenId); var token = await _tokenManager.FindByIdAsync(context.TokenId) ??
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
}
// Restore the creation/expiration dates/identifiers from the token entry metadata. // Restore the creation/expiration dates/identifiers from the token entry metadata.
context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token)) context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token))

21
src/OpenIddict.Validation/OpenIddictValidationService.cs

@ -55,13 +55,8 @@ public class OpenIddictValidationService
request = await ApplyConfigurationRequestAsync(); request = await ApplyConfigurationRequestAsync();
var response = await ExtractConfigurationResponseAsync(); var response = await ExtractConfigurationResponseAsync();
var configuration = await HandleConfigurationResponseAsync(); return await HandleConfigurationResponseAsync() ??
if (configuration is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
}
return configuration;
async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync() async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync()
{ {
@ -195,13 +190,8 @@ public class OpenIddictValidationService
var response = await ExtractCryptographyResponseAsync(); var response = await ExtractCryptographyResponseAsync();
var keys = await HandleCryptographyResponseAsync(); return await HandleCryptographyResponseAsync() ??
if (keys is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
}
return keys;
async ValueTask<OpenIddictRequest> PrepareCryptographyRequestAsync() async ValueTask<OpenIddictRequest> PrepareCryptographyRequestAsync()
{ {
@ -351,13 +341,8 @@ public class OpenIddictValidationService
request = await ApplyIntrospectionRequestAsync(); request = await ApplyIntrospectionRequestAsync();
var response = await ExtractIntrospectionResponseAsync(); var response = await ExtractIntrospectionResponseAsync();
var principal = await HandleIntrospectionResponseAsync(); return await HandleIntrospectionResponseAsync() ??
if (principal is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0157)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0157));
}
return principal;
async ValueTask<OpenIddictRequest> PrepareIntrospectionRequestAsync() async ValueTask<OpenIddictRequest> PrepareIntrospectionRequestAsync()
{ {

2
test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs

@ -211,7 +211,7 @@ public class OpenIddictServerIntegrationTestClient : IAsyncDisposable
} }
var values = (string?[]?) parameter.Value; var values = (string?[]?) parameter.Value;
if (values is null || values.Length == 0) if (values is not { Length: > 0 })
{ {
continue; continue;
} }

Loading…
Cancel
Save