Browse Source

Normalize the code style of null-coalescing and ternary operators

pull/2501/head
Kévin Chalet 3 weeks ago
parent
commit
3c0e8b4e24
  1. 32
      gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs
  2. 28
      sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs
  3. 36
      sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs
  4. 4
      sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs
  5. 5
      sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs
  6. 4
      src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs
  7. 12
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandler.cs
  8. 4
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.Authentication.cs
  9. 4
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.Session.cs
  10. 60
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
  11. 28
      src/OpenIddict.Client.Owin/OpenIddictClientOwinHandler.cs
  12. 4
      src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.Authentication.cs
  13. 4
      src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.Session.cs
  14. 64
      src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs
  15. 6
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs
  16. 4
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs
  17. 4
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs
  18. 24
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs
  19. 6
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHttpListener.cs
  20. 10
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationPipeListener.cs
  21. 8
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpConfiguration.cs
  22. 8
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.Userinfo.cs
  23. 72
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  24. 16
      src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Exchange.cs
  25. 16
      src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Revocation.cs
  26. 88
      src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Userinfo.cs
  27. 20
      src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.cs
  28. 44
      src/OpenIddict.Client/OpenIddictClientBuilder.cs
  29. 28
      src/OpenIddict.Client/OpenIddictClientHandlerDescriptor.cs
  30. 14
      src/OpenIddict.Client/OpenIddictClientHandlers.Introspection.cs
  31. 18
      src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs
  32. 6
      src/OpenIddict.Client/OpenIddictClientHandlers.Userinfo.cs
  33. 77
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  34. 8
      src/OpenIddict.Client/OpenIddictClientRetriever.cs
  35. 24
      src/OpenIddict.Client/OpenIddictClientService.cs
  36. 8
      src/OpenIddict.Core/Caches/OpenIddictApplicationCache.cs
  37. 8
      src/OpenIddict.Core/Caches/OpenIddictAuthorizationCache.cs
  38. 8
      src/OpenIddict.Core/Caches/OpenIddictResourceCache.cs
  39. 8
      src/OpenIddict.Core/Caches/OpenIddictScopeCache.cs
  40. 8
      src/OpenIddict.Core/Caches/OpenIddictTokenCache.cs
  41. 28
      src/OpenIddict.Core/Managers/OpenIddictApplicationManager.cs
  42. 28
      src/OpenIddict.Core/Managers/OpenIddictAuthorizationManager.cs
  43. 22
      src/OpenIddict.Core/Managers/OpenIddictResourceManager.cs
  44. 28
      src/OpenIddict.Core/Managers/OpenIddictScopeManager.cs
  45. 40
      src/OpenIddict.Core/Managers/OpenIddictTokenManager.cs
  46. 4
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkAuthorizationStore.cs
  47. 8
      src/OpenIddict.EntityFramework/Stores/OpenIddictEntityFrameworkTokenStore.cs
  48. 6
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreAuthorizationStore.cs
  49. 6
      src/OpenIddict.EntityFrameworkCore/Stores/OpenIddictEntityFrameworkCoreTokenStore.cs
  50. 8
      src/OpenIddict.Quartz/OpenIddictQuartzJob.cs
  51. 16
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs
  52. 16
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs
  53. 4
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Device.cs
  54. 12
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Session.cs
  55. 68
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
  56. 24
      src/OpenIddict.Server.DataProtection/OpenIddictServerDataProtectionHandlers.Protection.cs
  57. 24
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandler.cs
  58. 16
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs
  59. 4
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Device.cs
  60. 12
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Session.cs
  61. 72
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
  62. 44
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  63. 28
      src/OpenIddict.Server/OpenIddictServerHandlerDescriptor.cs
  64. 124
      src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs
  65. 24
      src/OpenIddict.Server/OpenIddictServerHandlers.Device.cs
  66. 44
      src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
  67. 20
      src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs
  68. 34
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  69. 8
      src/OpenIddict.Server/OpenIddictServerHandlers.Revocation.cs
  70. 20
      src/OpenIddict.Server/OpenIddictServerHandlers.Session.cs
  71. 4
      src/OpenIddict.Server/OpenIddictServerHandlers.Userinfo.cs
  72. 188
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  73. 8
      src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandler.cs
  74. 40
      src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs
  75. 16
      src/OpenIddict.Validation.Owin/OpenIddictValidationOwinHandler.cs
  76. 48
      src/OpenIddict.Validation.Owin/OpenIddictValidationOwinHandlers.cs
  77. 8
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs
  78. 68
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs
  79. 44
      src/OpenIddict.Validation/OpenIddictValidationBuilder.cs
  80. 28
      src/OpenIddict.Validation/OpenIddictValidationHandlerDescriptor.cs
  81. 7
      src/OpenIddict.Validation/OpenIddictValidationHandlers.Introspection.cs
  82. 14
      src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs
  83. 4
      src/OpenIddict.Validation/OpenIddictValidationHandlers.cs
  84. 8
      src/OpenIddict.Validation/OpenIddictValidationRetriever.cs
  85. 8
      src/OpenIddict.Validation/OpenIddictValidationService.cs
  86. 4
      test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.cs

32
gen/OpenIddict.Client.WebIntegration.Generators/OpenIddictClientWebIntegrationGenerator.cs

