Browse Source

Normalize JARM alg headers, negotiate JWT-only server response modes and add client JARM encryption requirement

pull/2549/head
pieroviano 2 months ago
parent
commit
33ce5dcdfd
  1. 7
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 4
      src/OpenIddict.Client.AspNetCore/OpenIddictClientAspNetCoreHandlers.cs
  3. 4
      src/OpenIddict.Client.Owin/OpenIddictClientOwinHandlers.cs
  4. 4
      src/OpenIddict.Client.SystemIntegration/OpenIddictClientSystemIntegrationHandlers.cs
  5. 92
      src/OpenIddict.Client/OpenIddictClientHandlers.Jarm.cs
  6. 4
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  7. 18
      src/OpenIddict.Client/OpenIddictClientRegistration.cs
  8. 31
      src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs
  9. 9
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  10. 12
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  11. 5
      src/OpenIddict.Server/OpenIddictServerOptions.cs
  12. 125
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Jarm.cs
  13. 87
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.AuthorizationResponse.cs

7
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2045,6 +2045,10 @@ JWT authorization responses can only be encrypted using 'RSA-OAEP' with 'A128CBC
<data name="ID0647" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0648" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0532" xml:space="preserve">
<value>The backchannel authentication request was not correctly extracted.
@ -3141,6 +3145,9 @@ Error URI: {2}</value>
<data name="ID2325" xml:space="preserve">
<value>The JWT authorization response was signed using an algorithm that is not allowed.</value>
</data>
<data name="ID2326" xml:space="preserve">
<value>The JWT authorization response was not encrypted, which is required by the client registration.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>

4
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).

4
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).

4
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

92
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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="context">The context associated with the event to process.</param>
/// <returns>The response modes that can be negotiated.</returns>
public static ICollection<string> 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<string>(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<string> types &&
(types.Contains(ResponseTypes.IdToken) || types.Contains(ResponseTypes.Token))
? ResponseModes.FragmentJwt : ResponseModes.QueryJwt;
}
/// <summary>
@ -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;

4
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)),

18
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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public string? AuthorizationResponseSigningAlgorithm { get; set; }
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// Note: encrypted responses are decrypted using the encryption credentials registered in the client options.
/// </remarks>
public bool RequireEncryptedAuthorizationResponses { get; set; }
/// <summary>
/// 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.

31
src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.Jarm.cs

@ -80,9 +80,11 @@ public static partial class OpenIddictServerHandlers
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyAuthorizationResponseContext>()
.AddFilter<RequireJwtSecuredAuthorizationResponsesEnabled>()
.UseSingletonHandler<GenerateAuthorizationResponseToken>()
// 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
};
/// <summary>
/// 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.
/// </summary>
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
};
}
/// <summary>
/// Determines whether the JWT response mode specified in the request is enabled.
/// </summary>

9
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;

12
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]
};

5
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
/// <see cref="Settings.AuthorizationResponse.EncryptionAlgorithm"/> setting.
/// </summary>
/// <remarks>
/// 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).
/// </remarks>
public bool EnableJwtSecuredAuthorizationResponses { get; set; }
/// <summary>

125
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<InvalidOperationException>(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<InvalidOperationException>(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()
{

87
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<string?>?) 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<ApplyAuthorizationResponseContext>(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<string>("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]

Loading…
Cancel
Save