diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index 8d29abc1..5b70f1cc 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -2045,6 +2045,10 @@ JWT authorization responses can only be encrypted using 'RSA-OAEP' with 'A128CBC
The '{0}' JWT Secured Authorization Response Mode required by the client registration is not supported by the authorization server.
Ensure the server configuration lists this response mode in 'response_modes_supported' or set 'OpenIddictClientRegistration.RequireJwtSecuredAuthorizationResponses' to false.
+
+
+ The '{0}' response mode negotiated for the authorization request has no JWT Secured Authorization Response Mode variant.
+When 'OpenIddictClientRegistration.RequireJwtSecuredAuthorizationResponses' is set to true, only the 'query', 'fragment' and 'form_post' response modes (or their JWT variants) can be used.
The backchannel authentication request was not correctly extracted.
@@ -3141,6 +3145,9 @@ Error URI: {2}
The JWT authorization response was signed using an algorithm that is not allowed.
+
+ The JWT authorization response was not encrypted, which is required by the client registration.
+
The '{0}' parameter shouldn't be null or empty at this point.
diff --git a/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs b/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
index 37d35fab..e8867b1e 100644
--- a/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
+++ b/src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
@@ -701,7 +701,9 @@ public static partial class OpenIddictClientAspNetCoreHandlers
_ => context.Options.ResponseModes.Intersect(context.Registration.ResponseModes, StringComparer.Ordinal).ToList()
},
- SupportedServerResponseModes: context.Configuration.ResponseModesSupported) switch
+ // Note: when JWT Secured Authorization Response Modes are required, the base response modes are
+ // negotiated based on the JWT variants supported by the server (see AttachJwtResponseMode).
+ SupportedServerResponseModes: OpenIddictClientHandlers.AttachJwtResponseMode.GetNegotiableServerResponseModes(context)) switch
{
// If both the client and the server support response_mode=form_post, use it if the response
// types contain a value that prevents response_mode=query from being used (token/id_token).
diff --git a/src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs b/src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs
index 21a08a88..edef7779 100644
--- a/src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs
+++ b/src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs
@@ -720,7 +720,9 @@ public static partial class OpenIddictClientOwinHandlers
_ => context.Options.ResponseModes.Intersect(context.Registration.ResponseModes, StringComparer.Ordinal).ToList()
},
- SupportedServerResponseModes: context.Configuration.ResponseModesSupported) switch
+ // Note: when JWT Secured Authorization Response Modes are required, the base response modes are
+ // negotiated based on the JWT variants supported by the server (see AttachJwtResponseMode).
+ SupportedServerResponseModes: OpenIddictClientHandlers.AttachJwtResponseMode.GetNegotiableServerResponseModes(context)) switch
{
// If both the client and the server support response_mode=form_post, use it if the response
// types contain a value that prevents response_mode=query from being used (token/id_token).
diff --git a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs
index ac56bfa7..4acb342a 100644
--- a/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs
+++ b/src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs
@@ -1476,7 +1476,9 @@ public static partial class OpenIddictClientSystemIntegrationHandlers
_ => context.Options.ResponseModes.Intersect(context.Registration.ResponseModes, StringComparer.Ordinal).ToList()
},
- SupportedServerResponseModes: context.Configuration.ResponseModesSupported) switch
+ // Note: when JWT Secured Authorization Response Modes are required, the base response modes are
+ // negotiated based on the JWT variants supported by the server (see AttachJwtResponseMode).
+ SupportedServerResponseModes: OpenIddictClientHandlers.AttachJwtResponseMode.GetNegotiableServerResponseModes(context)) switch
{
// When using the web authentication broker on Windows, if both the client and
// the server support response_mode=fragment, use it if the response types contain
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Jarm.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Jarm.cs
index f89167a9..cbf9a6d3 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.Jarm.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Jarm.cs
@@ -52,20 +52,85 @@ public static partial class OpenIddictClientHandlers
ResponseModes.Jwt or ResponseModes.QueryJwt or
ResponseModes.FragmentJwt or ResponseModes.FormPostJwt => context.ResponseMode,
- _ => throw new InvalidOperationException(SR.FormatID0647(context.ResponseMode))
+ _ => throw new InvalidOperationException(SR.FormatID0648(context.ResponseMode))
};
// If the server explicitly lists the supported response modes, ensure the JWT variant is supported.
- if (context.Configuration.ResponseModesSupported.Count is > 0 &&
- !context.Configuration.ResponseModesSupported.Contains(mode))
+ var server = context.Configuration.ResponseModesSupported;
+ if (server.Count is > 0 && !server.Contains(mode))
{
- throw new InvalidOperationException(SR.FormatID0647(mode));
+ // If the specific variant is not listed but the generic "jwt" response mode is, use it when it
+ // resolves to the same variant on the server side ("query.jwt" if the response type doesn't
+ // contain id_token or token, "fragment.jwt" otherwise).
+ //
+ // See https://openid.net/specs/oauth-v2-jarm.html#section-2.3.4 for more information.
+ if (server.Contains(ResponseModes.Jwt) && string.Equals(mode, ResolveJwtResponseMode(context.ResponseType), StringComparison.Ordinal))
+ {
+ mode = ResponseModes.Jwt;
+ }
+
+ else
+ {
+ throw new InvalidOperationException(SR.FormatID0647(mode));
+ }
}
context.ResponseMode = mode;
return ValueTask.CompletedTask;
}
+
+ ///
+ /// Resolves the response modes supported by the authorization server that can be negotiated by the
+ /// handlers responsible for selecting the base response mode ("query", "fragment" or "form_post").
+ /// When the client registration requires JWT Secured Authorization Response Modes (JARM) and the server
+ /// explicitly lists the response modes it supports, a base response mode is only considered supported
+ /// if its JWT variant is listed (or if "jwt" is listed and resolves to that variant, which is true for
+ /// "query" and "fragment"). Otherwise, the response modes listed by the server are returned as-is.
+ ///
+ /// The context associated with the event to process.
+ /// The response modes that can be negotiated.
+ public static ICollection GetNegotiableServerResponseModes(ProcessChallengeContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ var server = context.Configuration.ResponseModesSupported;
+ if (context.Registration is not { RequireJwtSecuredAuthorizationResponses: true } || server.Count is 0)
+ {
+ return server;
+ }
+
+ var modes = new HashSet(StringComparer.Ordinal);
+
+ if (server.Contains(ResponseModes.QueryJwt) || server.Contains(ResponseModes.Jwt))
+ {
+ modes.Add(ResponseModes.Query);
+ }
+
+ if (server.Contains(ResponseModes.FragmentJwt) || server.Contains(ResponseModes.Jwt))
+ {
+ modes.Add(ResponseModes.Fragment);
+ }
+
+ if (server.Contains(ResponseModes.FormPostJwt))
+ {
+ modes.Add(ResponseModes.FormPost);
+ }
+
+ // Note: if the server doesn't list any JWT response mode, the listed response modes are returned as-is
+ // so that the base response mode can be negotiated and a descriptive exception thrown by this handler.
+ if (modes.Count is 0)
+ {
+ return server;
+ }
+
+ return modes;
+ }
+
+ private static string ResolveJwtResponseMode(string? type)
+ => type?.Split(Separators.Space) is IList types &&
+ (types.Contains(ResponseTypes.IdToken) || types.Contains(ResponseTypes.Token))
+ ? ResponseModes.FragmentJwt : ResponseModes.QueryJwt;
}
///
@@ -218,6 +283,15 @@ public static partial class OpenIddictClientHandlers
return;
}
+ // If the client registration requires encrypted responses, reject JWTs that were only signed.
+ //
+ // See https://openid.net/specs/oauth-v2-jarm.html#section-2.2 for more information.
+ if (token.InnerToken is null && context.Registration.RequireEncryptedAuthorizationResponses)
+ {
+ Reject(SR.GetResourceString(SR.ID2326), SR.ID2326);
+ return;
+ }
+
if (token.InnerToken is not null)
{
token = token.InnerToken;
@@ -225,13 +299,15 @@ public static partial class OpenIddictClientHandlers
// Ensure the JWT was signed using the algorithm registered for the client (the equivalent of the
// "authorization_signed_response_alg" client metadata) or, if no algorithm was explicitly set,
- // using one of the algorithms advertised by the server in "authorization_signing_alg_values_supported".
+ // using one of the algorithms advertised by the server in "authorization_signing_alg_values_supported"
+ // (or RS256, the default value defined by JARM, if the server doesn't advertise any algorithm).
//
- // See https://openid.net/specs/oauth-v2-jarm.html#section-2.4 for more information.
+ // See https://openid.net/specs/oauth-v2-jarm.html#section-2.4 and #section-3 for more information.
if (!string.IsNullOrEmpty(context.Registration.AuthorizationResponseSigningAlgorithm)
? !string.Equals(token.Alg, context.Registration.AuthorizationResponseSigningAlgorithm, StringComparison.Ordinal)
- : context.Configuration.AuthorizationSigningAlgValuesSupported.Count is > 0 &&
- !context.Configuration.AuthorizationSigningAlgValuesSupported.Contains(token.Alg))
+ : context.Configuration.AuthorizationSigningAlgValuesSupported.Count is > 0
+ ? !context.Configuration.AuthorizationSigningAlgValuesSupported.Contains(token.Alg)
+ : !string.Equals(token.Alg, SecurityAlgorithms.RsaSha256, StringComparison.Ordinal))
{
Reject(SR.GetResourceString(SR.ID2325), SR.ID2325);
return;
diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
index 99eeffdc..dc2af365 100644
--- a/src/OpenIddict.Client/OpenIddictClientHandlers.cs
+++ b/src/OpenIddict.Client/OpenIddictClientHandlers.cs
@@ -5911,7 +5911,9 @@ public static partial class OpenIddictClientHandlers
_ => context.Options.ResponseModes.Intersect(context.Registration.ResponseModes, StringComparer.Ordinal).ToList()
},
- SupportedServerResponseModes: context.Configuration.ResponseModesSupported) switch
+ // Note: when JWT Secured Authorization Response Modes are required, the base response modes are
+ // negotiated based on the JWT variants supported by the server (see AttachJwtResponseMode).
+ SupportedServerResponseModes: OpenIddictClientHandlers.AttachJwtResponseMode.GetNegotiableServerResponseModes(context)) switch
{
// If the list of response modes supported by the client is empty, abort the challenge operation.
({ Count: 0 }, { Count: _ }) => throw new InvalidOperationException(SR.GetResourceString(SR.ID0362)),
diff --git a/src/OpenIddict.Client/OpenIddictClientRegistration.cs b/src/OpenIddict.Client/OpenIddictClientRegistration.cs
index f3aaebc9..3155dd93 100644
--- a/src/OpenIddict.Client/OpenIddictClientRegistration.cs
+++ b/src/OpenIddict.Client/OpenIddictClientRegistration.cs
@@ -184,10 +184,26 @@ public sealed class OpenIddictClientRegistration
/// responses (JARM), which corresponds to the "authorization_signed_response_alg" client metadata
/// registered for this client. If no value is explicitly set, the JWT authorization responses signed
/// using any of the algorithms advertised by the server via "authorization_signing_alg_values_supported"
- /// are accepted (or any asymmetric algorithm, if the server doesn't advertise the supported algorithms).
+ /// are accepted or, if the server doesn't advertise the supported algorithms, only RS256 (the default
+ /// value defined by the JARM specification) is accepted.
///
+ ///
+ /// Note: accepting all the advertised algorithms when no value is set is a deliberate relaxation of the JARM
+ /// specification (that defines RS256 as the default value), as clients that don't use dynamic client
+ /// registration have no way to tell the server which algorithm they expect.
+ ///
public string? AuthorizationResponseSigningAlgorithm { get; set; }
+ ///
+ /// Gets or sets a boolean indicating whether JWT authorization responses (JARM) must be encrypted, which
+ /// corresponds to the "authorization_encrypted_response_alg" client metadata being registered for this client.
+ /// When enabled, JWT authorization responses that are only signed are rejected to prevent downgrade attacks.
+ ///
+ ///
+ /// Note: encrypted responses are decrypted using the encryption credentials registered in the client options.
+ ///
+ public bool RequireEncryptedAuthorizationResponses { get; set; }
+
///
/// Gets the client authentication methods allowed by the client instance.
/// If no value is explicitly set, all the methods enabled in the client options can be used.
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs
index d438891a..4988d730 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs
+++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs
@@ -80,9 +80,11 @@ public static partial class OpenIddictServerHandlers
= OpenIddictServerHandlerDescriptor.CreateBuilder()
.AddFilter()
.UseSingletonHandler()
- // Note: this handler is deliberately executed after the custom handlers using the default order
- // so that the parameters they add to the response are also included in the generated token.
- .SetOrder(50_000)
+ // Note: this handler is deliberately executed as late as possible (just before the host handlers
+ // responsible for applying the response, whose order starts at 250_000) so that the parameters added
+ // by custom handlers are also included in the generated token. Parameters added by handlers whose
+ // order is 249_000 or higher are not protected by the JWT and are ignored by conforming clients.
+ .SetOrder(249_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
@@ -239,10 +241,10 @@ public static partial class OpenIddictServerHandlers
// Note: the algorithms advertised in the discovery document are JWA short names, so the
// algorithm attached to the signing credentials (that can be expressed using the XML-DSig
// form, e.g "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") is normalized first.
- context.SigningCredentials = credentials.SigningCredentials.FirstOrDefault(credentials =>
+ context.SigningCredentials = NormalizeSigningCredentials(credentials.SigningCredentials.FirstOrDefault(credentials =>
credentials.Key is AsymmetricSecurityKey &&
string.Equals(GetJwaSigningAlgorithm(credentials.Algorithm), algorithm, StringComparison.Ordinal))
- ?? throw new InvalidOperationException(SR.FormatID0644(algorithm, Settings.AuthorizationResponse.SigningAlgorithm));
+ ?? throw new InvalidOperationException(SR.FormatID0644(algorithm, Settings.AuthorizationResponse.SigningAlgorithm)));
}
// Note: JWT authorization responses are only encrypted if the client application explicitly opted in
@@ -345,6 +347,25 @@ public static partial class OpenIddictServerHandlers
_ => algorithm
};
+ ///
+ /// Returns signing credentials whose algorithm is expressed using its JWA short name (RFC 7518, section 3.1),
+ /// so that the "alg" header of the generated JWT is a registered value (RFC 7515, section 4.1.1).
+ /// The specified credentials are returned as-is if they already use a JWA algorithm name.
+ ///
+ internal static SigningCredentials NormalizeSigningCredentials(SigningCredentials credentials)
+ {
+ var algorithm = GetJwaSigningAlgorithm(credentials.Algorithm);
+ if (string.Equals(algorithm, credentials.Algorithm, StringComparison.Ordinal))
+ {
+ return credentials;
+ }
+
+ return new SigningCredentials(credentials.Key, algorithm)
+ {
+ CryptoProviderFactory = credentials.CryptoProviderFactory
+ };
+ }
+
///
/// Determines whether the JWT response mode specified in the request is enabled.
///
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
index 707fdba3..643808c1 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
+++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
@@ -589,6 +589,15 @@ public static partial class OpenIddictServerHandlers
{
context.ResponseModes.Add(ResponseModes.Jwt);
}
+
+ // If JWT Secured Authorization Response Modes are required, requests using the plain response modes
+ // are always rejected: in this case, these modes are not returned as they are not supported by the
+ // server (see RFC 8414, section 2 for the definition of the "response_modes_supported" metadata).
+ if (context.Options.RequireJwtSecuredAuthorizationResponses)
+ {
+ context.ResponseModes.RemoveWhere(static mode => mode is not (ResponseModes.Jwt or
+ ResponseModes.QueryJwt or ResponseModes.FragmentJwt or ResponseModes.FormPostJwt));
+ }
}
return ValueTask.CompletedTask;
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
index 9b959b81..af4659e7 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
+++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
@@ -1661,11 +1661,15 @@ public static partial class OpenIddictServerHandlers
// overridden per client by AttachAuthorizationResponseSecurityCredentials.
//
// See https://openid.net/specs/oauth-v2-jarm.html#section-3 for more information.
+ //
+ // Note: the "alg" header MUST be a JWA registered value (RFC 7515, section 4.1.1), so credentials
+ // using the XML-DSig form of an algorithm are normalized to use the corresponding JWA short name.
TokenTypeIdentifiers.Private.AuthorizationResponse
- => credentials.SigningCredentials.FirstOrDefault(static credentials =>
- credentials.Key is AsymmetricSecurityKey &&
- Authentication.GetJwaSigningAlgorithm(credentials.Algorithm) is SecurityAlgorithms.RsaSha256) ??
- credentials.SigningCredentials.First(static credentials => credentials.Key is AsymmetricSecurityKey),
+ => Authentication.NormalizeSigningCredentials(
+ credentials.SigningCredentials.FirstOrDefault(static credentials =>
+ credentials.Key is AsymmetricSecurityKey &&
+ Authentication.GetJwaSigningAlgorithm(credentials.Algorithm) is SecurityAlgorithms.RsaSha256) ??
+ credentials.SigningCredentials.First(static credentials => credentials.Key is AsymmetricSecurityKey)),
_ => credentials.SigningCredentials[0]
};
diff --git a/src/OpenIddict.Server/OpenIddictServerOptions.cs b/src/OpenIddict.Server/OpenIddictServerOptions.cs
index 08c4772a..97f4747b 100644
--- a/src/OpenIddict.Server/OpenIddictServerOptions.cs
+++ b/src/OpenIddict.Server/OpenIddictServerOptions.cs
@@ -772,6 +772,11 @@ public sealed class OpenIddictServerOptions
/// The JWT is also encrypted if the client application opted in using the
/// setting.
///
+ ///
+ /// Note: the JWT is generated by a handler of the ApplyAuthorizationResponseContext event whose order is 249_000.
+ /// Custom handlers adding parameters to the authorization response must use a lower order for these parameters
+ /// to be included in the JWT (parameters added later are not protected and are ignored by conforming clients).
+ ///
public bool EnableJwtSecuredAuthorizationResponses { get; set; }
///
diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Jarm.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Jarm.cs
index 663971ee..1284b12a 100644
--- a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Jarm.cs
+++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Jarm.cs
@@ -74,6 +74,91 @@ public class OpenIddictClientHandlersJarmTests
Assert.Equal(SR.FormatID0647(ResponseModes.QueryJwt), exception.Message);
}
+ [Fact]
+ public async Task AttachJwtResponseMode_ThrowsAnExceptionForResponseModeWithoutJwtVariant()
+ {
+ // Arrange
+ using var provider = CreateProvider(required: true);
+ var context = new ProcessChallengeContext(CreateTransaction(provider)) { ResponseMode = "web_message" };
+
+ // Act and assert
+ var exception = await Assert.ThrowsAsync(async () =>
+ await new AttachJwtResponseMode().HandleAsync(context));
+
+ Assert.Equal(SR.FormatID0648("web_message"), exception.Message);
+ }
+
+ [Theory]
+ [InlineData(ResponseModes.Query, ResponseTypes.Code, ResponseModes.Jwt)]
+ [InlineData(ResponseModes.Fragment, ResponseTypes.Code + " " + ResponseTypes.IdToken, ResponseModes.Jwt)]
+ [InlineData(ResponseModes.Query, ResponseTypes.Code + " " + ResponseTypes.IdToken, null)]
+ [InlineData(ResponseModes.Fragment, ResponseTypes.Code, null)]
+ [InlineData(ResponseModes.FormPost, ResponseTypes.Code, null)]
+ public async Task AttachJwtResponseMode_GenericJwtResponseModeIsUsedWhenVariantIsNotListed(string mode, string type, string? expected)
+ {
+ // Arrange
+ using var provider = CreateProvider(required: true);
+ var transaction = CreateTransaction(provider);
+ transaction.Configuration.ResponseModesSupported.Add(ResponseModes.Jwt);
+
+ var context = new ProcessChallengeContext(transaction) { ResponseMode = mode, ResponseType = type };
+
+ // Act and assert
+ if (expected is null)
+ {
+ await Assert.ThrowsAsync(async () =>
+ await new AttachJwtResponseMode().HandleAsync(context));
+ }
+
+ else
+ {
+ await new AttachJwtResponseMode().HandleAsync(context);
+ Assert.Equal(expected, context.ResponseMode);
+ }
+ }
+
+ [Theory]
+ [InlineData(true, new string[0], new string[0])]
+ [InlineData(true, new[] { ResponseModes.Query, ResponseModes.FormPost }, new[] { ResponseModes.FormPost, ResponseModes.Query })]
+ [InlineData(true, new[] { ResponseModes.QueryJwt }, new[] { ResponseModes.Query })]
+ [InlineData(true, new[] { ResponseModes.Query, ResponseModes.FormPostJwt }, new[] { ResponseModes.FormPost })]
+ [InlineData(true, new[] { ResponseModes.Jwt }, new[] { ResponseModes.Fragment, ResponseModes.Query })]
+ [InlineData(true, new[] { ResponseModes.FragmentJwt, ResponseModes.FormPostJwt }, new[] { ResponseModes.FormPost, ResponseModes.Fragment })]
+ [InlineData(false, new[] { ResponseModes.QueryJwt }, new[] { ResponseModes.QueryJwt })]
+ public void GetNegotiableServerResponseModes_ReturnsExpectedModes(bool required, string[] listed, string[] expected)
+ {
+ // Arrange
+ using var provider = CreateProvider(required);
+ var transaction = CreateTransaction(provider);
+ transaction.Configuration.ResponseModesSupported.UnionWith(listed);
+
+ var context = new ProcessChallengeContext(transaction);
+
+ // Act
+ var modes = AttachJwtResponseMode.GetNegotiableServerResponseModes(context);
+
+ // Assert
+ Assert.Equal(expected, modes.OrderBy(static mode => mode, StringComparer.Ordinal).ToArray());
+ }
+
+ [Fact]
+ public async Task AttachResponseMode_BaseResponseModeIsNegotiatedWhenServerOnlyListsJwtResponseModes()
+ {
+ // Arrange
+ using var provider = CreateProvider(required: true);
+ var transaction = CreateTransaction(provider);
+ transaction.Configuration.ResponseModesSupported.UnionWith([ResponseModes.Jwt, ResponseModes.QueryJwt]);
+
+ var context = new ProcessChallengeContext(transaction) { ResponseType = ResponseTypes.Code };
+
+ // Act
+ await new AttachResponseMode().HandleAsync(context);
+ await new AttachJwtResponseMode().HandleAsync(context);
+
+ // Assert
+ Assert.Equal(ResponseModes.QueryJwt, context.ResponseMode);
+ }
+
[Theory]
[InlineData(false)]
[InlineData(true)]
@@ -184,6 +269,46 @@ public class OpenIddictClientHandlersJarmTests
}
}
+ [Fact]
+ public async Task ValidateAuthorizationResponseToken_Rs256IsRequiredWhenNoAlgorithmIsRegisteredOrAdvertised()
+ {
+ // Arrange
+ using var provider = CreateProvider(required: true);
+ var context = CreateAuthenticationContext(provider, CreateToken(
+ signing: new SigningCredentials(ServerSigningKey, SecurityAlgorithms.RsaSsaPssSha256)));
+
+ // Act
+ await CreateHandler(provider).HandleAsync(context);
+
+ // Assert
+ Assert.True(context.IsRejected);
+ Assert.Equal(SR.GetResourceString(SR.ID2325), context.ErrorDescription);
+ }
+
+ [Theory]
+ [InlineData(false, false, false)]
+ [InlineData(false, true, true)]
+ [InlineData(true, true, false)]
+ [InlineData(true, false, false)]
+ public async Task ValidateAuthorizationResponseToken_EncryptionIsValidatedWhenRequired(bool encrypted, bool required, bool rejected)
+ {
+ // Arrange
+ using var provider = CreateProvider(required: true);
+ var context = CreateAuthenticationContext(provider, CreateToken(encryption: encrypted ? GetEncryptionCredentials(provider) : null));
+ context.Registration.RequireEncryptedAuthorizationResponses = required;
+
+ // Act
+ await CreateHandler(provider).HandleAsync(context);
+
+ // Assert
+ Assert.Equal(rejected, context.IsRejected);
+
+ if (rejected)
+ {
+ Assert.Equal(SR.GetResourceString(SR.ID2326), context.ErrorDescription);
+ }
+ }
+
[Fact]
public async Task ValidateAuthorizationResponseToken_ErrorsAreExtractedFromToken()
{
diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.AuthorizationResponse.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.AuthorizationResponse.cs
index 84d396ba..67909668 100644
--- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.AuthorizationResponse.cs
+++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.AuthorizationResponse.cs
@@ -70,6 +70,30 @@ public abstract partial class OpenIddictServerIntegrationTests
Assert.Null(response[Metadata.AuthorizationEncryptionAlgValuesSupported]);
}
+ [Fact]
+ public async Task HandleConfigurationRequest_PlainResponseModesAreNotReturnedWhenJwtResponseModesAreRequired()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableJwtSecuredAuthorizationResponses();
+ options.RequireJwtSecuredAuthorizationResponses();
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.GetAsync("/.well-known/openid-configuration");
+
+ // Assert
+ var modes = (ImmutableArray?) response[Metadata.ResponseModesSupported];
+ Assert.NotNull(modes);
+ Assert.Equal(
+ new[] { ResponseModes.FormPostJwt, ResponseModes.FragmentJwt, ResponseModes.Jwt, ResponseModes.QueryJwt },
+ modes.Value.Select(static mode => mode!).OrderBy(static mode => mode, StringComparer.Ordinal).ToArray());
+ }
+
[Fact]
public async Task HandleConfigurationRequest_JwtResponseModesAreNotReturnedWhenDisabled()
{
@@ -454,6 +478,41 @@ public abstract partial class OpenIddictServerIntegrationTests
.EnumerateArray().Select(static element => element.GetString()!).ToArray());
}
+ [Theory]
+ [InlineData(10_000)]
+ [InlineData(200_000)]
+ [InlineData(248_000)]
+ public async Task ApplyAuthorizationResponse_TokenContainsParametersAddedByLateCustomHandlers(int order)
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureJwtResponseServer(options);
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ context.Response["custom_parameter"] = "custom_value";
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(order);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/authorize", CreateJwtResponseRequest());
+
+ // Assert
+ Assert.Null(response["custom_parameter"]);
+ var token = await ValidateAuthorizationResponseTokenAsync(client, (string?) response[Parameters.Response]);
+ Assert.Equal("custom_value", token.GetPayloadValue("custom_parameter"));
+ }
+
[Fact]
public async Task ApplyAuthorizationResponse_NonJwtResponseModesAreNotAffected()
{
@@ -820,6 +879,34 @@ public abstract partial class OpenIddictServerIntegrationTests
var value = (string?) response[Parameters.Response];
Assert.False(string.IsNullOrEmpty(value));
Assert.Equal("rsa", new JsonWebToken(value).Kid);
+ Assert.Equal(SecurityAlgorithms.RsaSha256, new JsonWebToken(value).Alg);
+ }
+
+ [Fact]
+ public async Task ApplyAuthorizationResponse_XmlDSigCredentialsAreNormalizedByDefault()
+ {
+ // Arrange
+ using var algorithm = RSA.Create(keySizeInBits: 2048);
+
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureJwtResponseServer(options);
+
+ options.Configure(options => options.SigningCredentials.Clear());
+ options.AddSigningCredentials(new SigningCredentials(
+ new RsaSecurityKey(algorithm) { KeyId = "rsa" }, SecurityAlgorithms.RsaSha256Signature));
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/authorize", CreateJwtResponseRequest());
+
+ // Assert
+ var value = (string?) response[Parameters.Response];
+ Assert.False(string.IsNullOrEmpty(value));
+ Assert.Equal("rsa", new JsonWebToken(value).Kid);
+ Assert.Equal(SecurityAlgorithms.RsaSha256, new JsonWebToken(value).Alg);
}
[Fact]