@ -582,9 +582,9 @@ public sealed partial class OpenIddictClientWebIntegrationBuilder
{{~ end ~}} {{~ end ~}}
public {{ provider.name }} Set{{ setting.property_name }}(Assembly assembly, string resource, string? password) public {{ provider.name }} Set{{ setting.property_name }}(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> Set{{ setting.property_name }}(assembly, resource, password, OperatingSystem.IsMacOS() ? => Set{{ setting.property_name }}(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Configures {{ setting.description }}. /// Configures {{ setting.description }}.
@ -604,8 +604,8 @@ public sealed partial class OpenIddictClientWebIntegrationBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return Set{{ setting.property_name }}(stream, password, flags); return Set{{ setting.property_name }}(stream, password, flags);
} }
@ -621,9 +621,9 @@ public sealed partial class OpenIddictClientWebIntegrationBuilder
{{~ end ~}} {{~ end ~}}
public {{ provider.name }} Set{{ setting.property_name }}(Stream stream, string? password) public {{ provider.name }} Set{{ setting.property_name }}(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> Set{{ setting.property_name }}(stream, password, OperatingSystem.IsMacOS() ? => Set{{ setting.property_name }}(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Configures {{ setting.description }}. /// Configures {{ setting.description }}.
@ -666,9 +666,9 @@ public sealed partial class OpenIddictClientWebIntegrationBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return Set{{ setting.property_name }}( return Set{{ setting.property_name }}(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -780,8 +780,9 @@ public sealed partial class OpenIddictClientWebIntegrationBuilder
Collection = (bool?) setting.Attribute("Collection") ?? false, Collection = (bool?) setting.Attribute("Collection") ?? false,
Obsolete = (bool?) setting.Attribute("Obsolete") ?? false, Obsolete = (bool?) setting.Attribute("Obsolete") ?? false,
Description = (string) setting.Attribute("Description") is string description ? Description = (string) setting.Attribute("Description") is string description
char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US")) + description[1..] : null, ? char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US")) + description[1..]
: null,
ClrType = (string) setting.Attribute("Type") switch ClrType = (string) setting.Attribute("Type") switch
{ {
"Boolean" => "bool", "Boolean" => "bool",
@ -1559,8 +1560,9 @@ public sealed partial class OpenIddictClientWebIntegrationSettings
Collection = (bool?) setting.Attribute("Collection") ?? false, Collection = (bool?) setting.Attribute("Collection") ?? false,
Obsolete = (bool?) setting.Attribute("Obsolete") ?? false, Obsolete = (bool?) setting.Attribute("Obsolete") ?? false,
Description = (string) setting.Attribute("Description") is string description ? Description = (string) setting.Attribute("Description") is string description
char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US")) + description[1..] : null, ? char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US")) + description[1..]
: null,
ClrType = (string) setting.Attribute("Type") switch ClrType = (string) setting.Attribute("Type") switch
{ {
"Boolean" => "bool", "Boolean" => "bool",

28
sandbox/OpenIddict.Sandbox.AspNet.Server/Controllers/AuthorizationController.cs

@ -53,8 +53,8 @@ public class AuthorizationController : Controller
// user agent (e.g as HTML hidden input fields). If only the query string or request form parameters // user agent (e.g as HTML hidden input fields). If only the query string or request form parameters
// need to be resolved, the Request.QueryString and Request.Form collections must be used instead. // need to be resolved, the Request.QueryString and Request.Form collections must be used instead.
var context = HttpContext.GetOwinContext(); var context = HttpContext.GetOwinContext();
var request = context.GetOpenIddictServerRequest() ?? var request = context.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Try to retrieve the user principal stored in the authentication cookie and redirect // Try to retrieve the user principal stored in the authentication cookie and redirect
// the user agent to the login page (or to an external provider) in the following cases: // the user agent to the login page (or to an external provider) in the following cases:
@ -124,12 +124,12 @@ public class AuthorizationController : Controller
} }
// Retrieve the profile of the logged in user. // Retrieve the profile of the logged in user.
var user = await context.GetUserManager<ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId()) ?? var user = await context.GetUserManager<ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId())
throw new InvalidOperationException("The user details cannot be retrieved."); ?? throw new InvalidOperationException("The user details cannot be retrieved.");
// Retrieve the application details from the database. // Retrieve the application details from the database.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(request.ClientId)
throw new InvalidOperationException("Details concerning the calling client application cannot be found."); ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Retrieve the permanent authorizations associated with the user and the calling client application. // Retrieve the permanent authorizations associated with the user and the calling client application.
var authorizations = await _authorizationManager.FindAsync( var authorizations = await _authorizationManager.FindAsync(
@ -230,8 +230,8 @@ public class AuthorizationController : Controller
// user agent (e.g as HTML hidden input fields). If only the query string or request form parameters // user agent (e.g as HTML hidden input fields). If only the query string or request form parameters
// need to be resolved, the Request.QueryString and Request.Form collections must be used instead. // need to be resolved, the Request.QueryString and Request.Form collections must be used instead.
var context = HttpContext.GetOwinContext(); var context = HttpContext.GetOwinContext();
var request = context.GetOpenIddictServerRequest() ?? var request = context.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Retrieve the user principal stored in the authentication cookie. // Retrieve the user principal stored in the authentication cookie.
var result = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie); var result = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);
@ -243,12 +243,12 @@ public class AuthorizationController : Controller
} }
// Retrieve the profile of the logged in user. // Retrieve the profile of the logged in user.
var user = await context.GetUserManager<ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId()) ?? var user = await context.GetUserManager<ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId())
throw new InvalidOperationException("The user details cannot be retrieved."); ?? throw new InvalidOperationException("The user details cannot be retrieved.");
// Retrieve the application details from the database. // Retrieve the application details from the database.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(request.ClientId)
throw new InvalidOperationException("Details concerning the calling client application cannot be found."); ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Retrieve the permanent authorizations associated with the user and the calling client application. // Retrieve the permanent authorizations associated with the user and the calling client application.
var authorizations = await _authorizationManager.FindAsync( var authorizations = await _authorizationManager.FindAsync(
@ -348,8 +348,8 @@ public class AuthorizationController : Controller
public async Task<ActionResult> Exchange() public async Task<ActionResult> Exchange()
{ {
var context = HttpContext.GetOwinContext(); var context = HttpContext.GetOwinContext();
var request = context.GetOpenIddictServerRequest() ?? var request = context.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType()) if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType())
{ {

36
sandbox/OpenIddict.Sandbox.AspNetCore.Server/Controllers/AuthorizationController.cs

@ -62,8 +62,8 @@ public class AuthorizationController : Controller
// As such, the data contained in this object MUST NOT be serialized or returned unprotected to the // As such, the data contained in this object MUST NOT be serialized or returned unprotected to the
// user agent (e.g as HTML hidden input fields). If only the query string or request form parameters // user agent (e.g as HTML hidden input fields). If only the query string or request form parameters
// need to be resolved, the Request.Query and Request.Form collections must be used instead. // need to be resolved, the Request.Query and Request.Form collections must be used instead.
var request = HttpContext.GetOpenIddictServerRequest() ?? var request = HttpContext.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Try to retrieve the user principal stored in the authentication cookie and redirect // Try to retrieve the user principal stored in the authentication cookie and redirect
// the user agent to the login page (or to an external provider) in the following cases: // the user agent to the login page (or to an external provider) in the following cases:
@ -148,12 +148,12 @@ public class AuthorizationController : Controller
} }
// Retrieve the profile of the logged in user. // Retrieve the profile of the logged in user.
var user = await _userManager.GetUserAsync(result.Principal) ?? var user = await _userManager.GetUserAsync(result.Principal)
throw new InvalidOperationException("The user details cannot be retrieved."); ?? throw new InvalidOperationException("The user details cannot be retrieved.");
// Retrieve the application details from the database. // Retrieve the application details from the database.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId!) ?? var application = await _applicationManager.FindByClientIdAsync(request.ClientId!)
throw new InvalidOperationException("Details concerning the calling client application cannot be found."); ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Retrieve the permanent authorizations associated with the user and the calling client application. // Retrieve the permanent authorizations associated with the user and the calling client application.
var authorizations = await _authorizationManager.FindAsync( var authorizations = await _authorizationManager.FindAsync(
@ -247,16 +247,16 @@ public class AuthorizationController : Controller
// As such, the data contained in this object MUST NOT be serialized or returned unprotected to the // As such, the data contained in this object MUST NOT be serialized or returned unprotected to the
// user agent (e.g as HTML hidden input fields). If only the query string or request form parameters // user agent (e.g as HTML hidden input fields). If only the query string or request form parameters
// need to be resolved, the Request.Query and Request.Form collections must be used instead. // need to be resolved, the Request.Query and Request.Form collections must be used instead.
var request = HttpContext.GetOpenIddictServerRequest() ?? var request = HttpContext.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Retrieve the profile of the logged in user. // Retrieve the profile of the logged in user.
var user = await _userManager.GetUserAsync(User) ?? var user = await _userManager.GetUserAsync(User)
throw new InvalidOperationException("The user details cannot be retrieved."); ?? throw new InvalidOperationException("The user details cannot be retrieved.");
// Retrieve the application details from the database. // Retrieve the application details from the database.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId!) ?? var application = await _applicationManager.FindByClientIdAsync(request.ClientId!)
throw new InvalidOperationException("Details concerning the calling client application cannot be found."); ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Retrieve the permanent authorizations associated with the user and the calling client application. // Retrieve the permanent authorizations associated with the user and the calling client application.
var authorizations = await _authorizationManager.FindAsync( var authorizations = await _authorizationManager.FindAsync(
@ -334,8 +334,8 @@ public class AuthorizationController : Controller
if (result is { Succeeded: true } && !string.IsNullOrEmpty(result.Principal.GetClaim(Claims.ClientId))) if (result is { Succeeded: true } && !string.IsNullOrEmpty(result.Principal.GetClaim(Claims.ClientId)))
{ {
// Retrieve the application details from the database using the client_id stored in the principal. // Retrieve the application details from the database using the client_id stored in the principal.
var application = await _applicationManager.FindByClientIdAsync(result.Principal.GetClaim(Claims.ClientId)!) ?? var application = await _applicationManager.FindByClientIdAsync(result.Principal.GetClaim(Claims.ClientId)!)
throw new InvalidOperationException("Details concerning the calling client application cannot be found."); ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Render a form asking the user to confirm the authorization demand. // Render a form asking the user to confirm the authorization demand.
return View(new VerifyViewModel return View(new VerifyViewModel
@ -366,8 +366,8 @@ public class AuthorizationController : Controller
public async Task<IActionResult> VerifyAccept() public async Task<IActionResult> VerifyAccept()
{ {
// Retrieve the profile of the logged in user. // Retrieve the profile of the logged in user.
var user = await _userManager.GetUserAsync(User) ?? var user = await _userManager.GetUserAsync(User)
throw new InvalidOperationException("The user details cannot be retrieved."); ?? throw new InvalidOperationException("The user details cannot be retrieved.");
// Retrieve the claims principal associated with the user code. // Retrieve the claims principal associated with the user code.
var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
@ -458,8 +458,8 @@ public class AuthorizationController : Controller
[HttpPost("~/connect/token"), IgnoreAntiforgeryToken, Produces("application/json")] [HttpPost("~/connect/token"), IgnoreAntiforgeryToken, Produces("application/json")]
public async Task<IActionResult> Exchange() public async Task<IActionResult> Exchange()
{ {
var request = HttpContext.GetOpenIddictServerRequest() ?? var request = HttpContext.GetOpenIddictServerRequest()
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
if (request.IsPasswordGrantType()) if (request.IsPasswordGrantType())
{ {

4
sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs

@ -351,8 +351,8 @@ builder.Services.Configure<KestrelServerOptions>(options => options.ListenAnyIP(
.Where(static certificate => certificate.NotBefore < TimeProvider.System.GetLocalNow()) .Where(static certificate => certificate.NotBefore < TimeProvider.System.GetLocalNow())
.Where(static certificate => certificate.NotAfter > TimeProvider.System.GetLocalNow()) .Where(static certificate => certificate.NotAfter > TimeProvider.System.GetLocalNow())
.OrderByDescending(static certificate => certificate.NotAfter) .OrderByDescending(static certificate => certificate.NotAfter)
.FirstOrDefault() ?? .FirstOrDefault()
throw new InvalidOperationException("The ASP.NET Core HTTPS development certificate was not found.") ?? throw new InvalidOperationException("The ASP.NET Core HTTPS development certificate was not found.")
}); });
} }
})); }));

5
sandbox/OpenIddict.Sandbox.Console.Client/InteractiveService.cs

@ -402,8 +402,9 @@ public class InteractiveService : BackgroundService
CancellationToken = stoppingToken, CancellationToken = stoppingToken,
ProviderName = provider, ProviderName = provider,
Token = response.IssuedToken, Token = response.IssuedToken,
TokenTypeHint = response.IssuedTokenType is TokenTypeIdentifiers.AccessToken ? TokenTypeHint = response.IssuedTokenType is TokenTypeIdentifiers.AccessToken
TokenTypeHints.AccessToken : TokenTypeHints.RefreshToken ? TokenTypeHints.AccessToken
: TokenTypeHints.RefreshToken
}); });
AnsiConsole.MarkupLine("[steelblue]Access token revoked.[/]"); AnsiConsole.MarkupLine("[steelblue]Access token revoked.[/]");

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

@ -803,8 +803,8 @@ public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
// When the parameter is a string starting with '{' or '[' (which would correspond // When the parameter is a string starting with '{' or '[' (which would correspond
// to a JSON object or array), try to deserialize it to get a JsonElement instance. // to a JSON object or array), try to deserialize it to get a JsonElement instance.
string { Length: > 0 } value when value[0] is '{' or '[' => string { Length: > 0 } value when value[0] is '{' or '[' =>
DeserializeElement(value) ?? DeserializeElement(value)
DeserializeElement(JsonSerializer.Serialize(value, OpenIddictSerializer.Default.String)) ?? default, ?? DeserializeElement(JsonSerializer.Serialize(value, OpenIddictSerializer.Default.String)) ?? default,
// Otherwise, serialize it to get a JsonElement instance. // Otherwise, serialize it to get a JsonElement instance.
bool value => JsonSerializer.SerializeToElement(value, OpenIddictSerializer.Default.Boolean), bool value => JsonSerializer.SerializeToElement(value, OpenIddictSerializer.Default.Boolean),

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

@ -107,8 +107,8 @@ public sealed class OpenIddictClientAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
// 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,
@ -370,8 +370,8 @@ public sealed class OpenIddictClientAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task HandleChallengeAsync(AuthenticationProperties? properties) protected override async Task HandleChallengeAsync(AuthenticationProperties? properties)
{ {
var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();
@ -418,8 +418,8 @@ public sealed class OpenIddictClientAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
public async Task SignOutAsync(AuthenticationProperties? properties) public async Task SignOutAsync(AuthenticationProperties? properties)
{ {
var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictClientAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
var context = new ProcessSignOutContext(transaction) var context = new ProcessSignOutContext(transaction)
{ {

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

@ -65,8 +65,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters // Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification. // with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.

4
src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.Session.cs

@ -65,8 +65,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters // Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification. // with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.

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

@ -100,8 +100,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -151,8 +151,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Don't require that transport security be used if the request is not handled by OpenIddict. // Don't require that transport security be used if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictClientEndpointType.Unknown && !request.IsHttps) if (context.EndpointType is not OpenIddictClientEndpointType.Unknown && !request.IsHttps)
@ -193,8 +193,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Don't require that the request host be present if the request is not handled by OpenIddict. // Don't require that the request host be present if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictClientEndpointType.Unknown && !request.Host.HasValue) if (context.EndpointType is not OpenIddictClientEndpointType.Unknown && !request.Host.HasValue)
@ -235,8 +235,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (HttpMethods.IsGet(request.Method)) if (HttpMethods.IsGet(request.Method))
{ {
@ -383,8 +383,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Resolve the nonce from the state token principal. // Resolve the nonce from the state token principal.
var nonce = context.StateTokenPrincipal.GetClaim(Claims.Private.Nonce); var nonce = context.StateTokenPrincipal.GetClaim(Claims.Private.Nonce);
@ -533,8 +533,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!); var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!);
if (properties is { Items.Count: > 0 }) if (properties is { Items.Count: > 0 })
@ -640,8 +640,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (!request.IsHttps) if (!request.IsHttps)
{ {
@ -792,8 +792,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Resolve the cookie builder from the ASP.NET Core integration options. // Resolve the cookie builder from the ASP.NET Core integration options.
var builder = _options.CurrentValue.CookieBuilder; var builder = _options.CurrentValue.CookieBuilder;
@ -856,8 +856,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!); var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!);
if (properties is { Items.Count: > 0 }) if (properties is { Items.Count: > 0 })
@ -953,8 +953,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (!request.IsHttps) if (!request.IsHttps)
{ {
@ -1015,8 +1015,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Resolve the cookie builder from the ASP.NET Core integration options. // Resolve the cookie builder from the ASP.NET Core integration options.
var builder = _options.CurrentValue.CookieBuilder; var builder = _options.CurrentValue.CookieBuilder;
@ -1109,8 +1109,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -1149,8 +1149,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[HeaderNames.CacheControl] = "no-store"; response.Headers[HeaderNames.CacheControl] = "no-store";
@ -1227,8 +1227,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -1280,8 +1280,8 @@ public static partial class OpenIddictClientAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));

28
src/OpenIddict.Client.Owin/OpenIddictClientOwinHandler.cs

@ -78,11 +78,11 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
// in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when // in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when
// active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case. // active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case.
var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName) ?? var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!) ?? var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
if (context.IsRequestHandled) if (context.IsRequestHandled)
{ {
@ -126,8 +126,8 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync() protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync()
{ {
var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName) ?? var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
// 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,
@ -295,8 +295,8 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
if (challenge is not null && Response.StatusCode is 401 or 403) if (challenge is not null && Response.StatusCode is 401 or 403)
{ {
var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName) ?? var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties();
@ -341,8 +341,8 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
if (signout is not null) if (signout is not null)
{ {
var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName) ?? var transaction = Context.Get<OpenIddictClientTransaction>(typeof(OpenIddictClientTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0315)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0315));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = signout.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = signout.Properties ?? new AuthenticationProperties();
@ -409,8 +409,8 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
return new AuthenticationResponseChallenge( return new AuthenticationResponseChallenge(
authenticationTypes: [OpenIddictClientOwinDefaults.AuthenticationType], authenticationTypes: [OpenIddictClientOwinDefaults.AuthenticationType],
properties : new AuthenticationProperties(dictionary: new Dictionary<string, string>( properties : new AuthenticationProperties(dictionary: new Dictionary<string, string>(
manager.AuthenticationResponseChallenge.Properties.Dictionary ?? manager.AuthenticationResponseChallenge.Properties.Dictionary
ImmutableDictionary.Create<string, string>()) ?? ImmutableDictionary.Create<string, string>())
{ {
[Properties.ProviderName] = type [Properties.ProviderName] = type
})); }));
@ -448,8 +448,8 @@ public sealed class OpenIddictClientOwinHandler : AuthenticationHandler<Authenti
return new AuthenticationResponseRevoke( return new AuthenticationResponseRevoke(
authenticationTypes: [OpenIddictClientOwinDefaults.AuthenticationType], authenticationTypes: [OpenIddictClientOwinDefaults.AuthenticationType],
properties : new AuthenticationProperties(dictionary: new Dictionary<string, string>( properties : new AuthenticationProperties(dictionary: new Dictionary<string, string>(
manager.AuthenticationResponseRevoke.Properties.Dictionary ?? manager.AuthenticationResponseRevoke.Properties.Dictionary
ImmutableDictionary.Create<string, string>()) ?? ImmutableDictionary.Create<string, string>())
{ {
[Properties.ProviderName] = type [Properties.ProviderName] = type
})); }));

4
src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.Authentication.cs

@ -65,8 +65,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var location = context.AuthorizationEndpoint; var location = context.AuthorizationEndpoint;

4
src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.Session.cs

@ -63,8 +63,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var location = context.EndSessionEndpoint; var location = context.EndSessionEndpoint;

64
src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs

@ -97,8 +97,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -148,8 +148,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Don't require that transport security be used if the request is not handled by OpenIddict. // Don't require that transport security be used if the request is not handled by OpenIddict.
if (context.EndpointType is OpenIddictClientEndpointType.Unknown) if (context.EndpointType is OpenIddictClientEndpointType.Unknown)
@ -195,8 +195,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Don't require that the request host be present if the request is not handled by OpenIddict. // Don't require that the request host be present if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictClientEndpointType.Unknown && if (context.EndpointType is not OpenIddictClientEndpointType.Unknown &&
@ -238,8 +238,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase)) if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase))
{ {
@ -392,8 +392,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Resolve the nonce from the state token principal. // Resolve the nonce from the state token principal.
var nonce = context.StateTokenPrincipal.GetClaim(Claims.Private.Nonce); var nonce = context.StateTokenPrincipal.GetClaim(Claims.Private.Nonce);
@ -539,8 +539,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!); var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!);
if (properties is not { Dictionary.Count: > 0 }) if (properties is not { Dictionary.Count: > 0 })
@ -659,8 +659,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (!request.IsSecure) if (!request.IsSecure)
{ {
@ -811,8 +811,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Compute a collision-resistant and hard-to-guess cookie name using the nonce. // Compute a collision-resistant and hard-to-guess cookie name using the nonce.
var name = new StringBuilder(_options.CurrentValue.CookieName) var name = new StringBuilder(_options.CurrentValue.CookieName)
@ -883,8 +883,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!); var properties = context.Transaction.GetProperty<AuthenticationProperties>(typeof(AuthenticationProperties).FullName!);
if (properties is not { Dictionary.Count: > 0 }) if (properties is not { Dictionary.Count: > 0 })
@ -993,8 +993,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (!request.IsSecure) if (!request.IsSecure)
{ {
@ -1055,8 +1055,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Compute a collision-resistant and hard-to-guess cookie name using the nonce. // Compute a collision-resistant and hard-to-guess cookie name using the nonce.
var name = new StringBuilder(_options.CurrentValue.CookieName) var name = new StringBuilder(_options.CurrentValue.CookieName)
@ -1157,8 +1157,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -1197,8 +1197,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OWIN authentication middleware configured to use active authentication (which is the default mode) // OWIN authentication middleware configured to use active authentication (which is the default mode)
// are known to aggressively intercept 401 responses even if the request is already considered fully // are known to aggressively intercept 401 responses even if the request is already considered fully
@ -1247,8 +1247,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Similarly to the automatic authentication mode used by OWIN authentication middleware, // Similarly to the automatic authentication mode used by OWIN authentication middleware,
// the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if // the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if
@ -1311,8 +1311,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[Headers.CacheControl] = "no-store"; response.Headers[Headers.CacheControl] = "no-store";
@ -1388,8 +1388,8 @@ public static partial class OpenIddictClientOwinHandlers
// This handler only applies to OWIN requests. If the HTTP context cannot be resolved, // This handler only applies to OWIN requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));

6
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationConfiguration.cs

@ -111,9 +111,9 @@ public sealed class OpenIddictClientSystemIntegrationConfiguration : IConfigureO
// Note: on Windows, the name is deliberately prefixed with "LOCAL\" to support // Note: on Windows, the name is deliberately prefixed with "LOCAL\" to support
// partial trust/sandboxed applications that are executed in an AppContainer // partial trust/sandboxed applications that are executed in an AppContainer
// and cannot communicate with applications outside the sandbox container. // and cannot communicate with applications outside the sandbox container.
options.PipeName = OperatingSystem.IsWindows() ? options.PipeName = OperatingSystem.IsWindows()
@$"LOCAL\{options.ApplicationDiscriminator}" : ? @$"LOCAL\{options.ApplicationDiscriminator}"
options.ApplicationDiscriminator; : options.ApplicationDiscriminator;
} }
#if NET #if NET

4
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Authentication.cs

@ -636,8 +636,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ?? var response = context.Transaction.GetHttpListenerContext()?.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// Always return a 200 status, even for responses indicating that the authentication failed. // Always return a 200 status, even for responses indicating that the authentication failed.
response.StatusCode = 200; response.StatusCode = 200;

4
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.Session.cs

@ -636,8 +636,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ?? var response = context.Transaction.GetHttpListenerContext()?.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// Always return a 200 status, even for responses indicating that the authentication failed. // Always return a 200 status, even for responses indicating that the authentication failed.
response.StatusCode = 200; response.StatusCode = 200;

24
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs

@ -320,8 +320,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ?? var response = context.Transaction.GetHttpListenerContext()?.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// Unlike the ASP.NET Core or OWIN hosts, the embedded server instantiated by the system // Unlike the ASP.NET Core or OWIN hosts, the embedded server instantiated by the system
// integration is not meant to handle requests pointing to user-defined HTTP endpoints. // integration is not meant to handle requests pointing to user-defined HTTP endpoints.
@ -362,8 +362,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpListenerContext()?.Request ?? var request = context.Transaction.GetHttpListenerContext()?.Request
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// If the incoming request doesn't use GET, reject it. // If the incoming request doesn't use GET, reject it.
if (!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) if (!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
@ -412,8 +412,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpListenerContext()?.Request ?? var request = context.Transaction.GetHttpListenerContext()?.Request
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
if (string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) if (string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{ {
@ -1152,8 +1152,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.StateTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var activation = context.Transaction.GetProtocolActivation() ?? var activation = context.Transaction.GetProtocolActivation()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0375)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0375));
var identifier = context.StateTokenPrincipal.GetClaim(Claims.Private.InstanceId); var identifier = context.StateTokenPrincipal.GetClaim(Claims.Private.InstanceId);
if (string.IsNullOrEmpty(identifier)) if (string.IsNullOrEmpty(identifier))
@ -1942,8 +1942,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ?? var response = context.Transaction.GetHttpListenerContext()?.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -1982,8 +1982,8 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
// This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved, // This handler only applies to HTTP listener requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpListenerContext()?.Response ?? var response = context.Transaction.GetHttpListenerContext()?.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0390)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0390));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[Headers.CacheControl] = "no-store"; response.Headers[Headers.CacheControl] = "no-store";

6
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHttpListener.cs

@ -208,9 +208,9 @@ public sealed class OpenIddictClientSystemIntegrationHttpListener : BackgroundSe
} }
} }
throw exceptions is { Count: > 0 } ? throw exceptions is { Count: > 0 }
new InvalidOperationException(SR.GetResourceString(SR.ID0391), new AggregateException(exceptions.Take(3))) : ? new InvalidOperationException(SR.GetResourceString(SR.ID0391), new AggregateException(exceptions.Take(3)))
new InvalidOperationException(SR.GetResourceString(SR.ID0391)); : new InvalidOperationException(SR.GetResourceString(SR.ID0391));
} }
static async Task ProcessRequestsAsync(HttpListener listener, OpenIddictClientSystemIntegrationService service, static async Task ProcessRequestsAsync(HttpListener listener, OpenIddictClientSystemIntegrationService service,

10
src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationPipeListener.cs

@ -130,11 +130,11 @@ public sealed class OpenIddictClientSystemIntegrationPipeListener : BackgroundSe
static NamedPipeServerStream CreatePipeServerStream(OpenIddictClientSystemIntegrationOptions options) static NamedPipeServerStream CreatePipeServerStream(OpenIddictClientSystemIntegrationOptions options)
// Note: the ACL-based PipeSecurity class is only supported on Windows. On other operating systems, // Note: the ACL-based PipeSecurity class is only supported on Windows. On other operating systems,
// PipeOptions.CurrentUserOnly can be used as an alternative, but only for TFMs that implement it. // PipeOptions.CurrentUserOnly can be used as an alternative, but only for TFMs that implement it.
=> OperatingSystem.IsWindows() ? => OperatingSystem.IsWindows()
#if NET #if NET
NamedPipeServerStreamAcl.Create( ? NamedPipeServerStreamAcl.Create(
#else #else
new NamedPipeServerStream( ? new NamedPipeServerStream(
#endif #endif
pipeName : $@"{options.PipeName}-{options.InstanceIdentifier}", pipeName : $@"{options.PipeName}-{options.InstanceIdentifier}",
direction : PipeDirection.In, direction : PipeDirection.In,
@ -145,8 +145,8 @@ public sealed class OpenIddictClientSystemIntegrationPipeListener : BackgroundSe
outBufferSize : 0, outBufferSize : 0,
pipeSecurity : options.PipeSecurity, pipeSecurity : options.PipeSecurity,
inheritability : HandleInheritability.None, inheritability : HandleInheritability.None,
additionalAccessRights : default) : additionalAccessRights : default)
new NamedPipeServerStream( : new NamedPipeServerStream(
pipeName : $@"{options.PipeName}-{options.InstanceIdentifier}", pipeName : $@"{options.PipeName}-{options.InstanceIdentifier}",
direction : PipeDirection.In, direction : PipeDirection.In,
maxNumberOfServerInstances: NamedPipeServerStream.MaxAllowedServerInstances, maxNumberOfServerInstances: NamedPipeServerStream.MaxAllowedServerInstances,

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

@ -76,8 +76,8 @@ public sealed class OpenIddictClientSystemNetHttpConfiguration : IConfigureOptio
// To work around this limitation, the OpenIddict System.Net.Http integration uses // To work around this limitation, the OpenIddict System.Net.Http integration uses
// an async-local context to flow per-instance properties and uses dynamic client // an async-local context to flow per-instance properties and uses dynamic client
// names to ensure the inner HttpClientHandler is not reused if the context differs. // names to ensure the inner HttpClientHandler is not reused if the context differs.
var context = OpenIddictClientSystemNetHttpContext.Current ?? var context = OpenIddictClientSystemNetHttpContext.Current
throw new InvalidOperationException(SR.FormatID0516(nameof(OpenIddictClientSystemNetHttpContext))); ?? throw new InvalidOperationException(SR.FormatID0516(nameof(OpenIddictClientSystemNetHttpContext)));
var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientSystemNetHttpOptions>>().CurrentValue; var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientSystemNetHttpOptions>>().CurrentValue;
@ -141,8 +141,8 @@ public sealed class OpenIddictClientSystemNetHttpConfiguration : IConfigureOptio
foreach (var action in settings.HttpClientHandlerActions) foreach (var action in settings.HttpClientHandlerActions)
{ {
options.HttpMessageHandlerBuilderActions.Add(builder => action(context.Registration, options.HttpMessageHandlerBuilderActions.Add(builder => action(context.Registration,
builder.PrimaryHandler as HttpClientHandler ?? builder.PrimaryHandler as HttpClientHandler
throw new InvalidOperationException(SR.FormatID0373(typeof(HttpClientHandler).FullName)))); ?? throw new InvalidOperationException(SR.FormatID0373(typeof(HttpClientHandler).FullName))));
} }
} }

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

@ -68,8 +68,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Attach the authorization header containing the access token to the HTTP request. // Attach the authorization header containing the access token to the HTTP request.
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.Request.AccessToken); request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, context.Request.AccessToken);
@ -110,8 +110,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// The status code is deliberately not validated to ensure even errored responses // The status code is deliberately not validated to ensure even errored responses
// (typically in the 4xx range) can be deserialized and handled by the event handlers. // (typically in the 4xx range) can be deserialized and handled by the event handlers.

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

@ -85,8 +85,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
var identifier = OpenIddictClientSystemNetHttpContext.ComputeStableId(OpenIddictClientSystemNetHttpContext.Current); var identifier = OpenIddictClientSystemNetHttpContext.ComputeStableId(OpenIddictClientSystemNetHttpContext.Current);
var client = _factory.CreateClient( var client = _factory.CreateClient(
$"{typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName().Name}:{identifier}") ?? $"{typeof(OpenIddictClientSystemNetHttpOptions).Assembly.GetName().Name}:{identifier}")
throw new InvalidOperationException(SR.GetResourceString(SR.ID0174)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0174));
// Create and store the HttpClient in the transaction properties. // Create and store the HttpClient in the transaction properties.
context.Transaction.SetProperty(typeof(HttpClient).FullName!, client); context.Transaction.SetProperty(typeof(HttpClient).FullName!, client);
@ -183,11 +183,11 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
#if NET #if NET
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
var client = context.Transaction.GetHttpClient() ?? var client = context.Transaction.GetHttpClient()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
// When supported, import the HTTP version and version policy from the client instance. // When supported, import the HTTP version and version policy from the client instance.
request.Version = client.DefaultRequestVersion; request.Version = client.DefaultRequestVersion;
@ -221,8 +221,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypes.Json)); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypes.Json));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue(Charsets.Utf8)); request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue(Charsets.Utf8));
@ -263,8 +263,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Some authorization servers are known to aggressively check user agents and encourage // Some authorization servers are known to aggressively check user agents and encourage
// developers to use unique user agents. While a default user agent is always added, // developers to use unique user agents. While a default user agent is always added,
@ -314,8 +314,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Attach the contact address specified in the options, if available. // Attach the contact address specified in the options, if available.
request.Headers.From = _options.CurrentValue.ContactAddress?.ToString(); request.Headers.From = _options.CurrentValue.ContactAddress?.ToString();
@ -349,8 +349,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: don't overwrite the authorization header if one was already set by another handler. // Note: don't overwrite the authorization header if one was already set by another handler.
if (request.Headers.Authorization is null && if (request.Headers.Authorization is null &&
@ -403,8 +403,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (context.Transaction.Request.Count is 0) if (context.Transaction.Request.Count is 0)
{ {
@ -458,12 +458,12 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: a "using" statement is deliberately used here to dispose of the client in this handler. // Note: a "using" statement is deliberately used here to dispose of the client in this handler.
using var client = context.Transaction.GetHttpClient() ?? using var client = context.Transaction.GetHttpClient()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
HttpResponseMessage response; HttpResponseMessage response;
@ -491,8 +491,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
} }
// 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
throw new InvalidOperationException(SR.GetResourceString(SR.ID0175))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0175)));
} }
} }
@ -519,8 +519,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Dispose(); request.Dispose();
@ -576,8 +576,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If no Content-Encoding header was returned, keep the response stream as-is. // If no Content-Encoding header was returned, keep the response stream as-is.
if (response.Content is not { Headers.ContentEncoding.Count: > 0 }) if (response.Content is not { Headers.ContentEncoding.Count: > 0 })
@ -702,8 +702,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If the returned Content-Type doesn't indicate the response has a JSON payload, // If the returned Content-Type doesn't indicate the response has a JSON payload,
// ignore it and allow other handlers in the pipeline to process the HTTP response. // ignore it and allow other handlers in the pipeline to process the HTTP response.
@ -778,8 +778,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (response.Headers.WwwAuthenticate.Count is 0) if (response.Headers.WwwAuthenticate.Count is 0)
{ {
@ -904,8 +904,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Only process an empty response if no Content-Type header is attached to the // Only process an empty response if no Content-Type header is attached to the
// HTTP response and the Content-Length header is not present or set to 0. // HTTP response and the Content-Length header is not present or set to 0.
@ -941,8 +941,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// At this stage, return a generic error based on the HTTP status code if no // At this stage, return a generic error based on the HTTP status code if no
// error could be extracted from the payload or from the WWW-Authenticate header. // error could be extracted from the payload or from the WWW-Authenticate header.
@ -1008,8 +1008,8 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
response.Dispose(); response.Dispose();

16
src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Exchange.cs

@ -146,8 +146,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// These providers don't implement the standard version of the client_secret_basic // These providers don't implement the standard version of the client_secret_basic
// authentication method as they don't support formURL-encoding the client credentials. // authentication method as they don't support formURL-encoding the client credentials.
@ -197,8 +197,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// HeyBoxChat requires a "token" header containing the Bot token. // HeyBoxChat requires a "token" header containing the Bot token.
if (context.Registration.ProviderType is ProviderTypes.HeyBoxChat) if (context.Registration.ProviderType is ProviderTypes.HeyBoxChat)
@ -246,8 +246,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (request.RequestUri is null) if (request.RequestUri is null)
{ {
@ -306,8 +306,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Content = context.Registration.ProviderType switch request.Content = context.Registration.ProviderType switch
{ {

16
src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Revocation.cs

@ -61,8 +61,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Content = context.Registration.ProviderType switch request.Content = context.Registration.ProviderType switch
{ {
@ -165,8 +165,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Method = context.Registration.ProviderType switch request.Method = context.Registration.ProviderType switch
{ {
@ -203,8 +203,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Zendesk requires using bearer authentication with the token that is going to be revoked. // Zendesk requires using bearer authentication with the token that is going to be revoked.
if (context.Registration.ProviderType is ProviderTypes.Zendesk) if (context.Registration.ProviderType is ProviderTypes.Zendesk)
@ -252,8 +252,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (response.Content is null) if (response.Content is null)
{ {

88
src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.Userinfo.cs

@ -63,8 +63,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Method = context.Registration.ProviderType switch request.Method = context.Registration.ProviderType switch
{ {
@ -107,8 +107,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Bungie.net requires sending a static API key. // Bungie.net requires sending a static API key.
if (context.Registration.ProviderType is ProviderTypes.BungieNet) if (context.Registration.ProviderType is ProviderTypes.BungieNet)
@ -167,8 +167,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// By default, OpenIddict sends the access token as part of the Authorization header // By default, OpenIddict sends the access token as part of the Authorization header
// using the Bearer authentication scheme. Some providers don't support this method // using the Bearer authentication scheme. Some providers don't support this method
@ -268,8 +268,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Content = context.Registration.ProviderType switch request.Content = context.Registration.ProviderType switch
{ {
@ -314,8 +314,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (response.Content is null) if (response.Content is null)
{ {
@ -384,85 +384,85 @@ public static partial class OpenIddictClientWebIntegrationHandlers
context.Response = context.Registration.ProviderType switch context.Response = context.Registration.ProviderType switch
{ {
// Basecamp returns a nested "identity" object and a collection of "accounts". // Basecamp returns a nested "identity" object and a collection of "accounts".
ProviderTypes.Basecamp => new(context.Response["identity"]?.GetNamedParameters() ?? ProviderTypes.Basecamp => new(context.Response["identity"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("identity"))) ?? throw new InvalidOperationException(SR.FormatID0334("identity")))
{ {
["accounts"] = context.Response["accounts"] ["accounts"] = context.Response["accounts"]
}, },
// Bungie.net returns a nested "bungieNetUser" object that is itself nested in a "Response" object. // Bungie.net returns a nested "bungieNetUser" object that is itself nested in a "Response" object.
ProviderTypes.BungieNet => new(context.Response["Response"]?["bungieNetUser"]?.GetNamedParameters() ?? ProviderTypes.BungieNet => new(context.Response["Response"]?["bungieNetUser"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("Response/bungieNetUser"))), ?? throw new InvalidOperationException(SR.FormatID0334("Response/bungieNetUser"))),
// Calendly returns a nested "resource" object. // Calendly returns a nested "resource" object.
ProviderTypes.Calendly => new(context.Response["resource"]?.GetNamedParameters() ?? ProviderTypes.Calendly => new(context.Response["resource"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("resource"))), ?? throw new InvalidOperationException(SR.FormatID0334("resource"))),
// Disqus returns a nested "response" object. // Disqus returns a nested "response" object.
ProviderTypes.Disqus => new(context.Response["response"]?.GetNamedParameters() ?? ProviderTypes.Disqus => new(context.Response["response"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("response"))), ?? throw new InvalidOperationException(SR.FormatID0334("response"))),
// Exact Online returns a "results" array nested in a "d" node and containing a single element. // Exact Online returns a "results" array nested in a "d" node and containing a single element.
ProviderTypes.ExactOnline => new(context.Response["d"]?["results"]?[0]?.GetNamedParameters() ?? ProviderTypes.ExactOnline => new(context.Response["d"]?["results"]?[0]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("d/results/0"))), ?? throw new InvalidOperationException(SR.FormatID0334("d/results/0"))),
// These providers return a nested "user" object. // These providers return a nested "user" object.
ProviderTypes.Fitbit or ProviderTypes.Todoist or ProviderTypes.VkId or ProviderTypes.Zendesk ProviderTypes.Fitbit or ProviderTypes.Todoist or ProviderTypes.VkId or ProviderTypes.Zendesk
=> new(context.Response["user"]?.GetNamedParameters() ?? => new(context.Response["user"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("user"))), ?? throw new InvalidOperationException(SR.FormatID0334("user"))),
// Harvest returns a nested "user" object and a collection of "accounts". // Harvest returns a nested "user" object and a collection of "accounts".
ProviderTypes.Harvest => new(context.Response["user"]?.GetNamedParameters() ?? ProviderTypes.Harvest => new(context.Response["user"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("user"))) ?? throw new InvalidOperationException(SR.FormatID0334("user")))
{ {
["accounts"] = context.Response["accounts"] ["accounts"] = context.Response["accounts"]
}, },
// HeyBoxChat returns a nested "result" object. // HeyBoxChat returns a nested "result" object.
ProviderTypes.HeyBoxChat => new(context.Response["result"]?.GetNamedParameters() ?? ProviderTypes.HeyBoxChat => new(context.Response["result"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("result"))), ?? throw new InvalidOperationException(SR.FormatID0334("result"))),
// These providers return a nested "data" object. // These providers return a nested "data" object.
ProviderTypes.Kook or ProviderTypes.Kroger or ProviderTypes.Kook or ProviderTypes.Kroger or
ProviderTypes.Patreon or ProviderTypes.Pipedrive or ProviderTypes.Twitter ProviderTypes.Patreon or ProviderTypes.Pipedrive or ProviderTypes.Twitter
=> new(context.Response["data"]?.GetNamedParameters() ?? => new(context.Response["data"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("data"))), ?? throw new InvalidOperationException(SR.FormatID0334("data"))),
// Linear returns a nested "viewer" object that is itself nested in a GraphQL "data" node. // Linear returns a nested "viewer" object that is itself nested in a GraphQL "data" node.
ProviderTypes.Linear => new(context.Response["data"]?["viewer"]?.GetNamedParameters() ?? ProviderTypes.Linear => new(context.Response["data"]?["viewer"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("data/viewer"))), ?? throw new InvalidOperationException(SR.FormatID0334("data/viewer"))),
// Meetup returns a nested "self" object that is itself nested in a GraphQL "data" node. // Meetup returns a nested "self" object that is itself nested in a GraphQL "data" node.
ProviderTypes.Meetup => new(context.Response["data"]?["self"]?.GetNamedParameters() ?? ProviderTypes.Meetup => new(context.Response["data"]?["self"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("data/self"))), ?? throw new InvalidOperationException(SR.FormatID0334("data/self"))),
// Miro returns a nested "user" object, as well as a nested "team" and "organization". // Miro returns a nested "user" object, as well as a nested "team" and "organization".
ProviderTypes.Miro => new(context.Response["user"]?.GetNamedParameters() ?? ProviderTypes.Miro => new(context.Response["user"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("user"))) ?? throw new InvalidOperationException(SR.FormatID0334("user")))
{ {
["organization"] = context.Response["organization"], ["organization"] = context.Response["organization"],
["team"] = context.Response["team"] ["team"] = context.Response["team"]
}, },
// Nextcloud returns a nested "data" object that is itself nested in a "ocs" node. // Nextcloud returns a nested "data" object that is itself nested in a "ocs" node.
ProviderTypes.Nextcloud => new(context.Response["ocs"]?["data"]?.GetNamedParameters() ?? ProviderTypes.Nextcloud => new(context.Response["ocs"]?["data"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("ocs/data"))), ?? throw new InvalidOperationException(SR.FormatID0334("ocs/data"))),
// ServiceChannel returns a nested "UserProfile" object. // ServiceChannel returns a nested "UserProfile" object.
ProviderTypes.ServiceChannel => new(context.Response["UserProfile"]?.GetNamedParameters() ?? ProviderTypes.ServiceChannel => new(context.Response["UserProfile"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("UserProfile"))), ?? throw new InvalidOperationException(SR.FormatID0334("UserProfile"))),
// StackExchange returns an "items" array containing a single element. // StackExchange returns an "items" array containing a single element.
ProviderTypes.StackExchange => new(context.Response["items"]?[0]?.GetNamedParameters() ?? ProviderTypes.StackExchange => new(context.Response["items"]?[0]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("items/0"))), ?? throw new InvalidOperationException(SR.FormatID0334("items/0"))),
// SubscribeStar returns a nested "user" object that is itself nested in a GraphQL "data" node. // SubscribeStar returns a nested "user" object that is itself nested in a GraphQL "data" node.
ProviderTypes.SubscribeStar => new(context.Response["data"]?["user"]?.GetNamedParameters() ?? ProviderTypes.SubscribeStar => new(context.Response["data"]?["user"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("data/user"))), ?? throw new InvalidOperationException(SR.FormatID0334("data/user"))),
// Tumblr returns a nested "user" object that is itself nested in a "response" node. // Tumblr returns a nested "user" object that is itself nested in a "response" node.
ProviderTypes.Tumblr => new(context.Response["response"]?["user"]?.GetNamedParameters() ?? ProviderTypes.Tumblr => new(context.Response["response"]?["user"]?.GetNamedParameters()
throw new InvalidOperationException(SR.FormatID0334("response/user"))), ?? throw new InvalidOperationException(SR.FormatID0334("response/user"))),
_ => context.Response _ => context.Response
}; };

20
src/OpenIddict.Client.WebIntegration/OpenIddictClientWebIntegrationHandlers.cs

@ -1358,9 +1358,9 @@ public static partial class OpenIddictClientWebIntegrationHandlers
context.Registration.TokenValidationParameters.RoleClaimType); context.Registration.TokenValidationParameters.RoleClaimType);
// Resolve the issuer that will be attached to the claims created by this handler. // Resolve the issuer that will be attached to the claims created by this handler.
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
@ -1432,9 +1432,9 @@ public static partial class OpenIddictClientWebIntegrationHandlers
return ValueTask.CompletedTask; return ValueTask.CompletedTask;
} }
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
if (!context.MergedPrincipal.HasClaim(ClaimTypes.Email)) if (!context.MergedPrincipal.HasClaim(ClaimTypes.Email))
{ {
@ -1531,8 +1531,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
ProviderTypes.MusicBrainz => (string?) context.UserInfoResponse?["sub"], ProviderTypes.MusicBrainz => (string?) context.UserInfoResponse?["sub"],
// Nextcloud returns the username as a custom "displayname" or "display-name" node: // Nextcloud returns the username as a custom "displayname" or "display-name" node:
ProviderTypes.Nextcloud => (string?) context.UserInfoResponse?["displayname"] ?? ProviderTypes.Nextcloud => (string?) context.UserInfoResponse?["displayname"]
(string?) context.UserInfoResponse?["display-name"], ?? (string?) context.UserInfoResponse?["display-name"],
// Notion returns the username as a custom "bot/owner/user/name" node but // Notion returns the username as a custom "bot/owner/user/name" node but
// requires a special capability to access this node, that may not be present: // requires a special capability to access this node, that may not be present:
@ -1698,8 +1698,8 @@ public static partial class OpenIddictClientWebIntegrationHandlers
if (context.Registration.ProviderType is ProviderTypes.IdAustria) if (context.Registration.ProviderType is ProviderTypes.IdAustria)
{ {
context.MergedPrincipal.SetClaim(ClaimTypes.NameIdentifier, context.MergedPrincipal.SetClaim(ClaimTypes.NameIdentifier,
context.BackchannelIdentityTokenPrincipal?.GetClaim("urn:pvpgvat:oidc.bpk") ?? context.BackchannelIdentityTokenPrincipal?.GetClaim("urn:pvpgvat:oidc.bpk")
context.FrontchannelIdentityTokenPrincipal?.GetClaim("urn:pvpgvat:oidc.bpk")); ?? context.FrontchannelIdentityTokenPrincipal?.GetClaim("urn:pvpgvat:oidc.bpk"));
} }
return ValueTask.CompletedTask; return ValueTask.CompletedTask;

44
src/OpenIddict.Client/OpenIddictClientBuilder.cs

@ -349,9 +349,9 @@ public sealed class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
public OpenIddictClientBuilder AddEncryptionCertificate(Assembly assembly, string resource, string? password) public OpenIddictClientBuilder AddEncryptionCertificate(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate retrieved from an embedded resource. /// Registers an encryption certificate retrieved from an embedded resource.
@ -368,8 +368,8 @@ public sealed class OpenIddictClientBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -382,9 +382,9 @@ public sealed class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
public OpenIddictClientBuilder AddEncryptionCertificate(Stream stream, string? password) public OpenIddictClientBuilder AddEncryptionCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate extracted from a stream. /// Registers an encryption certificate extracted from a stream.
@ -421,9 +421,9 @@ public sealed class OpenIddictClientBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddEncryptionCertificate( return AddEncryptionCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -745,9 +745,9 @@ public sealed class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
public OpenIddictClientBuilder AddSigningCertificate(Assembly assembly, string resource, string? password) public OpenIddictClientBuilder AddSigningCertificate(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate retrieved from an embedded resource. /// Registers a signing certificate retrieved from an embedded resource.
@ -764,8 +764,8 @@ public sealed class OpenIddictClientBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddSigningCertificate(stream, password, flags); return AddSigningCertificate(stream, password, flags);
} }
@ -778,9 +778,9 @@ public sealed class OpenIddictClientBuilder
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
public OpenIddictClientBuilder AddSigningCertificate(Stream stream, string? password) public OpenIddictClientBuilder AddSigningCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate extracted from a stream. /// Registers a signing certificate extracted from a stream.
@ -817,9 +817,9 @@ public sealed class OpenIddictClientBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddSigningCertificate( return AddSigningCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {

28
src/OpenIddict.Client/OpenIddictClientHandlerDescriptor.cs

@ -158,8 +158,11 @@ public sealed class OpenIddictClientHandlerDescriptor
/// <param name="handler">The handler instance.</param> /// <param name="handler">The handler instance.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler) public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler)
=> UseSingletonHandler(new OpenIddictClientHandler<TContext>(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return UseSingletonHandler(new OpenIddictClientHandler<TContext>(handler));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified scoped handler. /// Configures the descriptor to use the specified scoped handler.
@ -179,8 +182,11 @@ public sealed class OpenIddictClientHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictClientHandler<TContext> where THandler : class, IOpenIddictClientHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Scoped(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Scoped(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -200,8 +206,11 @@ public sealed class OpenIddictClientHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictClientHandler<TContext> where THandler : class, IOpenIddictClientHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Singleton(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -211,8 +220,11 @@ public sealed class OpenIddictClientHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(THandler handler) public Builder<TContext> UseSingletonHandler<THandler>(THandler handler)
where THandler : class, IOpenIddictClientHandler<TContext> where THandler : class, IOpenIddictClientHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return SetServiceDescriptor(ServiceDescriptor.Singleton(handler));
}
/// <summary> /// <summary>
/// Build a new descriptor instance, based on the parameters that were previously set. /// Build a new descriptor instance, based on the parameters that were previously set.

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

@ -374,20 +374,20 @@ public static partial class OpenIddictClientHandlers
// //
// Note: if WS-Federation claim mapping was not disabled, the resulting identity // Note: if WS-Federation claim mapping was not disabled, the resulting identity
// will use the default WS-Federation claims as the name/role claim types. // will use the default WS-Federation claims as the name/role claim types.
var identity = context.Options.DisableWebServicesFederationClaimMapping ? var identity = context.Options.DisableWebServicesFederationClaimMapping
new ClaimsIdentity( ? new ClaimsIdentity(
context.Registration.TokenValidationParameters.AuthenticationType, context.Registration.TokenValidationParameters.AuthenticationType,
context.Registration.TokenValidationParameters.NameClaimType, context.Registration.TokenValidationParameters.NameClaimType,
context.Registration.TokenValidationParameters.RoleClaimType) : context.Registration.TokenValidationParameters.RoleClaimType)
new ClaimsIdentity( : new ClaimsIdentity(
context.Registration.TokenValidationParameters.AuthenticationType, context.Registration.TokenValidationParameters.AuthenticationType,
nameType: ClaimTypes.Name, nameType: ClaimTypes.Name,
roleType: ClaimTypes.Role); roleType: ClaimTypes.Role);
// Resolve the issuer that will be attached to the claims created by this handler. // Resolve the issuer that will be attached to the claims created by this handler.
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
foreach (var parameter in context.Response.GetParameters()) foreach (var parameter in context.Response.GetParameters())
{ {

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

@ -851,8 +851,8 @@ public static partial class OpenIddictClientHandlers
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017)); Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017));
var token = await _tokenManager.FindByIdAsync(context.TokenId) ?? var token = await _tokenManager.FindByIdAsync(context.TokenId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
if (await _tokenManager.HasStatusAsync(token, Statuses.Redeemed)) if (await _tokenManager.HasStatusAsync(token, Statuses.Redeemed))
{ {
@ -980,8 +980,8 @@ public static partial class OpenIddictClientHandlers
// Tokens produced by the client stack cannot have an application attached. // Tokens produced by the client stack cannot have an application attached.
var token = await _tokenManager.CreateAsync(descriptor) ?? var token = await _tokenManager.CreateAsync(descriptor)
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);
@ -1058,9 +1058,9 @@ public static partial class OpenIddictClientHandlers
{ {
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var claims = context.SecurityTokenDescriptor.Claims is not null ? var claims = context.SecurityTokenDescriptor.Claims is not null
new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal) : ? new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal)
new Dictionary<string, object>(StringComparer.Ordinal); : new Dictionary<string, object>(StringComparer.Ordinal);
// For client assertions, set the public audience claims // For client assertions, set the public audience claims
// using the private audience claims from the security principal. // using the private audience claims from the security principal.
@ -1172,8 +1172,8 @@ public static partial class OpenIddictClientHandlers
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)
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);

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

@ -168,9 +168,9 @@ public static partial class OpenIddictClientHandlers
context.Registration.TokenValidationParameters.RoleClaimType); context.Registration.TokenValidationParameters.RoleClaimType);
// Resolve the issuer that will be attached to the claims created by this handler. // Resolve the issuer that will be attached to the claims created by this handler.
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
foreach (var parameter in context.Response.GetParameters()) foreach (var parameter in context.Response.GetParameters())
{ {

77
src/OpenIddict.Client/OpenIddictClientHandlers.cs

@ -417,9 +417,9 @@ public static partial class OpenIddictClientHandlers
context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) && context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) &&
context.Options.Registrations.Count is not 1) context.Options.Registrations.Count is not 1)
{ {
throw context.Options.Registrations.Count is 0 ? throw context.Options.Registrations.Count is 0
new InvalidOperationException(SR.GetResourceString(SR.ID0304)) : ? new InvalidOperationException(SR.GetResourceString(SR.ID0304))
new InvalidOperationException(SR.GetResourceString(SR.ID0355)); : new InvalidOperationException(SR.GetResourceString(SR.ID0355));
} }
break; break;
@ -525,8 +525,8 @@ public static partial class OpenIddictClientHandlers
{ {
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&
@ -1148,8 +1148,8 @@ public static partial class OpenIddictClientHandlers
// Resolve and attach the server configuration to the context. // Resolve and attach the server configuration to the context.
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&
@ -1521,8 +1521,9 @@ public static partial class OpenIddictClientHandlers
context.FrontchannelAccessTokenExpirationDate = context.EndpointType switch context.FrontchannelAccessTokenExpirationDate = context.EndpointType switch
{ {
OpenIddictClientEndpointType.Redirection when context.ExtractFrontchannelAccessToken OpenIddictClientEndpointType.Redirection when context.ExtractFrontchannelAccessToken
=> (long?) context.Request[Parameters.ExpiresIn] is long value ? => (long?) context.Request[Parameters.ExpiresIn] is long value
context.Options.TimeProvider.GetUtcNow().AddSeconds(value) : null, ? context.Options.TimeProvider.GetUtcNow().AddSeconds(value)
: null,
_ => null _ => null
}; };
@ -4267,8 +4268,8 @@ public static partial class OpenIddictClientHandlers
// the backchannel access token (retrieved from the token endpoint) is always preferred to the // the backchannel access token (retrieved from the token endpoint) is always preferred to the
// frontchannel access token if available, as it may grant a greater access to user's resources. // frontchannel access token if available, as it may grant a greater access to user's resources.
GrantTypes.AuthorizationCode or GrantTypes.Implicit GrantTypes.AuthorizationCode or GrantTypes.Implicit
=> context.BackchannelAccessToken ?? context.FrontchannelAccessToken ?? => context.BackchannelAccessToken ?? context.FrontchannelAccessToken
throw new InvalidOperationException(SR.GetResourceString(SR.ID0162)), ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0162)),
// For the OAuth 2.0 token exchange flow, use the issued token as the access token, // For the OAuth 2.0 token exchange flow, use the issued token as the access token,
// but only if the "issued_token_type" node indicates it's an access token. // but only if the "issued_token_type" node indicates it's an access token.
@ -4687,12 +4688,12 @@ public static partial class OpenIddictClientHandlers
// //
// Note: if WS-Federation claim mapping was not disabled, the resulting identity // Note: if WS-Federation claim mapping was not disabled, the resulting identity
// will use the default WS-Federation claims as the name/role claim types. // will use the default WS-Federation claims as the name/role claim types.
var identity = context.Options.DisableWebServicesFederationClaimMapping ? var identity = context.Options.DisableWebServicesFederationClaimMapping
new ClaimsIdentity( ? new ClaimsIdentity(
context.Registration.TokenValidationParameters.AuthenticationType, context.Registration.TokenValidationParameters.AuthenticationType,
context.Registration.TokenValidationParameters.NameClaimType, context.Registration.TokenValidationParameters.NameClaimType,
context.Registration.TokenValidationParameters.RoleClaimType) : context.Registration.TokenValidationParameters.RoleClaimType)
new ClaimsIdentity( : new ClaimsIdentity(
context.Registration.TokenValidationParameters.AuthenticationType, context.Registration.TokenValidationParameters.AuthenticationType,
nameType: ClaimTypes.Name, nameType: ClaimTypes.Name,
roleType: ClaimTypes.Role); roleType: ClaimTypes.Role);
@ -4769,9 +4770,9 @@ public static partial class OpenIddictClientHandlers
return ValueTask.CompletedTask; return ValueTask.CompletedTask;
} }
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
MapClaim(ClaimTypes.Email, ClaimValueTypes.String, [Claims.Email]); MapClaim(ClaimTypes.Email, ClaimValueTypes.String, [Claims.Email]);
MapClaim(ClaimTypes.Gender, ClaimValueTypes.String, [Claims.Gender]); MapClaim(ClaimTypes.Gender, ClaimValueTypes.String, [Claims.Gender]);
@ -4883,9 +4884,9 @@ public static partial class OpenIddictClientHandlers
context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) && context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) &&
context.Options.Registrations.Count is not 1) context.Options.Registrations.Count is not 1)
{ {
throw context.Options.Registrations.Count is 0 ? throw context.Options.Registrations.Count is 0
new InvalidOperationException(SR.GetResourceString(SR.ID0304)) : ? new InvalidOperationException(SR.GetResourceString(SR.ID0304))
new InvalidOperationException(SR.GetResourceString(SR.ID0305)); : new InvalidOperationException(SR.GetResourceString(SR.ID0305));
} }
if (context.Principal is not { Identity: ClaimsIdentity }) if (context.Principal is not { Identity: ClaimsIdentity })
@ -5012,8 +5013,8 @@ public static partial class OpenIddictClientHandlers
{ {
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&
@ -7341,9 +7342,9 @@ public static partial class OpenIddictClientHandlers
context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) && context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) &&
context.Options.Registrations.Count is not 1) context.Options.Registrations.Count is not 1)
{ {
throw context.Options.Registrations.Count is 0 ? throw context.Options.Registrations.Count is 0
new InvalidOperationException(SR.GetResourceString(SR.ID0304)) : ? new InvalidOperationException(SR.GetResourceString(SR.ID0304))
new InvalidOperationException(SR.GetResourceString(SR.ID0305)); : new InvalidOperationException(SR.GetResourceString(SR.ID0305));
} }
return ValueTask.CompletedTask; return ValueTask.CompletedTask;
@ -7425,8 +7426,8 @@ public static partial class OpenIddictClientHandlers
{ {
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&
@ -8081,9 +8082,9 @@ public static partial class OpenIddictClientHandlers
return ValueTask.CompletedTask; return ValueTask.CompletedTask;
} }
var issuer = context.Registration.ClaimsIssuer ?? var issuer = context.Registration.ClaimsIssuer
context.Registration.ProviderName ?? ?? context.Registration.ProviderName
context.Registration.Issuer.AbsoluteUri; ?? context.Registration.Issuer.AbsoluteUri;
MapClaim(ClaimTypes.Name, ClaimValueTypes.String, [Claims.Username]); MapClaim(ClaimTypes.Name, ClaimValueTypes.String, [Claims.Username]);
MapClaim(ClaimTypes.NameIdentifier, ClaimValueTypes.String, [Claims.Subject]); MapClaim(ClaimTypes.NameIdentifier, ClaimValueTypes.String, [Claims.Subject]);
@ -8230,8 +8231,8 @@ public static partial class OpenIddictClientHandlers
{ {
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&
@ -8884,9 +8885,9 @@ public static partial class OpenIddictClientHandlers
context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) && context.Issuer is null && string.IsNullOrEmpty(context.ProviderName) &&
context.Options.Registrations.Count is not 1) context.Options.Registrations.Count is not 1)
{ {
throw context.Options.Registrations.Count is 0 ? throw context.Options.Registrations.Count is 0
new InvalidOperationException(SR.GetResourceString(SR.ID0304)) : ? new InvalidOperationException(SR.GetResourceString(SR.ID0304))
new InvalidOperationException(SR.GetResourceString(SR.ID0305)); : new InvalidOperationException(SR.GetResourceString(SR.ID0305));
} }
if (context.Principal is not { Identity: ClaimsIdentity }) if (context.Principal is not { Identity: ClaimsIdentity })
@ -9013,8 +9014,8 @@ public static partial class OpenIddictClientHandlers
{ {
context.Configuration = await context.Registration.ConfigurationManager context.Configuration = await context.Registration.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&

8
src/OpenIddict.Client/OpenIddictClientRetriever.cs

@ -48,16 +48,16 @@ public sealed class OpenIddictClientRetriever : IConfigurationRetriever<OpenIddi
cancel.ThrowIfCancellationRequested(); cancel.ThrowIfCancellationRequested();
var configuration = await _service.GetConfigurationAsync(_registration, uri, cancel) ?? var configuration = await _service.GetConfigurationAsync(_registration, uri, cancel)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
if (configuration.JsonWebKeySetUri is null) if (configuration.JsonWebKeySetUri is null)
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0146)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0146));
} }
configuration.JsonWebKeySet = await _service.GetSecurityKeysAsync(_registration, configuration.JsonWebKeySetUri, cancel) ?? configuration.JsonWebKeySet = await _service.GetSecurityKeysAsync(_registration, configuration.JsonWebKeySetUri, cancel)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
// Copy the signing keys found in the JSON Web Key Set to the SigningKeys collection. // Copy the signing keys found in the JSON Web Key Set to the SigningKeys collection.
foreach (var key in configuration.JsonWebKeySet.GetSigningKeys()) foreach (var key in configuration.JsonWebKeySet.GetSigningKeys())

24
src/OpenIddict.Client/OpenIddictClientService.cs

@ -151,8 +151,8 @@ public class OpenIddictClientService
var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>(); var options = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
return new(options.CurrentValue.Registrations.Find(registration => string.Equals( return new(options.CurrentValue.Registrations.Find(registration => string.Equals(
registration.RegistrationId, identifier, StringComparison.Ordinal)) ?? registration.RegistrationId, identifier, StringComparison.Ordinal))
throw new InvalidOperationException(SR.GetResourceString(SR.ID0410))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0410)));
} }
/// <summary> /// <summary>
@ -181,8 +181,8 @@ public class OpenIddictClientService
return await registration.ConfigurationManager return await registration.ConfigurationManager
.GetConfigurationAsync(cancellationToken) .GetConfigurationAsync(cancellationToken)
.WaitAsync(cancellationToken) ?? .WaitAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
/// <summary> /// <summary>
@ -211,8 +211,8 @@ public class OpenIddictClientService
return await registration.ConfigurationManager return await registration.ConfigurationManager
.GetConfigurationAsync(cancellationToken) .GetConfigurationAsync(cancellationToken)
.WaitAsync(cancellationToken) ?? .WaitAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
/// <summary> /// <summary>
@ -238,8 +238,8 @@ public class OpenIddictClientService
return await registration.ConfigurationManager return await registration.ConfigurationManager
.GetConfigurationAsync(cancellationToken) .GetConfigurationAsync(cancellationToken)
.WaitAsync(cancellationToken) ?? .WaitAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
/// <summary> /// <summary>
@ -1190,8 +1190,8 @@ public class OpenIddictClientService
request = await ApplyConfigurationRequestAsync(); request = await ApplyConfigurationRequestAsync();
var response = await ExtractConfigurationResponseAsync(); var response = await ExtractConfigurationResponseAsync();
return await HandleConfigurationResponseAsync() ?? return await HandleConfigurationResponseAsync()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync() async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync()
{ {
@ -1387,8 +1387,8 @@ public class OpenIddictClientService
var response = await ExtractJsonWebKeySetResponseAsync(); var response = await ExtractJsonWebKeySetResponseAsync();
return await HandleJsonWebKeySetResponseAsync() ?? return await HandleJsonWebKeySetResponseAsync()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
async ValueTask<OpenIddictRequest> PrepareJsonWebKeySetRequestAsync() async ValueTask<OpenIddictRequest> PrepareJsonWebKeySetRequestAsync()
{ {

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

@ -274,8 +274,8 @@ public sealed class OpenIddictApplicationCache<TApplication> : IOpenIddictApplic
if (application is not null) if (application is not null)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = 1L; entry.Size = 1L;
@ -297,8 +297,8 @@ public sealed class OpenIddictApplicationCache<TApplication> : IOpenIddictApplic
foreach (var application in applications) foreach (var application in applications)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(application, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = applications.Length; entry.Size = applications.Length;

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

@ -238,8 +238,8 @@ public sealed class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAu
if (authorization is not null) if (authorization is not null)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = 1L; entry.Size = 1L;
@ -261,8 +261,8 @@ public sealed class OpenIddictAuthorizationCache<TAuthorization> : IOpenIddictAu
foreach (var authorization in authorizations) foreach (var authorization in authorizations)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(authorization, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = authorizations.Length; entry.Size = authorizations.Length;

8
src/OpenIddict.Core/Caches/OpenIddictResourceCache.cs

@ -200,8 +200,8 @@ public sealed class OpenIddictResourceCache<TResource> : IOpenIddictResourceCach
if (resource is not null) if (resource is not null)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(resource, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(resource, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = 1L; entry.Size = 1L;
@ -223,8 +223,8 @@ public sealed class OpenIddictResourceCache<TResource> : IOpenIddictResourceCach
foreach (var resource in resources) foreach (var resource in resources)
{ {
entry.AddExpirationToken(await CreateExpirationSignalAsync(resource, cancellationToken) ?? entry.AddExpirationToken(await CreateExpirationSignalAsync(resource, cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0197))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0197)));
} }
entry.Size = resources.Length; entry.Size = resources.Length;

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

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

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

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

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

@ -246,8 +246,8 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
{ {
ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(descriptor);
var application = await Store.InstantiateAsync(cancellationToken) ?? var application = await Store.InstantiateAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
await PopulateAsync(application, descriptor, cancellationToken); await PopulateAsync(application, descriptor, cancellationToken);
@ -299,9 +299,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var application = Options.CurrentValue.DisableEntityCaching ? var application = Options.CurrentValue.DisableEntityCaching
await Store.FindByClientIdAsync(identifier, cancellationToken) : ? await Store.FindByClientIdAsync(identifier, cancellationToken)
await Cache.FindByClientIdAsync(identifier, cancellationToken); : await Cache.FindByClientIdAsync(identifier, cancellationToken);
if (application is null) if (application is null)
{ {
@ -333,9 +333,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var application = Options.CurrentValue.DisableEntityCaching ? var application = Options.CurrentValue.DisableEntityCaching
await Store.FindByIdAsync(identifier, cancellationToken) : ? await Store.FindByIdAsync(identifier, cancellationToken)
await Cache.FindByIdAsync(identifier, cancellationToken); : await Cache.FindByIdAsync(identifier, cancellationToken);
if (application is null) if (application is null)
{ {
@ -365,9 +365,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
{ {
ArgumentException.ThrowIfNullOrEmpty(uri); ArgumentException.ThrowIfNullOrEmpty(uri);
var applications = Options.CurrentValue.DisableEntityCaching ? var applications = Options.CurrentValue.DisableEntityCaching
Store.FindByPostLogoutRedirectUriAsync(uri, cancellationToken) : ? Store.FindByPostLogoutRedirectUriAsync(uri, cancellationToken)
Cache.FindByPostLogoutRedirectUriAsync(uri, cancellationToken); : Cache.FindByPostLogoutRedirectUriAsync(uri, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -404,9 +404,9 @@ public class OpenIddictApplicationManager<TApplication> : IOpenIddictApplication
{ {
ArgumentException.ThrowIfNullOrEmpty(uri); ArgumentException.ThrowIfNullOrEmpty(uri);
var applications = Options.CurrentValue.DisableEntityCaching ? var applications = Options.CurrentValue.DisableEntityCaching
Store.FindByRedirectUriAsync(uri, cancellationToken) : ? Store.FindByRedirectUriAsync(uri, cancellationToken)
Cache.FindByRedirectUriAsync(uri, cancellationToken); : Cache.FindByRedirectUriAsync(uri, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {

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

@ -183,8 +183,8 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
{ {
ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(descriptor);
var authorization = await Store.InstantiateAsync(cancellationToken) ?? var authorization = await Store.InstantiateAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
await PopulateAsync(authorization, descriptor, cancellationToken); await PopulateAsync(authorization, descriptor, cancellationToken);
await CreateAsync(authorization, cancellationToken); await CreateAsync(authorization, cancellationToken);
@ -281,9 +281,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
string? status, string? type, string? status, string? type,
ImmutableArray<string>? scopes, CancellationToken cancellationToken = default) ImmutableArray<string>? scopes, CancellationToken cancellationToken = default)
{ {
var authorizations = Options.CurrentValue.DisableEntityCaching ? var authorizations = Options.CurrentValue.DisableEntityCaching
Store.FindAsync(subject, client, status, type, scopes, cancellationToken) : ? Store.FindAsync(subject, client, status, type, scopes, cancellationToken)
Cache.FindAsync(subject, client, status, type, scopes, cancellationToken); : Cache.FindAsync(subject, client, status, type, scopes, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -327,9 +327,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var authorizations = Options.CurrentValue.DisableEntityCaching ? var authorizations = Options.CurrentValue.DisableEntityCaching
Store.FindByApplicationIdAsync(identifier, cancellationToken) : ? Store.FindByApplicationIdAsync(identifier, cancellationToken)
Cache.FindByApplicationIdAsync(identifier, cancellationToken); : Cache.FindByApplicationIdAsync(identifier, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -367,9 +367,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var authorization = Options.CurrentValue.DisableEntityCaching ? var authorization = Options.CurrentValue.DisableEntityCaching
await Store.FindByIdAsync(identifier, cancellationToken) : ? await Store.FindByIdAsync(identifier, cancellationToken)
await Cache.FindByIdAsync(identifier, cancellationToken); : await Cache.FindByIdAsync(identifier, cancellationToken);
if (authorization is null) if (authorization is null)
{ {
@ -399,9 +399,9 @@ public class OpenIddictAuthorizationManager<TAuthorization> : IOpenIddictAuthori
{ {
ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(subject);
var authorizations = Options.CurrentValue.DisableEntityCaching ? var authorizations = Options.CurrentValue.DisableEntityCaching
Store.FindBySubjectAsync(subject, cancellationToken) : ? Store.FindBySubjectAsync(subject, cancellationToken)
Cache.FindBySubjectAsync(subject, cancellationToken); : Cache.FindBySubjectAsync(subject, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {

22
src/OpenIddict.Core/Managers/OpenIddictResourceManager.cs

@ -176,8 +176,8 @@ public class OpenIddictResourceManager<TResource> : IOpenIddictResourceManager w
{ {
ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(descriptor);
var resource = await Store.InstantiateAsync(cancellationToken) ?? var resource = await Store.InstantiateAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
await PopulateAsync(resource, descriptor, cancellationToken); await PopulateAsync(resource, descriptor, cancellationToken);
await CreateAsync(resource, cancellationToken); await CreateAsync(resource, cancellationToken);
@ -218,9 +218,9 @@ public class OpenIddictResourceManager<TResource> : IOpenIddictResourceManager w
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var resource = Options.CurrentValue.DisableEntityCaching ? var resource = Options.CurrentValue.DisableEntityCaching
await Store.FindByIdAsync(identifier, cancellationToken) : ? await Store.FindByIdAsync(identifier, cancellationToken)
await Cache.FindByIdAsync(identifier, cancellationToken); : await Cache.FindByIdAsync(identifier, cancellationToken);
if (resource is null) if (resource is null)
{ {
@ -252,9 +252,9 @@ public class OpenIddictResourceManager<TResource> : IOpenIddictResourceManager w
{ {
ArgumentException.ThrowIfNullOrEmpty(name); ArgumentException.ThrowIfNullOrEmpty(name);
var resource = Options.CurrentValue.DisableEntityCaching ? var resource = Options.CurrentValue.DisableEntityCaching
await Store.FindByNameAsync(name, cancellationToken) : ? await Store.FindByNameAsync(name, cancellationToken)
await Cache.FindByNameAsync(name, cancellationToken); : await Cache.FindByNameAsync(name, cancellationToken);
if (resource is null) if (resource is null)
{ {
@ -288,9 +288,9 @@ public class OpenIddictResourceManager<TResource> : IOpenIddictResourceManager w
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
var resources = Options.CurrentValue.DisableEntityCaching ? var resources = Options.CurrentValue.DisableEntityCaching
Store.FindByNamesAsync(names, cancellationToken) : ? Store.FindByNamesAsync(names, cancellationToken)
Cache.FindByNamesAsync(names, cancellationToken); : Cache.FindByNamesAsync(names, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {

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

@ -176,8 +176,8 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
{ {
ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(descriptor);
var scope = await Store.InstantiateAsync(cancellationToken) ?? var scope = await Store.InstantiateAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
await PopulateAsync(scope, descriptor, cancellationToken); await PopulateAsync(scope, descriptor, cancellationToken);
await CreateAsync(scope, cancellationToken); await CreateAsync(scope, cancellationToken);
@ -218,9 +218,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var scope = Options.CurrentValue.DisableEntityCaching ? var scope = Options.CurrentValue.DisableEntityCaching
await Store.FindByIdAsync(identifier, cancellationToken) : ? await Store.FindByIdAsync(identifier, cancellationToken)
await Cache.FindByIdAsync(identifier, cancellationToken); : await Cache.FindByIdAsync(identifier, cancellationToken);
if (scope is null) if (scope is null)
{ {
@ -252,9 +252,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
{ {
ArgumentException.ThrowIfNullOrEmpty(name); ArgumentException.ThrowIfNullOrEmpty(name);
var scope = Options.CurrentValue.DisableEntityCaching ? var scope = Options.CurrentValue.DisableEntityCaching
await Store.FindByNameAsync(name, cancellationToken) : ? await Store.FindByNameAsync(name, cancellationToken)
await Cache.FindByNameAsync(name, cancellationToken); : await Cache.FindByNameAsync(name, cancellationToken);
if (scope is null) if (scope is null)
{ {
@ -288,9 +288,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names)); throw new ArgumentException(SR.GetResourceString(SR.ID0203), nameof(names));
} }
var scopes = Options.CurrentValue.DisableEntityCaching ? var scopes = Options.CurrentValue.DisableEntityCaching
Store.FindByNamesAsync(names, cancellationToken) : ? Store.FindByNamesAsync(names, cancellationToken)
Cache.FindByNamesAsync(names, cancellationToken); : Cache.FindByNamesAsync(names, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -327,9 +327,9 @@ public class OpenIddictScopeManager<TScope> : IOpenIddictScopeManager where TSco
{ {
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
var scopes = Options.CurrentValue.DisableEntityCaching ? var scopes = Options.CurrentValue.DisableEntityCaching
Store.FindByResourceAsync(resource, cancellationToken) : ? Store.FindByResourceAsync(resource, cancellationToken)
Cache.FindByResourceAsync(resource, cancellationToken); : Cache.FindByResourceAsync(resource, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {

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

@ -191,8 +191,8 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
{ {
ArgumentNullException.ThrowIfNull(descriptor); ArgumentNullException.ThrowIfNull(descriptor);
var token = await Store.InstantiateAsync(cancellationToken) ?? var token = await Store.InstantiateAsync(cancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0208)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0208));
await PopulateAsync(token, descriptor, cancellationToken); await PopulateAsync(token, descriptor, cancellationToken);
await CreateAsync(token, cancellationToken); await CreateAsync(token, cancellationToken);
@ -233,9 +233,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
string? subject, string? client, string? subject, string? client,
string? status, string? type, CancellationToken cancellationToken = default) string? status, string? type, CancellationToken cancellationToken = default)
{ {
var tokens = Options.CurrentValue.DisableEntityCaching ? var tokens = Options.CurrentValue.DisableEntityCaching
Store.FindAsync(subject, client, status, type, cancellationToken) : ? Store.FindAsync(subject, client, status, type, cancellationToken)
Cache.FindAsync(subject, client, status, type, cancellationToken); : Cache.FindAsync(subject, client, status, type, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -272,9 +272,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var tokens = Options.CurrentValue.DisableEntityCaching ? var tokens = Options.CurrentValue.DisableEntityCaching
Store.FindByApplicationIdAsync(identifier, cancellationToken) : ? Store.FindByApplicationIdAsync(identifier, cancellationToken)
Cache.FindByApplicationIdAsync(identifier, cancellationToken); : Cache.FindByApplicationIdAsync(identifier, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -310,9 +310,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var tokens = Options.CurrentValue.DisableEntityCaching ? var tokens = Options.CurrentValue.DisableEntityCaching
Store.FindByAuthorizationIdAsync(identifier, cancellationToken) : ? Store.FindByAuthorizationIdAsync(identifier, cancellationToken)
Cache.FindByAuthorizationIdAsync(identifier, cancellationToken); : Cache.FindByAuthorizationIdAsync(identifier, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {
@ -350,9 +350,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
{ {
ArgumentException.ThrowIfNullOrEmpty(identifier); ArgumentException.ThrowIfNullOrEmpty(identifier);
var token = Options.CurrentValue.DisableEntityCaching ? var token = Options.CurrentValue.DisableEntityCaching
await Store.FindByIdAsync(identifier, cancellationToken) : ? await Store.FindByIdAsync(identifier, cancellationToken)
await Cache.FindByIdAsync(identifier, cancellationToken); : await Cache.FindByIdAsync(identifier, cancellationToken);
if (token is null) if (token is null)
{ {
@ -387,9 +387,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
identifier = await ObfuscateReferenceIdAsync(identifier, cancellationToken); identifier = await ObfuscateReferenceIdAsync(identifier, cancellationToken);
var token = Options.CurrentValue.DisableEntityCaching ? var token = Options.CurrentValue.DisableEntityCaching
await Store.FindByReferenceIdAsync(identifier, cancellationToken) : ? await Store.FindByReferenceIdAsync(identifier, cancellationToken)
await Cache.FindByReferenceIdAsync(identifier, cancellationToken); : await Cache.FindByReferenceIdAsync(identifier, cancellationToken);
if (token is null) if (token is null)
{ {
@ -420,9 +420,9 @@ public class OpenIddictTokenManager<TToken> : IOpenIddictTokenManager where TTok
{ {
ArgumentException.ThrowIfNullOrEmpty(subject); ArgumentException.ThrowIfNullOrEmpty(subject);
var tokens = Options.CurrentValue.DisableEntityCaching ? var tokens = Options.CurrentValue.DisableEntityCaching
Store.FindBySubjectAsync(subject, cancellationToken) : ? Store.FindBySubjectAsync(subject, cancellationToken)
Cache.FindBySubjectAsync(subject, cancellationToken); : Cache.FindBySubjectAsync(subject, cancellationToken);
if (Options.CurrentValue.DisableAdditionalFiltering) if (Options.CurrentValue.DisableAdditionalFiltering)
{ {

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

@ -723,8 +723,8 @@ public class OpenIddictEntityFrameworkAuthorizationStore<
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
authorization.Application = await context.Set<TApplication>().FindAsync( authorization.Application = await context.Set<TApplication>().FindAsync(
cancellationToken, ConvertIdentifierFromString(identifier)) ?? cancellationToken, ConvertIdentifierFromString(identifier))
throw new InvalidOperationException(SR.GetResourceString(SR.ID0244)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0244));
} }
else else

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

@ -821,8 +821,8 @@ public class OpenIddictEntityFrameworkTokenStore<
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
token.Application = await context.Set<TApplication>().FindAsync( token.Application = await context.Set<TApplication>().FindAsync(
cancellationToken, ConvertIdentifierFromString(identifier)) ?? cancellationToken, ConvertIdentifierFromString(identifier))
throw new InvalidOperationException(SR.GetResourceString(SR.ID0250)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0250));
} }
else else
@ -853,8 +853,8 @@ public class OpenIddictEntityFrameworkTokenStore<
if (!string.IsNullOrEmpty(identifier)) if (!string.IsNullOrEmpty(identifier))
{ {
token.Authorization = await context.Set<TAuthorization>().FindAsync( token.Authorization = await context.Set<TAuthorization>().FindAsync(
cancellationToken, ConvertIdentifierFromString(identifier)) ?? cancellationToken, ConvertIdentifierFromString(identifier))
throw new InvalidOperationException(SR.GetResourceString(SR.ID0251)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0251));
} }
else else

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

@ -684,9 +684,9 @@ public class OpenIddictEntityFrameworkCoreAuthorizationStore<
{ {
var context = await Context.GetDbContextAsync(cancellationToken); var context = await Context.GetDbContextAsync(cancellationToken);
IQueryable<TAuthorization> query = Options.CurrentValue.DisableBulkOperations ? IQueryable<TAuthorization> query = Options.CurrentValue.DisableBulkOperations
context.Set<TAuthorization>().Include(authorization => authorization.Application).AsTracking() : ? context.Set<TAuthorization>().Include(authorization => authorization.Application).AsTracking()
context.Set<TAuthorization>(); : context.Set<TAuthorization>();
if (!string.IsNullOrEmpty(subject)) if (!string.IsNullOrEmpty(subject))
{ {

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

@ -695,9 +695,9 @@ public class OpenIddictEntityFrameworkCoreTokenStore<
{ {
var context = await Context.GetDbContextAsync(cancellationToken); var context = await Context.GetDbContextAsync(cancellationToken);
IQueryable<TToken> query = Options.CurrentValue.DisableBulkOperations ? IQueryable<TToken> query = Options.CurrentValue.DisableBulkOperations
context.Set<TToken>().Include(token => token.Application).Include(token => token.Authorization).AsTracking() : ? context.Set<TToken>().Include(token => token.Application).Include(token => token.Authorization).AsTracking()
context.Set<TToken>(); : context.Set<TToken>();
if (!string.IsNullOrEmpty(subject)) if (!string.IsNullOrEmpty(subject))
{ {

8
src/OpenIddict.Quartz/OpenIddictQuartzJob.cs

@ -58,8 +58,8 @@ public sealed class OpenIddictQuartzJob : IJob
if (!_options.CurrentValue.DisableTokenPruning) if (!_options.CurrentValue.DisableTokenPruning)
{ {
var manager = scope.ServiceProvider.GetService<IOpenIddictTokenManager>() ?? var manager = scope.ServiceProvider.GetService<IOpenIddictTokenManager>()
throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278))) ?? throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278)))
{ {
RefireImmediately = false, RefireImmediately = false,
UnscheduleAllTriggers = true, UnscheduleAllTriggers = true,
@ -103,8 +103,8 @@ public sealed class OpenIddictQuartzJob : IJob
if (!_options.CurrentValue.DisableAuthorizationPruning) if (!_options.CurrentValue.DisableAuthorizationPruning)
{ {
var manager = scope.ServiceProvider.GetService<IOpenIddictAuthorizationManager>() ?? var manager = scope.ServiceProvider.GetService<IOpenIddictAuthorizationManager>()
throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278))) ?? throw new JobExecutionException(new InvalidOperationException(SR.GetResourceString(SR.ID0278)))
{ {
RefireImmediately = false, RefireImmediately = false,
UnscheduleAllTriggers = true, UnscheduleAllTriggers = true,

16
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandler.cs

@ -107,8 +107,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction
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,
@ -386,8 +386,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task HandleChallengeAsync(AuthenticationProperties? properties) protected override async Task HandleChallengeAsync(AuthenticationProperties? properties)
{ {
var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();
@ -435,8 +435,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
{ {
ArgumentNullException.ThrowIfNull(user); ArgumentNullException.ThrowIfNull(user);
var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();
@ -478,8 +478,8 @@ public sealed class OpenIddictServerAspNetCoreHandler : AuthenticationHandler<Au
/// <inheritdoc/> /// <inheritdoc/>
public async Task SignOutAsync(AuthenticationProperties? properties) public async Task SignOutAsync(AuthenticationProperties? properties)
{ {
var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
var context = new ProcessSignOutContext(transaction) var context = new ProcessSignOutContext(transaction)
{ {

16
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs

@ -94,8 +94,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var location = QueryHelpers.AddQueryString(context.RequestUri.GetLeftPart(UriPartial.Path), var location = QueryHelpers.AddQueryString(context.RequestUri.GetLeftPart(UriPartial.Path),
from parameter in context.Response.GetParameters() from parameter in context.Response.GetParameters()
@ -141,8 +141,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal))
@ -224,8 +224,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Query, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.Query, StringComparison.Ordinal))
@ -278,8 +278,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal))

4
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Device.cs

@ -79,8 +79,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Note: this handler only redirects the user agent to the URI specified in the // Note: this handler only redirects the user agent to the URI specified in the
// properties when there's no error or if the error is an access_denied error. // properties when there's no error or if the error is an access_denied error.

12
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Session.cs

@ -75,8 +75,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var location = QueryHelpers.AddQueryString(context.RequestUri.GetLeftPart(UriPartial.Path), var location = QueryHelpers.AddQueryString(context.RequestUri.GetLeftPart(UriPartial.Path),
from parameter in context.Response.GetParameters() from parameter in context.Response.GetParameters()
@ -117,8 +117,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.PostLogoutRedirectUri)) if (string.IsNullOrEmpty(context.PostLogoutRedirectUri))
{ {
@ -170,8 +170,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Note: this handler only executes if no post_logout_redirect_uri was specified // Note: this handler only executes if no post_logout_redirect_uri was specified
// and if the response doesn't correspond to an error, that must be handled locally. // and if the response doesn't correspond to an error, that must be handled locally.

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

@ -85,8 +85,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -136,8 +136,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Don't require that transport security be used if the request is not handled by OpenIddict. // Don't require that transport security be used if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.IsHttps) if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.IsHttps)
@ -178,8 +178,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Don't require that the request host be present if the request is not handled by OpenIddict. // Don't require that the request host be present if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.Host.HasValue) if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.Host.HasValue)
@ -435,8 +435,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (HttpMethods.IsGet(request.Method)) if (HttpMethods.IsGet(request.Method))
{ {
@ -483,8 +483,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (HttpMethods.IsGet(request.Method)) if (HttpMethods.IsGet(request.Method))
{ {
@ -560,8 +560,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (HttpMethods.IsPost(request.Method)) if (HttpMethods.IsPost(request.Method))
{ {
@ -635,8 +635,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Reject requests that use client_secret_post if support was explicitly disabled in the options. // Reject requests that use client_secret_post if support was explicitly disabled in the options.
if (!string.IsNullOrEmpty(context.Transaction.Request.ClientSecret) && if (!string.IsNullOrEmpty(context.Transaction.Request.ClientSecret) &&
@ -700,8 +700,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// If a client certificate was used during the TLS handshake, attach it to the context. // If a client certificate was used during the TLS handshake, attach it to the context.
if (request.IsHttps && await request.HttpContext.Connection.GetClientCertificateAsync( if (request.IsHttps && await request.HttpContext.Connection.GetClientCertificateAsync(
@ -739,8 +739,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
string? header = request.Headers[HeaderNames.Authorization]; string? header = request.Headers[HeaderNames.Authorization];
if (string.IsNullOrEmpty(header) || !header.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(header) || !header.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
@ -833,8 +833,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008)); Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
@ -927,8 +927,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
response.StatusCode = (context.EndpointType, context.Transaction.Response.Error) switch response.StatusCode = (context.EndpointType, context.Transaction.Response.Error) switch
{ {
@ -988,8 +988,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[HeaderNames.CacheControl] = "no-store"; response.Headers[HeaderNames.CacheControl] = "no-store";
@ -1031,8 +1031,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.Transaction.Response.Error)) if (string.IsNullOrEmpty(context.Transaction.Response.Error))
{ {
@ -1143,8 +1143,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// If the response doesn't contain a WWW-Authenticate header, don't return an empty response. // If the response doesn't contain a WWW-Authenticate header, don't return an empty response.
if (!response.Headers.ContainsKey(HeaderNames.WWWAuthenticate)) if (!response.Headers.ContainsKey(HeaderNames.WWWAuthenticate))
@ -1190,8 +1190,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
context.Logger.LogInformation(6142, SR.GetResourceString(SR.ID6142), context.Transaction.Response); context.Logger.LogInformation(6142, SR.GetResourceString(SR.ID6142), context.Transaction.Response);
@ -1281,8 +1281,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));
@ -1334,8 +1334,8 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007)); Debug.Assert(context.Transaction.Response is not null, SR.GetResourceString(SR.ID4007));

24
src/OpenIddict.Server.DataProtection/OpenIddictServerDataProtectionHandlers.Protection.cs

@ -109,20 +109,20 @@ public static partial class OpenIddictServerDataProtectionHandlers
0 => context.TokenTypeHint switch 0 => context.TokenTypeHint switch
{ {
TokenTypeHints.RefreshToken => TokenTypeHints.RefreshToken =>
ValidateToken(TokenTypeIdentifiers.RefreshToken) ?? ValidateToken(TokenTypeIdentifiers.RefreshToken)
ValidateToken(TokenTypeIdentifiers.AccessToken) ?? ?? ValidateToken(TokenTypeIdentifiers.AccessToken)
ValidateToken(TokenTypeIdentifiers.Private.AuthorizationCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.AuthorizationCode)
ValidateToken(TokenTypeIdentifiers.Private.DeviceCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.DeviceCode)
ValidateToken(TokenTypeIdentifiers.Private.UserCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.UserCode)
ValidateToken(TokenTypeIdentifiers.Private.RequestToken), ?? ValidateToken(TokenTypeIdentifiers.Private.RequestToken),
TokenTypeHints.AccessToken or _ => TokenTypeHints.AccessToken or _ =>
ValidateToken(TokenTypeIdentifiers.AccessToken) ?? ValidateToken(TokenTypeIdentifiers.AccessToken)
ValidateToken(TokenTypeIdentifiers.RefreshToken) ?? ?? ValidateToken(TokenTypeIdentifiers.RefreshToken)
ValidateToken(TokenTypeIdentifiers.Private.AuthorizationCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.AuthorizationCode)
ValidateToken(TokenTypeIdentifiers.Private.DeviceCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.DeviceCode)
ValidateToken(TokenTypeIdentifiers.Private.UserCode) ?? ?? ValidateToken(TokenTypeIdentifiers.Private.UserCode)
ValidateToken(TokenTypeIdentifiers.Private.RequestToken), ?? ValidateToken(TokenTypeIdentifiers.Private.RequestToken),
}, },
// If a single valid token type was set, ignore the specified token type hint. // If a single valid token type was set, ignore the specified token type hint.

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

@ -69,11 +69,11 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
// in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when // in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when
// active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case. // active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case.
var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ?? var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!) ?? var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
if (context.IsRequestHandled) if (context.IsRequestHandled)
{ {
@ -117,8 +117,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
/// <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)
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,
@ -283,8 +283,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge is not null && Response.StatusCode is 401 or 403) if (challenge is not null && Response.StatusCode is 401 or 403)
{ {
var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ?? var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties();
@ -326,8 +326,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
var signin = Helper.LookupSignIn(Options.AuthenticationType); var signin = Helper.LookupSignIn(Options.AuthenticationType);
if (signin is not null) if (signin is not null)
{ {
var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ?? var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = signin.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = signin.Properties ?? new AuthenticationProperties();
@ -370,8 +370,8 @@ public sealed class OpenIddictServerOwinHandler : AuthenticationHandler<Authenti
var signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); var signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);
if (signout is not null) if (signout is not null)
{ {
var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ?? var transaction = Context.Get<OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0112)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0112));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = signout.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = signout.Properties ?? new AuthenticationProperties();

16
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs

@ -96,8 +96,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var location = context.RequestUri.GetLeftPart(UriPartial.Path); var location = context.RequestUri.GetLeftPart(UriPartial.Path);
foreach (var (key, value) in foreach (var (key, value) in
@ -147,8 +147,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal))
@ -230,8 +230,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Query, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.Query, StringComparison.Ordinal))
@ -288,8 +288,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.RedirectUri) || if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal)) !string.Equals(context.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal))

4
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Device.cs

@ -82,8 +82,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Note: this handler only redirects the user agent to the URI specified in the // Note: this handler only redirects the user agent to the URI specified in the
// properties when there's no error or if the error is an access_denied error. // properties when there's no error or if the error is an access_denied error.

12
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Session.cs

@ -75,8 +75,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var location = context.RequestUri.GetLeftPart(UriPartial.Path); var location = context.RequestUri.GetLeftPart(UriPartial.Path);
foreach (var (key, value) in foreach (var (key, value) in
@ -120,8 +120,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.PostLogoutRedirectUri)) if (string.IsNullOrEmpty(context.PostLogoutRedirectUri))
{ {
@ -177,8 +177,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Note: this handler only executes if no post_logout_redirect_uri was specified // Note: this handler only executes if no post_logout_redirect_uri was specified
// and if the response doesn't correspond to an error, that must be handled locally. // and if the response doesn't correspond to an error, that must be handled locally.

72
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs

@ -83,8 +83,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -134,8 +134,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Don't require that transport security be used if the request is not handled by OpenIddict. // Don't require that transport security be used if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.IsSecure) if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && !request.IsSecure)
@ -176,8 +176,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Don't require that the request host be present if the request is not handled by OpenIddict. // Don't require that the request host be present if the request is not handled by OpenIddict.
if (context.EndpointType is not OpenIddictServerEndpointType.Unknown && if (context.EndpointType is not OpenIddictServerEndpointType.Unknown &&
@ -485,8 +485,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase)) if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase))
{ {
@ -536,8 +536,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase)) if (string.Equals(request.Method, "GET", StringComparison.OrdinalIgnoreCase))
{ {
@ -619,8 +619,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase)) if (string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{ {
@ -697,8 +697,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Reject requests that use client_secret_post if support was explicitly disabled in the options. // Reject requests that use client_secret_post if support was explicitly disabled in the options.
if (!string.IsNullOrEmpty(context.Transaction.Request.ClientSecret) && if (!string.IsNullOrEmpty(context.Transaction.Request.ClientSecret) &&
@ -762,8 +762,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// If a client certificate was used during the TLS handshake, attach it to the context. // If a client certificate was used during the TLS handshake, attach it to the context.
if (request.IsSecure && await GetClientCertificateAsync(request.Context) is X509Certificate2 certificate) if (request.IsSecure && await GetClientCertificateAsync(request.Context) is X509Certificate2 certificate)
@ -814,8 +814,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var header = request.Headers[Headers.Authorization]; var header = request.Headers[Headers.Authorization];
if (string.IsNullOrEmpty(header) || !header.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(header) || !header.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
@ -910,8 +910,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var header = request.Headers[Headers.Authorization]; var header = request.Headers[Headers.Authorization];
if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
@ -1002,8 +1002,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
response.StatusCode = (context.EndpointType, context.Transaction.Response.Error) switch response.StatusCode = (context.EndpointType, context.Transaction.Response.Error) switch
{ {
@ -1063,8 +1063,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OWIN authentication middleware configured to use active authentication (which is the default mode) // OWIN authentication middleware configured to use active authentication (which is the default mode)
// are known to aggressively intercept 401 responses even if the request is already considered fully // are known to aggressively intercept 401 responses even if the request is already considered fully
@ -1113,8 +1113,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Similarly to the automatic authentication mode used by OWIN authentication middleware, // Similarly to the automatic authentication mode used by OWIN authentication middleware,
// the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if // the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if
@ -1177,8 +1177,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[Headers.CacheControl] = "no-store"; response.Headers[Headers.CacheControl] = "no-store";
@ -1220,8 +1220,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.Transaction.Response.Error)) if (string.IsNullOrEmpty(context.Transaction.Response.Error))
{ {
@ -1332,8 +1332,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// If the response doesn't contain a WWW-Authenticate header, don't return an empty response. // If the response doesn't contain a WWW-Authenticate header, don't return an empty response.
if (!response.Headers.ContainsKey(Headers.WwwAuthenticate)) if (!response.Headers.ContainsKey(Headers.WwwAuthenticate))
@ -1379,8 +1379,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
context.Logger.LogInformation(6142, SR.GetResourceString(SR.ID6142), context.Transaction.Response); context.Logger.LogInformation(6142, SR.GetResourceString(SR.ID6142), context.Transaction.Response);
@ -1474,8 +1474,8 @@ public static partial class OpenIddictServerOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.Transaction.Response.Error)) if (string.IsNullOrEmpty(context.Transaction.Response.Error))
{ {

44
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -360,9 +360,9 @@ public sealed class OpenIddictServerBuilder
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(Assembly assembly, string resource, string? password) public OpenIddictServerBuilder AddEncryptionCertificate(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate retrieved from an embedded resource. /// Registers an encryption certificate retrieved from an embedded resource.
@ -379,8 +379,8 @@ public sealed class OpenIddictServerBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -393,9 +393,9 @@ public sealed class OpenIddictServerBuilder
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(Stream stream, string? password) public OpenIddictServerBuilder AddEncryptionCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate extracted from a stream. /// Registers an encryption certificate extracted from a stream.
@ -432,9 +432,9 @@ public sealed class OpenIddictServerBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddEncryptionCertificate( return AddEncryptionCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -756,9 +756,9 @@ public sealed class OpenIddictServerBuilder
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(Assembly assembly, string resource, string? password) public OpenIddictServerBuilder AddSigningCertificate(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate retrieved from an embedded resource. /// Registers a signing certificate retrieved from an embedded resource.
@ -775,8 +775,8 @@ public sealed class OpenIddictServerBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddSigningCertificate(stream, password, flags); return AddSigningCertificate(stream, password, flags);
} }
@ -789,9 +789,9 @@ public sealed class OpenIddictServerBuilder
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(Stream stream, string? password) public OpenIddictServerBuilder AddSigningCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate extracted from a stream. /// Registers a signing certificate extracted from a stream.
@ -828,9 +828,9 @@ public sealed class OpenIddictServerBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddSigningCertificate( return AddSigningCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {

28
src/OpenIddict.Server/OpenIddictServerHandlerDescriptor.cs

@ -158,8 +158,11 @@ public sealed class OpenIddictServerHandlerDescriptor
/// <param name="handler">The handler instance.</param> /// <param name="handler">The handler instance.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler) public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler)
=> UseSingletonHandler(new OpenIddictServerHandler<TContext>(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return UseSingletonHandler(new OpenIddictServerHandler<TContext>(handler));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified scoped handler. /// Configures the descriptor to use the specified scoped handler.
@ -179,8 +182,11 @@ public sealed class OpenIddictServerHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictServerHandler<TContext> where THandler : class, IOpenIddictServerHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Scoped(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Scoped(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -200,8 +206,11 @@ public sealed class OpenIddictServerHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictServerHandler<TContext> where THandler : class, IOpenIddictServerHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Singleton(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -211,8 +220,11 @@ public sealed class OpenIddictServerHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(THandler handler) public Builder<TContext> UseSingletonHandler<THandler>(THandler handler)
where THandler : class, IOpenIddictServerHandler<TContext> where THandler : class, IOpenIddictServerHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return SetServiceDescriptor(ServiceDescriptor.Singleton(handler));
}
/// <summary> /// <summary>
/// Build a new descriptor instance, based on the parameters that were previously set. /// Build a new descriptor instance, based on the parameters that were previously set.

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

@ -1346,10 +1346,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateResponseType(applicationManager: null) : ? new ValidateResponseType(applicationManager: null)
new ValidateResponseType(provider.GetService<IOpenIddictApplicationManager>() ?? : new ValidateResponseType(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateProofKeyForCodeExchangeParameters.Descriptor.Order + 1_000) .SetOrder(ValidateProofKeyForCodeExchangeParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1396,8 +1396,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// To prevent downgrade attacks, ensure that authorization requests returning // To prevent downgrade attacks, ensure that authorization requests returning
// an access token directly from the authorization endpoint are rejected if // an access token directly from the authorization endpoint are rejected if
@ -1449,8 +1449,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// If no explicit redirect_uri was specified, retrieve the URI associated with the // If no explicit redirect_uri was specified, retrieve the URI associated with the
// client and ensure exactly one redirect_uri was attached to the client definition. // client and ensure exactly one redirect_uri was attached to the client definition.
@ -1512,10 +1512,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateScopes() : ? new ValidateScopes()
new ValidateScopes(provider.GetService<IOpenIddictScopeManager>() ?? : new ValidateScopes(provider.GetService<IOpenIddictScopeManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateClientRedirectUri.Descriptor.Order + 1_000) .SetOrder(ValidateClientRedirectUri.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1587,10 +1587,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateResources() : ? new ValidateResources()
new ValidateResources(provider.GetService<IOpenIddictResourceManager>() ?? : new ValidateResources(provider.GetService<IOpenIddictResourceManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateScopes.Descriptor.Order + 1_000) .SetOrder(ValidateScopes.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1672,8 +1672,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)
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))
@ -1722,8 +1722,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)
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() &&
@ -1817,8 +1817,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)
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()))
@ -1892,8 +1892,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)
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())
{ {
@ -1953,8 +1953,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
foreach (var resource in context.Request.GetResources()) foreach (var resource in context.Request.GetResources())
{ {
@ -2014,8 +2014,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.PushedAuthorizationRequests)) if (await _applicationManager.HasRequirementAsync(application, Requirements.Features.PushedAuthorizationRequests))
{ {
@ -2080,8 +2080,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
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))
{ {
@ -2166,8 +2166,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateAuthorizationRequestContext>( var notification = context.Transaction.GetProperty<ValidateAuthorizationRequestContext>(
typeof(ValidateAuthorizationRequestContext).FullName!) ?? typeof(ValidateAuthorizationRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal; context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal;
@ -3433,10 +3433,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidatePushedResponseType(applicationManager: null) : ? new ValidatePushedResponseType(applicationManager: null)
new ValidatePushedResponseType(provider.GetService<IOpenIddictApplicationManager>() ?? : new ValidatePushedResponseType(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidatePushedAuthentication.Descriptor.Order + 1_000) .SetOrder(ValidatePushedAuthentication.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3483,8 +3483,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// To prevent downgrade attacks, ensure that pushed authorization requests returning // To prevent downgrade attacks, ensure that pushed authorization requests returning
// an access token directly from the authorization endpoint are rejected if // an access token directly from the authorization endpoint are rejected if
@ -3536,8 +3536,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// If no explicit redirect_uri was specified, retrieve the URI associated with the // If no explicit redirect_uri was specified, retrieve the URI associated with the
// client and ensure exactly one redirect_uri was attached to the client definition. // client and ensure exactly one redirect_uri was attached to the client definition.
@ -3599,10 +3599,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidatePushedScopes() : ? new ValidatePushedScopes()
new ValidatePushedScopes(provider.GetService<IOpenIddictScopeManager>() ?? : new ValidatePushedScopes(provider.GetService<IOpenIddictScopeManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidatePushedClientRedirectUri.Descriptor.Order + 1_000) .SetOrder(ValidatePushedClientRedirectUri.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3674,10 +3674,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidatePushedResources() : ? new ValidatePushedResources()
new ValidatePushedResources(provider.GetService<IOpenIddictResourceManager>() ?? : new ValidatePushedResources(provider.GetService<IOpenIddictResourceManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidatePushedScopes.Descriptor.Order + 1_000) .SetOrder(ValidatePushedScopes.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3759,8 +3759,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)
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 pushed authorization endpoint. // Reject the request if the application is not allowed to use the pushed authorization endpoint.
if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.PushedAuthorization)) if (!await _applicationManager.HasPermissionAsync(application, Permissions.Endpoints.PushedAuthorization))
@ -3809,8 +3809,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)
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() &&
@ -3904,8 +3904,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)
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()))
@ -3979,8 +3979,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)
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())
{ {
@ -4040,8 +4040,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
foreach (var resource in context.Request.GetResources()) foreach (var resource in context.Request.GetResources())
{ {
@ -4100,8 +4100,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
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))
{ {
@ -4186,8 +4186,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidatePushedAuthorizationRequestContext>( var notification = context.Transaction.GetProperty<ValidatePushedAuthorizationRequestContext>(
typeof(ValidatePushedAuthorizationRequestContext).FullName!) ?? typeof(ValidatePushedAuthorizationRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal; context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal;

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

@ -453,10 +453,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateScopes() : ? new ValidateScopes()
new ValidateScopes(provider.GetService<IOpenIddictScopeManager>() ?? : new ValidateScopes(provider.GetService<IOpenIddictScopeManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateClientCredentialsParameters.Descriptor.Order + 1_000) .SetOrder(ValidateClientCredentialsParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -595,8 +595,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)
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 authorization endpoint. // Reject the request if the application is not allowed to use the device authorization endpoint.
// //
@ -648,8 +648,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)
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))
@ -715,8 +715,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)
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())
{ {
@ -1078,8 +1078,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateEndUserVerificationRequestContext>( var notification = context.Transaction.GetProperty<ValidateEndUserVerificationRequestContext>(
typeof(ValidateEndUserVerificationRequestContext).FullName!) ?? typeof(ValidateEndUserVerificationRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.UserCodePrincipal ??= notification.UserCodePrincipal; context.UserCodePrincipal ??= notification.UserCodePrincipal;

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

@ -1019,10 +1019,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateScopes() : ? new ValidateScopes()
new ValidateScopes(provider.GetService<IOpenIddictScopeManager>() ?? : new ValidateScopes(provider.GetService<IOpenIddictScopeManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateResourceParameter.Descriptor.Order + 1_000) .SetOrder(ValidateResourceParameter.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1135,10 +1135,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateResources() : ? new ValidateResources()
new ValidateResources(provider.GetService<IOpenIddictResourceManager>() ?? : new ValidateResources(provider.GetService<IOpenIddictResourceManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateAudiences.Descriptor.Order + 1_000) .SetOrder(ValidateAudiences.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1284,8 +1284,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)
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))
@ -1336,8 +1336,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)
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))
@ -1403,8 +1403,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)
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())
{ {
@ -1465,8 +1465,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
foreach (var audience in context.Request.GetAudiences()) foreach (var audience in context.Request.GetAudiences())
{ {
@ -1520,8 +1520,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)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
foreach (var resource in context.Request.GetResources()) foreach (var resource in context.Request.GetResources())
{ {
@ -1586,8 +1586,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)
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))
{ {
@ -2149,8 +2149,8 @@ public static partial class OpenIddictServerHandlers
} }
var notification = context.Transaction.GetProperty<ValidateTokenRequestContext>( var notification = context.Transaction.GetProperty<ValidateTokenRequestContext>(
typeof(ValidateTokenRequestContext).FullName!) ?? typeof(ValidateTokenRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.ActorTokenPrincipal = notification.ActorTokenPrincipal; context.ActorTokenPrincipal = notification.ActorTokenPrincipal;
context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal; context.AuthorizationCodePrincipal = notification.AuthorizationCodePrincipal;

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

@ -528,8 +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)
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))
@ -674,8 +674,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateIntrospectionRequestContext>( var notification = context.Transaction.GetProperty<ValidateIntrospectionRequestContext>(
typeof(ValidateIntrospectionRequestContext).FullName!) ?? typeof(ValidateIntrospectionRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.GenericTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.GenericTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -735,8 +735,8 @@ public static partial class OpenIddictServerHandlers
// For access tokens that contain a confirmation claim, return it to the caller so // For access tokens that contain a confirmation claim, return it to the caller so
// that resource servers can verify the proof-of-possession when the token is used. // that resource servers can verify the proof-of-possession when the token is used.
TokenTypeIdentifiers.AccessToken when context.GenericTokenPrincipal.GetClaim( TokenTypeIdentifiers.AccessToken when context.GenericTokenPrincipal.GetClaim(
Claims.Confirmation) is { Length: > 0 } value => JsonObject.Parse(value) as JsonObject ?? Claims.Confirmation) is { Length: > 0 } value => JsonObject.Parse(value) as JsonObject
throw new InvalidOperationException(SR.GetResourceString(SR.ID2199)), ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID2199)),
_ => null _ => null
}; };
@ -746,8 +746,8 @@ public static partial class OpenIddictServerHandlers
// Infer the audiences/client_id from the claims stored in the security principal. // Infer the audiences/client_id from the claims stored in the security principal.
context.Audiences.UnionWith(context.GenericTokenPrincipal.GetAudiences()); context.Audiences.UnionWith(context.GenericTokenPrincipal.GetAudiences());
context.ClientId = context.GenericTokenPrincipal.GetClaim(Claims.ClientId) ?? context.ClientId = context.GenericTokenPrincipal.GetClaim(Claims.ClientId)
context.GenericTokenPrincipal.FindFirst(Claims.Private.Presenter)?.Value; ?? context.GenericTokenPrincipal.FindFirst(Claims.Private.Presenter)?.Value;
context.TokenType = context.GenericTokenPrincipal.GetTokenType() switch context.TokenType = context.GenericTokenPrincipal.GetTokenType() switch
{ {
@ -816,8 +816,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.Request.ClientId)
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))

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

@ -78,10 +78,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ResolveTokenValidationParameters() : ? new ResolveTokenValidationParameters()
new ResolveTokenValidationParameters(provider.GetService<IOpenIddictApplicationManager>() ?? : new ResolveTokenValidationParameters(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(int.MinValue + 100_000) .SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -722,8 +722,8 @@ public static partial class OpenIddictServerHandlers
// the "azp" or "client_id" claim if no "oi_prst" claim was found in the principal. // the "azp" or "client_id" claim if no "oi_prst" claim was found in the principal.
if (!context.Principal.HasClaim(Claims.Private.Presenter)) if (!context.Principal.HasClaim(Claims.Private.Presenter))
{ {
var presenter = context.Principal.GetClaim(Claims.AuthorizedParty) ?? var presenter = context.Principal.GetClaim(Claims.AuthorizedParty)
context.Principal.GetClaim(Claims.ClientId); ?? context.Principal.GetClaim(Claims.ClientId);
if (!string.IsNullOrEmpty(presenter)) if (!string.IsNullOrEmpty(presenter))
{ {
@ -1236,8 +1236,8 @@ public static partial class OpenIddictServerHandlers
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017)); Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017));
var token = await _tokenManager.FindByIdAsync(context.TokenId) ?? var token = await _tokenManager.FindByIdAsync(context.TokenId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
// If the token is already marked as redeemed, this may indicate that it was compromised. // If the token is already marked as redeemed, this may indicate that it was compromised.
// In this case, revoke the entire chain of tokens associated with the authorization, if one was attached to the token. // In this case, revoke the entire chain of tokens associated with the authorization, if one was attached to the token.
@ -1562,14 +1562,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)
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)
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);
@ -1649,9 +1649,9 @@ public static partial class OpenIddictServerHandlers
{ {
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var claims = context.SecurityTokenDescriptor.Claims is not null ? var claims = context.SecurityTokenDescriptor.Claims is not null
new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal) : ? new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal)
new Dictionary<string, object>(StringComparer.Ordinal); : new Dictionary<string, object>(StringComparer.Ordinal);
// For access and identity tokens, set the public audience claims // For access and identity tokens, set the public audience claims
// using the private audience claims from the security principal. // using the private audience claims from the security principal.
@ -1815,8 +1815,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)
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);

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

@ -469,8 +469,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)
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))
@ -615,8 +615,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateRevocationRequestContext>( var notification = context.Transaction.GetProperty<ValidateRevocationRequestContext>(
typeof(ValidateRevocationRequestContext).FullName!) ?? typeof(ValidateRevocationRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.GenericTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.GenericTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));

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

@ -599,8 +599,8 @@ public static partial class OpenIddictServerHandlers
if (!string.IsNullOrEmpty(context.ClientId)) if (!string.IsNullOrEmpty(context.ClientId))
{ {
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
if (!await _applicationManager.ValidatePostLogoutRedirectUriAsync(application, context.PostLogoutRedirectUri)) if (!await _applicationManager.ValidatePostLogoutRedirectUriAsync(application, context.PostLogoutRedirectUri))
{ {
@ -729,8 +729,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)
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 end session endpoint. // Reject the request if the application is not allowed to use the end session endpoint.
// //
@ -772,10 +772,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateAuthorizedParty() : ? new ValidateAuthorizedParty()
new ValidateAuthorizedParty(provider.GetService<IOpenIddictApplicationManager>() ?? : new ValidateAuthorizedParty(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateEndpointPermissions.Descriptor.Order + 1_000) .SetOrder(ValidateEndpointPermissions.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -905,8 +905,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateEndSessionRequestContext>( var notification = context.Transaction.GetProperty<ValidateEndSessionRequestContext>(
typeof(ValidateEndSessionRequestContext).FullName!) ?? typeof(ValidateEndSessionRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal; context.IdentityTokenHintPrincipal ??= notification.IdentityTokenHintPrincipal;

4
src/OpenIddict.Server/OpenIddictServerHandlers.Userinfo.cs

@ -408,8 +408,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ValidateUserInfoRequestContext>( var notification = context.Transaction.GetProperty<ValidateUserInfoRequestContext>(
typeof(ValidateUserInfoRequestContext).FullName!) ?? typeof(ValidateUserInfoRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.AccessTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.AccessTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));

188
src/OpenIddict.Server/OpenIddictServerHandlers.cs

@ -1,4 +1,4 @@
/* /*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning * See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project. * the license and the contributors participating to this project.
@ -978,10 +978,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateClientId() : ? new ValidateClientId()
new ValidateClientId(provider.GetService<IOpenIddictApplicationManager>() ?? : new ValidateClientId(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(ValidateClientAssertionAudience.Descriptor.Order + 1_000) .SetOrder(ValidateClientAssertionAudience.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -1113,8 +1113,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
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))
{ {
@ -1224,8 +1224,8 @@ public static partial class OpenIddictServerHandlers
return; return;
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
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))
@ -1272,10 +1272,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new ValidateClientCertificate() : ? new ValidateClientCertificate()
new ValidateClientCertificate(provider.GetService<IOpenIddictApplicationManager>() ?? : new ValidateClientCertificate(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.UseScopedHandler<ValidateClientCertificate>() .UseScopedHandler<ValidateClientCertificate>()
.SetOrder(ValidateClientSecret.Descriptor.Order + 1_000) .SetOrder(ValidateClientSecret.Descriptor.Order + 1_000)
@ -1398,8 +1398,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0032)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
// Note: to avoid building and introspecting a X.509 certificate chain and reduce the cost // Note: to avoid building and introspecting a X.509 certificate chain and reduce the cost
// of this check, a certificate is always assumed to be self-signed when it is self-issued. // of this check, a certificate is always assumed to be self-signed when it is self-issued.
@ -2651,8 +2651,8 @@ public static partial class OpenIddictServerHandlers
} }
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.UserCodePrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.UserCodePrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -2707,8 +2707,8 @@ public static partial class OpenIddictServerHandlers
} }
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.UserCodePrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.UserCodePrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -2954,8 +2954,8 @@ public static partial class OpenIddictServerHandlers
} }
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
var principal = context.EndpointType switch var principal = context.EndpointType switch
{ {
@ -3063,8 +3063,8 @@ public static partial class OpenIddictServerHandlers
var identity = (ClaimsIdentity) context.Principal.Identity; var identity = (ClaimsIdentity) context.Principal.Identity;
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
var principal = context.EndpointType switch var principal = context.EndpointType switch
{ {
@ -3483,14 +3483,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)
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)
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);
@ -3533,10 +3533,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareAccessTokenPrincipal() : ? new PrepareAccessTokenPrincipal()
new PrepareAccessTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareAccessTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(AttachAuthorization.Descriptor.Order + 1_000) .SetOrder(AttachAuthorization.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3610,8 +3610,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.AccessToken, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.AccessToken, out string? setting) &&
@ -3696,10 +3696,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareAuthorizationCodePrincipal() : ? new PrepareAuthorizationCodePrincipal()
new PrepareAuthorizationCodePrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareAuthorizationCodePrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareAccessTokenPrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareAccessTokenPrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3744,8 +3744,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.AuthorizationCode, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.AuthorizationCode, out string? setting) &&
@ -3784,8 +3784,9 @@ public static partial class OpenIddictServerHandlers
// Default to plain if no explicit code challenge method was specified. // Default to plain if no explicit code challenge method was specified.
principal.SetClaim(Claims.Private.CodeChallengeMethod, principal.SetClaim(Claims.Private.CodeChallengeMethod,
!string.IsNullOrEmpty(context.Request.CodeChallengeMethod) ? !string.IsNullOrEmpty(context.Request.CodeChallengeMethod)
context.Request.CodeChallengeMethod : CodeChallengeMethods.Plain); ? context.Request.CodeChallengeMethod
: CodeChallengeMethods.Plain);
} }
// Attach the nonce so that it can be later returned by // Attach the nonce so that it can be later returned by
@ -3819,10 +3820,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareDeviceCodePrincipal() : ? new PrepareDeviceCodePrincipal()
new PrepareDeviceCodePrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareDeviceCodePrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareAuthorizationCodePrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareAuthorizationCodePrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -3867,8 +3868,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.DeviceCode, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.DeviceCode, out string? setting) &&
@ -3929,10 +3930,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareIssuedTokenPrincipal() : ? new PrepareIssuedTokenPrincipal()
new PrepareIssuedTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareIssuedTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -4083,8 +4084,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var name = context.IssuedTokenType switch var name = context.IssuedTokenType switch
{ {
@ -4177,8 +4178,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
// Note: refresh tokens are only bound to the provided certificate when the client // Note: refresh tokens are only bound to the provided certificate when the client
// is a public application, as refresh tokens issued to confidential applications // is a public application, as refresh tokens issued to confidential applications
@ -4225,10 +4226,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareRequestTokenPrincipal() : ? new PrepareRequestTokenPrincipal()
new PrepareRequestTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareRequestTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareDeviceCodePrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -4273,8 +4274,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.RequestToken, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.RequestToken, out string? setting) &&
@ -4353,10 +4354,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareRefreshTokenPrincipal() : ? new PrepareRefreshTokenPrincipal()
new PrepareRefreshTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareRefreshTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareRequestTokenPrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareRequestTokenPrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -4397,8 +4398,8 @@ public static partial class OpenIddictServerHandlers
context.Options.DisableSlidingRefreshTokenExpiration) context.Options.DisableSlidingRefreshTokenExpiration)
{ {
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
Debug.Assert(notification.RefreshTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(notification.RefreshTokenPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
@ -4418,8 +4419,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.RefreshToken, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.RefreshToken, out string? setting) &&
@ -4471,8 +4472,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
// Note: refresh tokens are only bound to the provided certificate when the client // Note: refresh tokens are only bound to the provided certificate when the client
// is a public application, as refresh tokens issued to confidential applications // is a public application, as refresh tokens issued to confidential applications
@ -4518,10 +4519,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareIdentityTokenPrincipal() : ? new PrepareIdentityTokenPrincipal()
new PrepareIdentityTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareIdentityTokenPrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareRefreshTokenPrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareRefreshTokenPrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -4593,8 +4594,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.IdentityToken, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.IdentityToken, out string? setting) &&
@ -4669,10 +4670,10 @@ public static partial class OpenIddictServerHandlers
// invalid core configuration exceptions are not thrown even if the managers were registered. // invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue; var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ? return options.EnableDegradedMode
new PrepareUserCodePrincipal() : ? new PrepareUserCodePrincipal()
new PrepareUserCodePrincipal(provider.GetService<IOpenIddictApplicationManager>() ?? : new PrepareUserCodePrincipal(provider.GetService<IOpenIddictApplicationManager>()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
}) })
.SetOrder(PrepareIdentityTokenPrincipal.Descriptor.Order + 1_000) .SetOrder(PrepareIdentityTokenPrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn) .SetType(OpenIddictServerHandlerType.BuiltIn)
@ -4717,8 +4718,8 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
} }
var application = await _applicationManager.FindByClientIdAsync(context.ClientId) ?? var application = await _applicationManager.FindByClientIdAsync(context.ClientId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0017)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
var settings = await _applicationManager.GetSettingsAsync(application); var settings = await _applicationManager.GetSettingsAsync(application);
if (settings.TryGetValue(Settings.TokenLifetimes.UserCode, out string? setting) && if (settings.TryGetValue(Settings.TokenLifetimes.UserCode, out string? setting) &&
@ -5254,8 +5255,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)
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.
@ -5308,8 +5309,8 @@ public static partial class OpenIddictServerHandlers
} }
var credentials = context.Options.SigningCredentials.Find( var credentials = context.Options.SigningCredentials.Find(
static credentials => credentials.Key is AsymmetricSecurityKey) ?? static credentials => credentials.Key is AsymmetricSecurityKey)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0266)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0266));
if (!string.IsNullOrEmpty(context.AccessToken)) if (!string.IsNullOrEmpty(context.AccessToken))
{ {
@ -5646,8 +5647,9 @@ public static partial class OpenIddictServerHandlers
// is set to "N_A" to indicate when the token used as the "access_token" parameter is not an access token. // is set to "N_A" to indicate when the token used as the "access_token" parameter is not an access token.
context.Response.AccessToken = context.IssuedToken; context.Response.AccessToken = context.IssuedToken;
context.Response.IssuedTokenType = context.IssuedTokenType; context.Response.IssuedTokenType = context.IssuedTokenType;
context.Response.TokenType = context.IssuedTokenType is TokenTypeIdentifiers.AccessToken ? context.Response.TokenType = context.IssuedTokenType is TokenTypeIdentifiers.AccessToken
TokenTypes.Bearer : TokenTypes.NotApplicable; ? TokenTypes.Bearer
: TokenTypes.NotApplicable;
// If the principal is available, attach additional metadata. // If the principal is available, attach additional metadata.
if (context.IssuedTokenPrincipal is not null) if (context.IssuedTokenPrincipal is not null)
@ -5700,8 +5702,8 @@ public static partial class OpenIddictServerHandlers
} }
context.Response.ExpiresIn = ( context.Response.ExpiresIn = (
context.DeviceCodePrincipal?.GetExpirationDate() ?? context.DeviceCodePrincipal?.GetExpirationDate()
context.UserCodePrincipal?.GetExpirationDate()) switch ?? context.UserCodePrincipal?.GetExpirationDate()) switch
{ {
// If an expiration date was set on the device code or user // If an expiration date was set on the device code or user
// code principal, return it to the client application. // code principal, return it to the client application.
@ -5831,8 +5833,8 @@ public static partial class OpenIddictServerHandlers
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>( var notification = context.Transaction.GetProperty<ProcessAuthenticationContext>(
typeof(ProcessAuthenticationContext).FullName!) ?? typeof(ProcessAuthenticationContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0007)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0007));
var principal = notification.RequestTokenPrincipal; var principal = notification.RequestTokenPrincipal;
if (principal is null) if (principal is null)

8
src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandler.cs

@ -105,8 +105,8 @@ public sealed class OpenIddictValidationAspNetCoreHandler : AuthenticationHandle
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
var transaction = Context.Features.Get<OpenIddictValidationAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictValidationAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
// 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,
@ -207,8 +207,8 @@ public sealed class OpenIddictValidationAspNetCoreHandler : AuthenticationHandle
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task HandleChallengeAsync(AuthenticationProperties? properties) protected override async Task HandleChallengeAsync(AuthenticationProperties? properties)
{ {
var transaction = Context.Features.Get<OpenIddictValidationAspNetCoreFeature>()?.Transaction ?? var transaction = Context.Features.Get<OpenIddictValidationAspNetCoreFeature>()?.Transaction
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = properties ?? new AuthenticationProperties();

40
src/OpenIddict.Validation.AspNetCore/OpenIddictValidationAspNetCoreHandlers.cs

@ -85,8 +85,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -135,8 +135,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Don't require that a Host header be present if the issuer was set in the options. // Don't require that a Host header be present if the issuer was set in the options.
if (context.Options.Issuer is null && !request.Host.HasValue) if (context.Options.Issuer is null && !request.Host.HasValue)
@ -185,8 +185,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Resolve the access token from the standard Authorization header. // Resolve the access token from the standard Authorization header.
// See https://tools.ietf.org/html/rfc6750#section-2.1 for more information. // See https://tools.ietf.org/html/rfc6750#section-2.1 for more information.
@ -234,8 +234,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(request.ContentType) || if (string.IsNullOrEmpty(request.ContentType) ||
!request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) !request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
@ -287,8 +287,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Resolve the access token from the standard access_token query parameter. // Resolve the access token from the standard access_token query parameter.
// See https://tools.ietf.org/html/rfc6750#section-2.3 for more information. // See https://tools.ietf.org/html/rfc6750#section-2.3 for more information.
@ -327,8 +327,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetHttpRequest() ?? var request = context.Transaction.GetHttpRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// If a client certificate was used during the TLS handshake, attach it to the context. // If a client certificate was used during the TLS handshake, attach it to the context.
if (request.IsHttps && await request.HttpContext.Connection.GetClientCertificateAsync( if (request.IsHttps && await request.HttpContext.Connection.GetClientCertificateAsync(
@ -460,8 +460,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
response.StatusCode = context.Transaction.Response.Error switch response.StatusCode = context.Transaction.Response.Error switch
{ {
@ -505,8 +505,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[HeaderNames.CacheControl] = "no-store"; response.Headers[HeaderNames.CacheControl] = "no-store";
@ -548,8 +548,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.Transaction.Response.Error)) if (string.IsNullOrEmpty(context.Transaction.Response.Error))
{ {
@ -642,8 +642,8 @@ public static partial class OpenIddictValidationAspNetCoreHandlers
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved, // This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ?? var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
// If the response doesn't contain a WWW-Authenticate header, don't return an empty response. // If the response doesn't contain a WWW-Authenticate header, don't return an empty response.
if (!response.Headers.ContainsKey(HeaderNames.WWWAuthenticate)) if (!response.Headers.ContainsKey(HeaderNames.WWWAuthenticate))

16
src/OpenIddict.Validation.Owin/OpenIddictValidationOwinHandler.cs

@ -69,11 +69,11 @@ public sealed class OpenIddictValidationOwinHandler : AuthenticationHandler<Auth
// in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when // in InitializeCoreAsync() to ensure the request context is available from AuthenticateCoreAsync() when
// active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case. // active authentication is used, as AuthenticateCoreAsync() is always called before InvokeAsync() in this case.
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ?? var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!) ?? var context = transaction.GetProperty<ProcessRequestContext>(typeof(ProcessRequestContext).FullName!)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
if (context.IsRequestHandled) if (context.IsRequestHandled)
{ {
@ -117,8 +117,8 @@ public sealed class OpenIddictValidationOwinHandler : AuthenticationHandler<Auth
/// <inheritdoc/> /// <inheritdoc/>
protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync() protected override async Task<AuthenticationTicket?> AuthenticateCoreAsync()
{ {
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ?? var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
// 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,
@ -215,8 +215,8 @@ public sealed class OpenIddictValidationOwinHandler : AuthenticationHandler<Auth
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge is not null && Response.StatusCode is 401 or 403) if (challenge is not null && Response.StatusCode is 401 or 403)
{ {
var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName) ?? var transaction = Context.Get<OpenIddictValidationTransaction>(typeof(OpenIddictValidationTransaction).FullName)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0166)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0166));
transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties(); transaction.Properties[typeof(AuthenticationProperties).FullName!] = challenge.Properties ?? new AuthenticationProperties();

48
src/OpenIddict.Validation.Owin/OpenIddictValidationOwinHandlers.cs

@ -86,8 +86,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute // OpenIddict supports both absolute and relative URIs for all its endpoints, but only absolute
// URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized // URIs can be properly canonicalized by the BCL System.Uri class (e.g './path/../' is normalized
@ -136,8 +136,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Don't require that a Host header be present if the issuer was set in the options. // Don't require that a Host header be present if the issuer was set in the options.
if (context.Options.Issuer is null && string.IsNullOrEmpty(request.Host.Value)) if (context.Options.Issuer is null && string.IsNullOrEmpty(request.Host.Value))
@ -186,8 +186,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Resolve the access token from the standard Authorization header. // Resolve the access token from the standard Authorization header.
// See https://tools.ietf.org/html/rfc6750#section-2.1 for more information. // See https://tools.ietf.org/html/rfc6750#section-2.1 for more information.
@ -235,8 +235,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(request.ContentType) || if (string.IsNullOrEmpty(request.ContentType) ||
!request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) !request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
@ -289,8 +289,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Resolve the access token from the standard access_token query parameter. // Resolve the access token from the standard access_token query parameter.
// See https://tools.ietf.org/html/rfc6750#section-2.3 for more information. // See https://tools.ietf.org/html/rfc6750#section-2.3 for more information.
@ -330,8 +330,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var request = context.Transaction.GetOwinRequest() ?? var request = context.Transaction.GetOwinRequest()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// If a client certificate was used during the TLS handshake, attach it to the context. // If a client certificate was used during the TLS handshake, attach it to the context.
if (request.IsSecure && await GetClientCertificateAsync(request.Context) is X509Certificate2 certificate) if (request.IsSecure && await GetClientCertificateAsync(request.Context) is X509Certificate2 certificate)
@ -495,8 +495,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
response.StatusCode = context.Transaction.Response.Error switch response.StatusCode = context.Transaction.Response.Error switch
{ {
@ -540,8 +540,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// OWIN authentication middleware configured to use active authentication (which is the default mode) // OWIN authentication middleware configured to use active authentication (which is the default mode)
// are known to aggressively intercept 401 responses even if the request is already considered fully // are known to aggressively intercept 401 responses even if the request is already considered fully
@ -590,8 +590,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Similarly to the automatic authentication mode used by OWIN authentication middleware, // Similarly to the automatic authentication mode used by OWIN authentication middleware,
// the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if // the ASP.NET FormsAuthentication module aggressively intercepts 401 responses even if
@ -654,8 +654,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// Prevent the response from being cached. // Prevent the response from being cached.
response.Headers[Headers.CacheControl] = "no-store"; response.Headers[Headers.CacheControl] = "no-store";
@ -697,8 +697,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (string.IsNullOrEmpty(context.Transaction.Response.Error)) if (string.IsNullOrEmpty(context.Transaction.Response.Error))
{ {
@ -791,8 +791,8 @@ public static partial class OpenIddictValidationOwinHandlers
// This handler only applies to OWIN requests. If The OWIN request cannot be resolved, // This handler only applies to OWIN requests. If The OWIN request cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack. // this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetOwinRequest()?.Context.Response ?? var response = context.Transaction.GetOwinRequest()?.Context.Response
throw new InvalidOperationException(SR.GetResourceString(SR.ID0120)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
// If the response doesn't contain a WWW-Authenticate header, don't return an empty response. // If the response doesn't contain a WWW-Authenticate header, don't return an empty response.
if (!response.Headers.ContainsKey(Headers.WwwAuthenticate)) if (!response.Headers.ContainsKey(Headers.WwwAuthenticate))

8
src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpConfiguration.cs

@ -73,8 +73,8 @@ public sealed class OpenIddictValidationSystemNetHttpConfiguration : IConfigureO
// To work around this limitation, the OpenIddict System.Net.Http integration uses // To work around this limitation, the OpenIddict System.Net.Http integration uses
// an async-local context to flow per-instance properties and uses dynamic client // an async-local context to flow per-instance properties and uses dynamic client
// names to ensure the inner HttpClientHandler is not reused if the context differs. // names to ensure the inner HttpClientHandler is not reused if the context differs.
var context = OpenIddictValidationSystemNetHttpContext.Current ?? var context = OpenIddictValidationSystemNetHttpContext.Current
throw new InvalidOperationException(SR.FormatID0516(nameof(OpenIddictValidationSystemNetHttpContext))); ?? throw new InvalidOperationException(SR.FormatID0516(nameof(OpenIddictValidationSystemNetHttpContext)));
var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions>>().CurrentValue; var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions>>().CurrentValue;
@ -137,8 +137,8 @@ public sealed class OpenIddictValidationSystemNetHttpConfiguration : IConfigureO
// Register the user-defined HTTP client handler actions. // Register the user-defined HTTP client handler actions.
foreach (var action in settings.HttpClientHandlerActions) foreach (var action in settings.HttpClientHandlerActions)
{ {
options.HttpMessageHandlerBuilderActions.Add(builder => action(builder.PrimaryHandler as HttpClientHandler ?? options.HttpMessageHandlerBuilderActions.Add(builder => action(builder.PrimaryHandler as HttpClientHandler
throw new InvalidOperationException(SR.FormatID0373(typeof(HttpClientHandler).FullName)))); ?? throw new InvalidOperationException(SR.FormatID0373(typeof(HttpClientHandler).FullName))));
} }
} }

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

@ -79,8 +79,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
var identifier = OpenIddictValidationSystemNetHttpContext.ComputeStableId(OpenIddictValidationSystemNetHttpContext.Current); var identifier = OpenIddictValidationSystemNetHttpContext.ComputeStableId(OpenIddictValidationSystemNetHttpContext.Current);
var client = _factory.CreateClient( var client = _factory.CreateClient(
$"{typeof(OpenIddictValidationSystemNetHttpOptions).Assembly.GetName().Name}:{identifier}") ?? $"{typeof(OpenIddictValidationSystemNetHttpOptions).Assembly.GetName().Name}:{identifier}")
throw new InvalidOperationException(SR.GetResourceString(SR.ID0174)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0174));
// Create and store the HttpClient in the transaction properties. // Create and store the HttpClient in the transaction properties.
context.Transaction.SetProperty(typeof(HttpClient).FullName!, client); context.Transaction.SetProperty(typeof(HttpClient).FullName!, client);
@ -177,11 +177,11 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
#if NET #if NET
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
var client = context.Transaction.GetHttpClient() ?? var client = context.Transaction.GetHttpClient()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
// When supported, import the HTTP version and version policy from the client instance. // When supported, import the HTTP version and version policy from the client instance.
request.Version = client.DefaultRequestVersion; request.Version = client.DefaultRequestVersion;
@ -215,8 +215,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypes.Json)); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypes.Json));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue(Charsets.Utf8)); request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue(Charsets.Utf8));
@ -259,8 +259,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Some authorization servers are known to aggressively check user agents and encourage // Some authorization servers are known to aggressively check user agents and encourage
// developers to use unique user agents. While a default user agent is always added, // developers to use unique user agents. While a default user agent is always added,
@ -310,8 +310,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Attach the contact address specified in the options, if available. // Attach the contact address specified in the options, if available.
request.Headers.From = _options.CurrentValue.ContactAddress?.ToString(); request.Headers.From = _options.CurrentValue.ContactAddress?.ToString();
@ -345,8 +345,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: don't overwrite the authorization header if one was already set by another handler. // Note: don't overwrite the authorization header if one was already set by another handler.
if (request.Headers.Authorization is null && if (request.Headers.Authorization is null &&
@ -399,8 +399,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (context.Transaction.Request.Count is 0) if (context.Transaction.Request.Count is 0)
{ {
@ -454,12 +454,12 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// Note: a "using" statement is deliberately used here to dispose of the client in this handler. // Note: a "using" statement is deliberately used here to dispose of the client in this handler.
using var client = context.Transaction.GetHttpClient() ?? using var client = context.Transaction.GetHttpClient()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0372)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0372));
HttpResponseMessage response; HttpResponseMessage response;
@ -487,8 +487,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
} }
// 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
throw new InvalidOperationException(SR.GetResourceString(SR.ID0175))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0175)));
} }
} }
@ -515,8 +515,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP request cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var request = context.Transaction.GetHttpRequestMessage() ?? var request = context.Transaction.GetHttpRequestMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
request.Dispose(); request.Dispose();
@ -572,8 +572,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If no Content-Encoding header was returned, keep the response stream as-is. // If no Content-Encoding header was returned, keep the response stream as-is.
if (response.Content is not { Headers.ContentEncoding.Count: > 0 }) if (response.Content is not { Headers.ContentEncoding.Count: > 0 })
@ -698,8 +698,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// If the returned Content-Type doesn't indicate the response has a JSON payload, // If the returned Content-Type doesn't indicate the response has a JSON payload,
// ignore it and allow other handlers in the pipeline to process the HTTP response. // ignore it and allow other handlers in the pipeline to process the HTTP response.
@ -774,8 +774,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
if (response.Headers.WwwAuthenticate.Count is 0) if (response.Headers.WwwAuthenticate.Count is 0)
{ {
@ -894,8 +894,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
// At this stage, return a generic error based on the HTTP status code if no // At this stage, return a generic error based on the HTTP status code if no
// error could be extracted from the payload or from the WWW-Authenticate header. // error could be extracted from the payload or from the WWW-Authenticate header.
@ -961,8 +961,8 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved, // This handler only applies to System.Net.Http requests. If the HTTP response cannot be resolved,
// this may indicate that the request was incorrectly processed by another client stack. // this may indicate that the request was incorrectly processed by another client stack.
var response = context.Transaction.GetHttpResponseMessage() ?? var response = context.Transaction.GetHttpResponseMessage()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0173)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0173));
response.Dispose(); response.Dispose();

44
src/OpenIddict.Validation/OpenIddictValidationBuilder.cs

@ -217,9 +217,9 @@ public sealed class OpenIddictValidationBuilder
public OpenIddictValidationBuilder AddEncryptionCertificate( public OpenIddictValidationBuilder AddEncryptionCertificate(
Assembly assembly, string resource, string? password) Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate retrieved from an embedded resource. /// Registers an encryption certificate retrieved from an embedded resource.
@ -236,8 +236,8 @@ public sealed class OpenIddictValidationBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddEncryptionCertificate(stream, password, flags); return AddEncryptionCertificate(stream, password, flags);
} }
@ -250,9 +250,9 @@ public sealed class OpenIddictValidationBuilder
/// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns>
public OpenIddictValidationBuilder AddEncryptionCertificate(Stream stream, string? password) public OpenIddictValidationBuilder AddEncryptionCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers an encryption certificate extracted from a stream. /// Registers an encryption certificate extracted from a stream.
@ -290,9 +290,9 @@ public sealed class OpenIddictValidationBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddEncryptionCertificate( return AddEncryptionCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {
@ -444,9 +444,9 @@ public sealed class OpenIddictValidationBuilder
/// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns>
public OpenIddictValidationBuilder AddSigningCertificate(Assembly assembly, string resource, string? password) public OpenIddictValidationBuilder AddSigningCertificate(Assembly assembly, string resource, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate retrieved from an embedded resource. /// Registers a signing certificate retrieved from an embedded resource.
@ -463,8 +463,8 @@ public sealed class OpenIddictValidationBuilder
ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource); ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddSigningCertificate(stream, password, flags); return AddSigningCertificate(stream, password, flags);
} }
@ -477,9 +477,9 @@ public sealed class OpenIddictValidationBuilder
/// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns> /// <returns>The <see cref="OpenIddictValidationBuilder"/> instance.</returns>
public OpenIddictValidationBuilder AddSigningCertificate(Stream stream, string? password) public OpenIddictValidationBuilder AddSigningCertificate(Stream stream, string? password)
// Note: ephemeral key sets are currently not supported on macOS. // Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(stream, password, OperatingSystem.IsMacOS() ? => AddSigningCertificate(stream, password, OperatingSystem.IsMacOS()
X509KeyStorageFlags.MachineKeySet : ? X509KeyStorageFlags.MachineKeySet
X509KeyStorageFlags.EphemeralKeySet); : X509KeyStorageFlags.EphemeralKeySet);
/// <summary> /// <summary>
/// Registers a signing certificate extracted from a stream. /// Registers a signing certificate extracted from a stream.
@ -516,9 +516,9 @@ public sealed class OpenIddictValidationBuilder
ArgumentException.ThrowIfNullOrEmpty(thumbprint); ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddSigningCertificate( return AddSigningCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.CurrentUser, thumbprint)
GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? ?? GetCertificate(StoreLocation.LocalMachine, thumbprint)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{ {

28
src/OpenIddict.Validation/OpenIddictValidationHandlerDescriptor.cs

@ -158,8 +158,11 @@ public sealed class OpenIddictValidationHandlerDescriptor
/// <param name="handler">The handler instance.</param> /// <param name="handler">The handler instance.</param>
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler) public Builder<TContext> UseInlineHandler(Func<TContext, ValueTask> handler)
=> UseSingletonHandler(new OpenIddictValidationHandler<TContext>(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return UseSingletonHandler(new OpenIddictValidationHandler<TContext>(handler));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified scoped handler. /// Configures the descriptor to use the specified scoped handler.
@ -179,8 +182,11 @@ public sealed class OpenIddictValidationHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseScopedHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictValidationHandler<TContext> where THandler : class, IOpenIddictValidationHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Scoped(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Scoped(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -200,8 +206,11 @@ public sealed class OpenIddictValidationHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory) public Builder<TContext> UseSingletonHandler<THandler>(Func<IServiceProvider, THandler> factory)
where THandler : class, IOpenIddictValidationHandler<TContext> where THandler : class, IOpenIddictValidationHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(factory ?? {
throw new ArgumentNullException(nameof(factory)))); ArgumentNullException.ThrowIfNull(factory);
return SetServiceDescriptor(ServiceDescriptor.Singleton(factory));
}
/// <summary> /// <summary>
/// Configures the descriptor to use the specified singleton handler. /// Configures the descriptor to use the specified singleton handler.
@ -211,8 +220,11 @@ public sealed class OpenIddictValidationHandlerDescriptor
/// <returns>The builder instance, so that calls can be easily chained.</returns> /// <returns>The builder instance, so that calls can be easily chained.</returns>
public Builder<TContext> UseSingletonHandler<THandler>(THandler handler) public Builder<TContext> UseSingletonHandler<THandler>(THandler handler)
where THandler : class, IOpenIddictValidationHandler<TContext> where THandler : class, IOpenIddictValidationHandler<TContext>
=> SetServiceDescriptor(ServiceDescriptor.Singleton(handler ?? {
throw new ArgumentNullException(nameof(handler)))); ArgumentNullException.ThrowIfNull(handler);
return SetServiceDescriptor(ServiceDescriptor.Singleton(handler));
}
/// <summary> /// <summary>
/// Build a new descriptor instance, based on the parameters that were previously set. /// Build a new descriptor instance, based on the parameters that were previously set.

7
src/OpenIddict.Validation/OpenIddictValidationHandlers.Introspection.cs

@ -378,9 +378,10 @@ public static partial class OpenIddictValidationHandlers
context.Options.TokenValidationParameters.RoleClaimType); context.Options.TokenValidationParameters.RoleClaimType);
// Resolve the issuer that will be attached to the claims created by this handler. // Resolve the issuer that will be attached to the claims created by this handler.
var issuer = context.Options.ClaimsIssuer ?? var issuer = context.Options.ClaimsIssuer
context.Configuration.Issuer?.AbsoluteUri ?? ?? context.Configuration.Issuer?.AbsoluteUri
context.BaseUri?.AbsoluteUri ?? ClaimsIdentity.DefaultIssuer; ?? context.BaseUri?.AbsoluteUri
?? ClaimsIdentity.DefaultIssuer;
foreach (var parameter in context.Response.GetParameters()) foreach (var parameter in context.Response.GetParameters())
{ {

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

@ -492,8 +492,8 @@ public static partial class OpenIddictValidationHandlers
// the "azp" or "client_id" claim if no "oi_prst" claim was found in the principal. // the "azp" or "client_id" claim if no "oi_prst" claim was found in the principal.
if (!context.Principal.HasClaim(Claims.Private.Presenter)) if (!context.Principal.HasClaim(Claims.Private.Presenter))
{ {
var presenter = context.Principal.GetClaim(Claims.AuthorizedParty) ?? var presenter = context.Principal.GetClaim(Claims.AuthorizedParty)
context.Principal.GetClaim(Claims.ClientId); ?? context.Principal.GetClaim(Claims.ClientId);
if (!string.IsNullOrEmpty(presenter)) if (!string.IsNullOrEmpty(presenter))
{ {
@ -922,8 +922,8 @@ public static partial class OpenIddictValidationHandlers
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006)); Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017)); Debug.Assert(!string.IsNullOrEmpty(context.TokenId), SR.GetResourceString(SR.ID4017));
var token = await _tokenManager.FindByIdAsync(context.TokenId) ?? var token = await _tokenManager.FindByIdAsync(context.TokenId)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
if (!await _tokenManager.HasStatusAsync(token, Statuses.Valid)) if (!await _tokenManager.HasStatusAsync(token, Statuses.Valid))
{ {
@ -1078,9 +1078,9 @@ public static partial class OpenIddictValidationHandlers
{ {
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
var claims = context.SecurityTokenDescriptor.Claims is not null ? var claims = context.SecurityTokenDescriptor.Claims is not null
new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal) : ? new Dictionary<string, object>(context.SecurityTokenDescriptor.Claims, StringComparer.Ordinal)
new Dictionary<string, object>(StringComparer.Ordinal); : new Dictionary<string, object>(StringComparer.Ordinal);
// For client assertions, set the public audience claims // For client assertions, set the public audience claims
// using the private audience claims from the security principal. // using the private audience claims from the security principal.

4
src/OpenIddict.Validation/OpenIddictValidationHandlers.cs

@ -168,8 +168,8 @@ public static partial class OpenIddictValidationHandlers
// Resolve and attach the server configuration to the context if none has been set already. // Resolve and attach the server configuration to the context if none has been set already.
context.Configuration ??= await context.Options.ConfigurationManager context.Configuration ??= await context.Options.ConfigurationManager
.GetConfigurationAsync(context.CancellationToken) .GetConfigurationAsync(context.CancellationToken)
.WaitAsync(context.CancellationToken) ?? .WaitAsync(context.CancellationToken)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0140)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0140));
} }
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) && catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception) &&

8
src/OpenIddict.Validation/OpenIddictValidationRetriever.cs

@ -42,16 +42,16 @@ public sealed class OpenIddictValidationRetriever : IConfigurationRetriever<Open
cancel.ThrowIfCancellationRequested(); cancel.ThrowIfCancellationRequested();
var configuration = await _service.GetConfigurationAsync(uri, cancel) ?? var configuration = await _service.GetConfigurationAsync(uri, cancel)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
if (configuration.JsonWebKeySetUri is null) if (configuration.JsonWebKeySetUri is null)
{ {
throw new InvalidOperationException(SR.GetResourceString(SR.ID0146)); throw new InvalidOperationException(SR.GetResourceString(SR.ID0146));
} }
configuration.JsonWebKeySet = await _service.GetSecurityKeysAsync(configuration.JsonWebKeySetUri, cancel) ?? configuration.JsonWebKeySet = await _service.GetSecurityKeysAsync(configuration.JsonWebKeySetUri, cancel)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
// Copy the signing keys found in the JSON Web Key Set to the SigningKeys collection. // Copy the signing keys found in the JSON Web Key Set to the SigningKeys collection.
foreach (var key in configuration.JsonWebKeySet.GetSigningKeys()) foreach (var key in configuration.JsonWebKeySet.GetSigningKeys())

8
src/OpenIddict.Validation/OpenIddictValidationService.cs

@ -99,8 +99,8 @@ public class OpenIddictValidationService
request = await ApplyConfigurationRequestAsync(); request = await ApplyConfigurationRequestAsync();
var response = await ExtractConfigurationResponseAsync(); var response = await ExtractConfigurationResponseAsync();
return await HandleConfigurationResponseAsync() ?? return await HandleConfigurationResponseAsync()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0145)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0145));
async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync() async ValueTask<OpenIddictRequest> PrepareConfigurationRequestAsync()
{ {
@ -222,8 +222,8 @@ public class OpenIddictValidationService
var response = await ExtractJsonWebKeySetResponseAsync(); var response = await ExtractJsonWebKeySetResponseAsync();
return await HandleJsonWebKeySetResponseAsync() ?? return await HandleJsonWebKeySetResponseAsync()
throw new InvalidOperationException(SR.GetResourceString(SR.ID0147)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0147));
async ValueTask<OpenIddictRequest> PrepareJsonWebKeySetRequestAsync() async ValueTask<OpenIddictRequest> PrepareJsonWebKeySetRequestAsync()
{ {

4
test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.cs

@ -408,8 +408,8 @@ public abstract partial class OpenIddictValidationIntegrationTests
static X509Certificate2 GetSigningCertificate(Assembly assembly, string resource) static X509Certificate2 GetSigningCertificate(Assembly assembly, string resource)
{ {
using var stream = assembly.GetManifestResourceStream(resource) ?? using var stream = assembly.GetManifestResourceStream(resource)
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
using var buffer = new MemoryStream(); using var buffer = new MemoryStream();
stream.CopyTo(buffer); stream.CopyTo(buffer);

Loading…
Cancel
Save