Browse Source

Add DPoP (RFC 9449) support to the server stack

- Validate DPoP proofs at the token, PAR and userinfo endpoints (typ, alg, public jwk, htm/htu, iat, ath)
- Replay protection via redeemed token entries when token storage is enabled
- Optional server nonces (use_dpop_nonce + DPoP-Nonce header)
- Bind access tokens and public-client refresh tokens with cnf.jkt; token_type=DPoP
- dpop_jkt at authorization/PAR, enforced at code redemption
- Global RequireDPoP option, per-client ft:dpop requirement, discovery metadata
- DPoP scheme and WWW-Authenticate algs in ASP.NET Core and OWIN hosts
pull/2549/head
pieroviano 2 months ago
parent
commit
0dae3a9dbf
  1. 2
      Directory.Packages.props
  2. 439
      shared/OpenIddict.Extensions/IdentityModel/OpenIddictDPoPHelpers.cs
  3. 4
      shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj
  4. 17
      src/OpenIddict.Abstractions/OpenIddictConstants.cs
  5. 66
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  6. 5
      src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
  7. 9
      src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs
  8. 4
      src/OpenIddict.Client/OpenIddict.Client.csproj
  9. 6
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs
  10. 2
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs
  11. 2
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Exchange.cs
  12. 2
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Userinfo.cs
  13. 129
      src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
  14. 2
      src/OpenIddict.Server.Owin/OpenIddictServerOwinConstants.cs
  15. 2
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs
  16. 2
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs
  17. 2
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs
  18. 129
      src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
  19. 4
      src/OpenIddict.Server/OpenIddict.Server.csproj
  20. 46
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  21. 22
      src/OpenIddict.Server/OpenIddictServerConfiguration.cs
  22. 1
      src/OpenIddict.Server/OpenIddictServerExtensions.cs
  23. 14
      src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
  24. 7
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  25. 108
      src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
  26. 6
      src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs
  27. 59
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  28. 470
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  29. 50
      src/OpenIddict.Server/OpenIddictServerOptions.cs
  30. 30
      src/OpenIddict.Server/OpenIddictServerTransaction.cs
  31. 5
      src/OpenIddict.Validation/OpenIddict.Validation.csproj
  32. 23
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs
  33. 1125
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.DPoP.cs
  34. 24
      test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs
  35. 49
      test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs

2
Directory.Packages.props

@ -31,6 +31,7 @@
<PackageVersion Include="Microsoft.Bcl.Cryptography" Version="10.0.11" />
<PackageVersion Include="Microsoft.Bcl.HashCode" Version="6.0.0" />
<PackageVersion Include="Microsoft.Bcl.Memory" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.11" />
@ -114,6 +115,7 @@
<PackageVersion Include="EntityFramework" Version="6.5.2" />
<PackageVersion Include="Microsoft.AspNetCore.DataProtection" Version="10.0.11" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.11" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.11" />

439
shared/OpenIddict.Extensions/IdentityModel/OpenIddictDPoPHelpers.cs

@ -0,0 +1,439 @@
/*
* 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
* the license and the contributors participating to this project.
*/
using System.Buffers.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace OpenIddict.Extensions;
/// <summary>
/// Exposes the helpers used to create and validate OAuth 2.0 Demonstrating Proof of Possession (DPoP) proofs.
/// </summary>
/// <remarks>
/// See https://datatracker.ietf.org/doc/html/rfc9449 for more information.
/// </remarks>
internal static class OpenIddictDPoPHelpers
{
/// <summary>
/// Represents the errors that can be returned when validating a DPoP proof.
/// </summary>
internal enum ProofError
{
None = 0,
Malformed,
InvalidType,
InvalidAlgorithm,
InvalidKey,
InvalidSignature,
InvalidClaim
}
/// <summary>
/// Represents the result of a DPoP proof validation.
/// </summary>
/// <param name="Error">The error, if applicable.</param>
/// <param name="Claim">The name of the missing or invalid claim, if applicable.</param>
/// <param name="Token">The validated proof.</param>
/// <param name="Thumbprint">The RFC 7638 thumbprint of the public key contained in the proof.</param>
internal sealed record class ProofValidationResult(
ProofError Error, string? Claim, JsonWebToken? Token, string? Thumbprint);
/// <summary>
/// Gets the asymmetric signing algorithms that can be used to create DPoP proofs.
/// </summary>
internal static IReadOnlyList<string> SupportedAlgorithms { get; } =
[
SecurityAlgorithms.EcdsaSha256,
SecurityAlgorithms.EcdsaSha384,
SecurityAlgorithms.EcdsaSha512,
SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.RsaSha384,
SecurityAlgorithms.RsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.RsaSsaPssSha384,
SecurityAlgorithms.RsaSsaPssSha512
];
/// <summary>
/// Computes the "ath" value (i.e the base64url-encoded SHA-256 hash of the ASCII representation) of an access token.
/// </summary>
/// <param name="token">The access token.</param>
/// <returns>The base64url-encoded hash.</returns>
internal static string ComputeAccessTokenHash(string token)
{
ArgumentException.ThrowIfNullOrEmpty(token);
return Base64Url.EncodeToString(SHA256.HashData(Encoding.ASCII.GetBytes(token)));
}
/// <summary>
/// Determines whether the two specified strings are equal using a time-constant comparison.
/// </summary>
/// <param name="left">The first string.</param>
/// <param name="right">The second string.</param>
/// <returns><see langword="true"/> if the two strings are equal, <see langword="false"/> otherwise.</returns>
internal static bool FixedTimeEquals(string? left, string? right)
{
if (left is null || right is null)
{
return false;
}
return CryptographicOperations.FixedTimeEquals(
left : MemoryMarshal.AsBytes(left.AsSpan()),
right: MemoryMarshal.AsBytes(right.AsSpan()));
}
/// <summary>
/// Determines whether the specified "htu" value matches the specified request URI,
/// ignoring the query string and fragment components, as required by RFC 9449.
/// </summary>
/// <param name="value">The "htu" value extracted from the DPoP proof.</param>
/// <param name="uri">The request URI.</param>
/// <returns><see langword="true"/> if the URIs match, <see langword="false"/> otherwise.</returns>
internal static bool MatchesHttpUri(string? value, Uri uri)
{
ArgumentNullException.ThrowIfNull(uri);
if (string.IsNullOrEmpty(value) || !Uri.TryCreate(value, UriKind.Absolute, out Uri? candidate))
{
return false;
}
// Note: System.Uri automatically applies the syntax-based normalization rules defined in RFC 3986
// (e.g scheme and host case normalization, removal of dot segments and default port elision).
return string.Equals(candidate.Scheme, uri.Scheme, StringComparison.OrdinalIgnoreCase) &&
string.Equals(candidate.Host, uri.Host, StringComparison.OrdinalIgnoreCase) &&
candidate.Port == uri.Port &&
string.Equals(candidate.AbsolutePath, uri.AbsolutePath, StringComparison.Ordinal);
}
/// <summary>
/// Computes the RFC 7638 thumbprint of the public key attached to the specified signing credentials.
/// </summary>
/// <param name="credentials">The signing credentials.</param>
/// <returns>The base64url-encoded thumbprint.</returns>
internal static string ComputeJsonWebKeyThumbprint(SigningCredentials credentials)
{
ArgumentNullException.ThrowIfNull(credentials);
return Base64UrlEncoder.Encode(new JsonWebKey(CreatePublicJsonWebKey(credentials.Key).ToJsonString()).ComputeJwkThumbprint());
}
/// <summary>
/// Creates a DPoP proof using the specified signing credentials.
/// </summary>
/// <param name="credentials">The asymmetric signing credentials.</param>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="uri">The URI of the request.</param>
/// <param name="date">The issuance date.</param>
/// <param name="token">The access token, if applicable.</param>
/// <param name="nonce">The server-provided nonce, if applicable.</param>
/// <returns>The DPoP proof.</returns>
internal static string CreateProof(SigningCredentials credentials, string method,
Uri uri, DateTimeOffset date, string? token, string? nonce)
{
ArgumentNullException.ThrowIfNull(credentials);
ArgumentException.ThrowIfNullOrEmpty(method);
ArgumentNullException.ThrowIfNull(uri);
var claims = new Dictionary<string, object>(StringComparer.Ordinal)
{
[OpenIddictConstants.Claims.JwtId] = Guid.NewGuid().ToString(),
[OpenIddictConstants.Claims.HttpMethod] = method,
[OpenIddictConstants.Claims.HttpUri] = uri.GetLeftPart(UriPartial.Path),
[OpenIddictConstants.Claims.IssuedAt] = date.ToUnixTimeSeconds()
};
if (!string.IsNullOrEmpty(token))
{
claims[OpenIddictConstants.Claims.DPoPAccessTokenHash] = ComputeAccessTokenHash(token);
}
if (!string.IsNullOrEmpty(nonce))
{
claims[OpenIddictConstants.Claims.Nonce] = nonce;
}
var key = CreatePublicJsonWebKey(credentials.Key);
var handler = new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = false };
return handler.CreateToken(new SecurityTokenDescriptor
{
AdditionalHeaderClaims = new Dictionary<string, object>(StringComparer.Ordinal)
{
[JwtHeaderParameterNames.Jwk] = key.ToDictionary(
static node => node.Key, static node => (object) (string) node.Value!, StringComparer.Ordinal)
},
Claims = claims,
// Note: the key identifier is deliberately not included as the key is embedded in the proof.
SigningCredentials = new SigningCredentials(CreateKeyWithoutIdentifier(credentials.Key), credentials.Algorithm),
TokenType = OpenIddictConstants.JsonWebTokenTypes.DPoPProof
});
static SecurityKey CreateKeyWithoutIdentifier(SecurityKey key) => key switch
{
ECDsaSecurityKey { ECDsa: ECDsa algorithm } => new ECDsaSecurityKey(algorithm),
RsaSecurityKey { Rsa: RSA algorithm } => new RsaSecurityKey(algorithm),
RsaSecurityKey { Parameters: var parameters } => new RsaSecurityKey(parameters),
X509SecurityKey { Certificate: X509Certificate2 certificate } => new X509SecurityKey(certificate) { KeyId = null },
_ => key
};
}
/// <summary>
/// Validates the specified DPoP proof.
/// </summary>
/// <param name="proof">The DPoP proof.</param>
/// <param name="method">The HTTP method of the request.</param>
/// <param name="uri">The URI of the request.</param>
/// <param name="algorithms">The allowed signing algorithms.</param>
/// <param name="date">The current date.</param>
/// <param name="lifetime">The maximum difference allowed between the current date and the "iat" claim.</param>
/// <param name="token">The access token, if the "ath" claim must be validated.</param>
/// <returns>The validation result.</returns>
internal static async ValueTask<ProofValidationResult> ValidateProofAsync(string proof, string method, Uri uri,
IReadOnlyCollection<string> algorithms, DateTimeOffset date, TimeSpan lifetime, string? token)
{
ArgumentException.ThrowIfNullOrEmpty(proof);
ArgumentException.ThrowIfNullOrEmpty(method);
ArgumentNullException.ThrowIfNull(uri);
ArgumentNullException.ThrowIfNull(algorithms);
var handler = new JsonWebTokenHandler();
JsonWebToken jwt;
try
{
if (!handler.CanReadToken(proof))
{
return new(ProofError.Malformed, null, null, null);
}
jwt = new JsonWebToken(proof);
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
return new(ProofError.Malformed, null, null, null);
}
// DPoP proofs MUST be signed JSON Web Tokens (encrypted proofs are not allowed).
if (jwt.IsEncrypted)
{
return new(ProofError.Malformed, null, null, null);
}
// DPoP proofs MUST use the "dpop+jwt" type.
if (!string.Equals(jwt.Typ, OpenIddictConstants.JsonWebTokenTypes.DPoPProof, StringComparison.OrdinalIgnoreCase))
{
return new(ProofError.InvalidType, null, null, null);
}
// DPoP proofs MUST use an asymmetric algorithm (symmetric algorithms and "none" are never allowed).
if (string.IsNullOrEmpty(jwt.Alg) || !SupportedAlgorithms.Contains(jwt.Alg, StringComparer.Ordinal) ||
!algorithms.Contains(jwt.Alg, StringComparer.Ordinal))
{
return new(ProofError.InvalidAlgorithm, null, null, null);
}
// Resolve the public key from the "jwk" header.
JsonWebKey key;
string thumbprint;
try
{
if (JsonNode.Parse(Base64Url.DecodeFromChars(jwt.EncodedHeader)) is not JsonObject header ||
header[JwtHeaderParameterNames.Jwk] is not JsonObject node)
{
return new(ProofError.InvalidKey, null, null, null);
}
// The JSON Web Key MUST NOT contain a private key.
foreach (var name in (string[]) [JsonWebKeyParameterNames.D, JsonWebKeyParameterNames.DP,
JsonWebKeyParameterNames.DQ, JsonWebKeyParameterNames.K, JsonWebKeyParameterNames.Oth,
JsonWebKeyParameterNames.P, JsonWebKeyParameterNames.Q, JsonWebKeyParameterNames.QI])
{
if (node.ContainsKey(name))
{
return new(ProofError.InvalidKey, null, null, null);
}
}
key = new JsonWebKey(node.ToJsonString());
// Note: only elliptic curve and RSA keys are supported.
if (key.Kty is not (JsonWebAlgorithmsKeyTypes.EllipticCurve or JsonWebAlgorithmsKeyTypes.RSA))
{
return new(ProofError.InvalidKey, null, null, null);
}
thumbprint = Base64UrlEncoder.Encode(key.ComputeJwkThumbprint());
}
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
return new(ProofError.InvalidKey, null, null, null);
}
var result = await handler.ValidateTokenAsync(jwt, new TokenValidationParameters
{
IssuerSigningKey = key,
RequireExpirationTime = false,
RequireSignedTokens = true,
TryAllIssuerSigningKeys = true,
ValidAlgorithms = [jwt.Alg],
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = false,
ValidateLifetime = false,
ValidTypes =
[
OpenIddictConstants.JsonWebTokenTypes.DPoPProof,
OpenIddictConstants.JsonWebTokenTypes.Prefixes.Application + OpenIddictConstants.JsonWebTokenTypes.DPoPProof
]
});
if (!result.IsValid)
{
return new(ProofError.InvalidSignature, null, null, null);
}
// DPoP proofs MUST contain a unique identifier.
if (!jwt.TryGetPayloadValue(OpenIddictConstants.Claims.JwtId, out string? identifier) || string.IsNullOrEmpty(identifier))
{
return new(ProofError.InvalidClaim, OpenIddictConstants.Claims.JwtId, null, null);
}
// DPoP proofs MUST contain a "htm" claim matching the HTTP method of the request.
if (!jwt.TryGetPayloadValue(OpenIddictConstants.Claims.HttpMethod, out string? htm) ||
!string.Equals(htm, method, StringComparison.Ordinal))
{
return new(ProofError.InvalidClaim, OpenIddictConstants.Claims.HttpMethod, null, null);
}
// DPoP proofs MUST contain a "htu" claim matching the URI of the request (without query and fragment).
if (!jwt.TryGetPayloadValue(OpenIddictConstants.Claims.HttpUri, out string? htu) || !MatchesHttpUri(htu, uri))
{
return new(ProofError.InvalidClaim, OpenIddictConstants.Claims.HttpUri, null, null);
}
// DPoP proofs MUST contain an "iat" claim within the acceptable window.
if (!jwt.TryGetPayloadValue(OpenIddictConstants.Claims.IssuedAt, out object? _) ||
new DateTimeOffset(jwt.IssuedAt, TimeSpan.Zero) is var issued &&
(issued < date - lifetime || issued > date + lifetime))
{
return new(ProofError.InvalidClaim, OpenIddictConstants.Claims.IssuedAt, null, null);
}
// When an access token is presented, DPoP proofs MUST contain a matching "ath" claim.
if (!string.IsNullOrEmpty(token) &&
(!jwt.TryGetPayloadValue(OpenIddictConstants.Claims.DPoPAccessTokenHash, out string? hash) ||
!FixedTimeEquals(hash, ComputeAccessTokenHash(token))))
{
return new(ProofError.InvalidClaim, OpenIddictConstants.Claims.DPoPAccessTokenHash, null, null);
}
return new(ProofError.None, null, jwt, thumbprint);
}
/// <summary>
/// Resolves the unique identifier ("jti") of the specified DPoP proof.
/// </summary>
/// <param name="token">The DPoP proof.</param>
/// <returns>The unique identifier.</returns>
internal static string? GetJwtId(JsonWebToken token)
=> token.TryGetPayloadValue(OpenIddictConstants.Claims.JwtId, out string? value) ? value : null;
/// <summary>
/// Resolves the nonce attached to the specified DPoP proof, if applicable.
/// </summary>
/// <param name="token">The DPoP proof.</param>
/// <returns>The nonce, if applicable.</returns>
internal static string? GetNonce(JsonWebToken token)
=> token.TryGetPayloadValue(OpenIddictConstants.Claims.Nonce, out string? value) ? value : null;
/// <summary>
/// Creates a JSON Web Key containing only the public members of the specified asymmetric key.
/// </summary>
/// <param name="key">The asymmetric key.</param>
/// <returns>The JSON representation of the public key.</returns>
private static JsonObject CreatePublicJsonWebKey(SecurityKey key)
{
switch (key)
{
case ECDsaSecurityKey { ECDsa: ECDsa algorithm }:
return CreateEllipticCurveKey(algorithm.ExportParameters(includePrivateParameters: false));
case RsaSecurityKey { Rsa: RSA algorithm }:
return CreateRsaKey(algorithm.ExportParameters(includePrivateParameters: false));
case RsaSecurityKey { Parameters: RSAParameters { Modulus: not null, Exponent: not null } parameters }:
return CreateRsaKey(parameters);
case X509SecurityKey { Certificate: X509Certificate2 certificate } when certificate.GetECDsaPublicKey() is ECDsa algorithm:
using (algorithm)
{
return CreateEllipticCurveKey(algorithm.ExportParameters(includePrivateParameters: false));
}
case X509SecurityKey { Certificate: X509Certificate2 certificate } when certificate.GetRSAPublicKey() is RSA algorithm:
using (algorithm)
{
return CreateRsaKey(algorithm.ExportParameters(includePrivateParameters: false));
}
case JsonWebKey { Kty: JsonWebAlgorithmsKeyTypes.EllipticCurve } value:
return new JsonObject
{
[JsonWebKeyParameterNames.Crv] = value.Crv,
[JsonWebKeyParameterNames.Kty] = value.Kty,
[JsonWebKeyParameterNames.X] = value.X,
[JsonWebKeyParameterNames.Y] = value.Y
};
case JsonWebKey { Kty: JsonWebAlgorithmsKeyTypes.RSA } value:
return new JsonObject
{
[JsonWebKeyParameterNames.E] = value.E,
[JsonWebKeyParameterNames.Kty] = value.Kty,
[JsonWebKeyParameterNames.N] = value.N
};
default: throw new InvalidOperationException(SR.GetResourceString(SR.ID0548));
}
static JsonObject CreateEllipticCurveKey(ECParameters parameters) => new()
{
[JsonWebKeyParameterNames.Crv] = (parameters.Curve.Oid?.Value, parameters.Curve.Oid?.FriendlyName) switch
{
("1.2.840.10045.3.1.7", _) or (_, "nistP256" or "ECDSA_P256") => JsonWebKeyECTypes.P256,
("1.3.132.0.34", _) or (_, "nistP384" or "ECDSA_P384") => JsonWebKeyECTypes.P384,
("1.3.132.0.35", _) or (_, "nistP521" or "ECDSA_P521") => JsonWebKeyECTypes.P521,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0548))
},
[JsonWebKeyParameterNames.Kty] = JsonWebAlgorithmsKeyTypes.EllipticCurve,
[JsonWebKeyParameterNames.X] = Base64UrlEncoder.Encode(parameters.Q.X),
[JsonWebKeyParameterNames.Y] = Base64UrlEncoder.Encode(parameters.Q.Y)
};
static JsonObject CreateRsaKey(RSAParameters parameters) => new()
{
[JsonWebKeyParameterNames.E] = Base64UrlEncoder.Encode(parameters.Exponent),
[JsonWebKeyParameterNames.Kty] = JsonWebAlgorithmsKeyTypes.RSA,
[JsonWebKeyParameterNames.N] = Base64UrlEncoder.Encode(parameters.Modulus)
};
}
}

4
shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj

@ -10,6 +10,10 @@
<ProjectReference Include="..\..\src\OpenIddict.Abstractions\OpenIddict.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<PackageReference Include="System.Collections.Immutable" />
</ItemGroup>

17
src/OpenIddict.Abstractions/OpenIddictConstants.cs

@ -78,6 +78,7 @@ public static class OpenIddictConstants
public const string CodeHash = "c_hash";
public const string Confirmation = "cnf";
public const string Country = "country";
public const string DPoPAccessTokenHash = "ath";
public const string Email = "email";
public const string EmailVerified = "email_verified";
public const string ExpiresAt = "exp";
@ -85,10 +86,13 @@ public static class OpenIddictConstants
public const string Formatted = "formatted";
public const string Gender = "gender";
public const string GivenName = "given_name";
public const string HttpMethod = "htm";
public const string HttpUri = "htu";
public const string IssuedAt = "iat";
public const string Issuer = "iss";
public const string Locale = "locale";
public const string Locality = "locality";
public const string JsonWebKeyThumbprint = "jkt";
public const string JwtId = "jti";
public const string KeyId = "kid";
public const string MiddleName = "middle_name";
@ -137,6 +141,7 @@ public static class OpenIddictConstants
public const string CreationDate = "oi_crt_dt";
public const string DeviceCodeId = "oi_dvc_id";
public const string DeviceCodeLifetime = "oi_dvc_lft";
public const string DPoPJwkThumbprint = "oi_dpop_jkt";
public const string EndpointType = "oi_ept_typ";
public const string ExpirationDate = "oi_exp_dt";
public const string GrantType = "oi_grt_typ";
@ -240,6 +245,7 @@ public static class OpenIddictConstants
public const string InteractionRequired = "interaction_required";
public const string InvalidBindingMessage = "invalid_binding_message";
public const string InvalidClient = "invalid_client";
public const string InvalidDPoPProof = "invalid_dpop_proof";
public const string InvalidGrant = "invalid_grant";
public const string InvalidRequest = "invalid_request";
public const string InvalidRequestObject = "invalid_request_object";
@ -263,6 +269,7 @@ public static class OpenIddictConstants
public const string UnsupportedGrantType = "unsupported_grant_type";
public const string UnsupportedResponseType = "unsupported_response_type";
public const string UnsupportedTokenType = "unsupported_token_type";
public const string UseDPoPNonce = "use_dpop_nonce";
}
public static class GrantTypes
@ -283,6 +290,7 @@ public static class OpenIddictConstants
public const string AuthorizationGrant = "authorization-grant+jwt";
public const string AuthorizationRequest = "oauth-authz-req+jwt";
public const string ClientAuthentication = "client-authentication+jwt";
public const string DPoPProof = "dpop+jwt";
public const string GenericJsonWebToken = "JWT";
public static class Prefixes
@ -295,6 +303,7 @@ public static class OpenIddictConstants
public const string AuthenticationRequestId = "oi_arid+jwt";
public const string AuthorizationCode = "oi_auc+jwt";
public const string DeviceCode = "oi_dvc+jwt";
public const string DPoPNonce = "oi_dpop_nce+jwt";
public const string RefreshToken = "oi_reft+jwt";
public const string RequestToken = "oi_reqt+jwt";
public const string StateToken = "oi_stet+jwt";
@ -319,6 +328,7 @@ public static class OpenIddictConstants
public const string DeviceAuthorizationEndpoint = "device_authorization_endpoint";
public const string DeviceAuthorizationEndpointAuthMethodsSupported = "device_authorization_endpoint_auth_methods_supported";
public const string DisplayValuesSupported = "display_values_supported";
public const string DPoPSigningAlgValuesSupported = "dpop_signing_alg_values_supported";
public const string EndSessionEndpoint = "end_session_endpoint";
public const string GrantTypesSupported = "grant_types_supported";
public const string IdTokenEncryptionAlgValuesSupported = "id_token_encryption_alg_values_supported";
@ -380,6 +390,7 @@ public static class OpenIddictConstants
{
public const string AccessToken = "access_token";
public const string AcrValues = "acr_values";
public const string Algs = "algs";
public const string Active = "active";
public const string ActorToken = "actor_token";
public const string ActorTokenType = "actor_token_type";
@ -400,6 +411,7 @@ public static class OpenIddictConstants
public const string CodeVerifier = "code_verifier";
public const string DeviceCode = "device_code";
public const string Display = "display";
public const string DPoPJkt = "dpop_jkt";
public const string Error = "error";
public const string ErrorDescription = "error_description";
public const string ErrorUri = "error_uri";
@ -539,6 +551,7 @@ public static class OpenIddictConstants
{
public static class Features
{
public const string DPoP = "ft:dpop";
public const string ProofKeyForCodeExchange = "ft:pkce";
public const string PushedAuthorizationRequests = "ft:par";
public const string SignedRequestObjects = "ft:jar";
@ -569,6 +582,7 @@ public static class OpenIddictConstants
{
public const string Basic = "Basic";
public const string Bearer = "Bearer";
public const string DPoP = "DPoP";
}
public static class Scopes
@ -637,6 +651,7 @@ public static class OpenIddictConstants
{
public static class Private
{
public const string DPoP = "urn:openiddict:params:oauth:token-binding-method:dpop";
public const string SelfSignedTlsClientCertificate = "urn:openiddict:params:oauth:token-binding-method:self_signed_tls_client_certificate";
public const string TlsClientCertificate = "urn:openiddict:params:oauth:token-binding-method:tls_client_certificate";
}
@ -680,6 +695,7 @@ public static class OpenIddictConstants
public const string AuthorizationCode = "urn:openiddict:params:oauth:token-type:authorization_code";
public const string ClientAssertion = "urn:openiddict:params:oauth:token-type:client_assertion";
public const string DeviceCode = "urn:openiddict:params:oauth:token-type:device_code";
public const string DPoPProof = "urn:openiddict:params:oauth:token-type:dpop_proof";
public const string RequestObject = "urn:openiddict:params:oauth:token-type:request_object";
public const string RequestToken = "urn:openiddict:params:oauth:token-type:request_token";
public const string StateToken = "urn:openiddict:params:oauth:token-type:state_token";
@ -691,6 +707,7 @@ public static class OpenIddictConstants
public static class TokenTypes
{
public const string Bearer = "Bearer";
public const string DPoP = "DPoP";
public const string NotApplicable = "N_A";
}
}

66
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -1858,6 +1858,30 @@ To use ASP.NET Core Data Protection, reference the 'OpenIddict.Server.DataProtec
<data name="ID0543" xml:space="preserve">
<value>The key rotation interval, propagation time, retention time and key ring cache lifetime must be positive, and the propagation time must be shorter than the rotation interval.</value>
</data>
<data name="ID0544" xml:space="preserve">
<value>DPoP proofs cannot be required when DPoP support is not enabled.
To enable DPoP support, call 'services.AddOpenIddict().AddServer().EnableDPoPSupport()'.</value>
</data>
<data name="ID0545" xml:space="preserve">
<value>DPoP nonces cannot be required when DPoP support is not enabled.
To enable DPoP support, call 'services.AddOpenIddict().AddServer().EnableDPoPSupport()'.</value>
</data>
<data name="ID0546" xml:space="preserve">
<value>At least one asymmetric signing algorithm (e.g ES256 or PS256) must be allowed for DPoP proofs and only asymmetric algorithms can be used.</value>
</data>
<data name="ID0547" xml:space="preserve">
<value>The DPoP proof and nonce lifetimes must be positive.</value>
</data>
<data name="ID0548" xml:space="preserve">
<value>The DPoP signing key must be an elliptic curve (P-256, P-384 or P-521) or RSA key whose public parameters can be exported.</value>
</data>
<data name="ID0549" xml:space="preserve">
<value>The HTTP method of the current request couldn't be resolved, which is required to validate DPoP proofs.</value>
</data>
<data name="ID0550" xml:space="preserve">
<value>No DPoP signing credentials were attached to the client registration.
To enable DPoP, call 'services.AddOpenIddict().AddClient().EnableDPoPTokenBinding()'.</value>
</data>
<data name="ID0532" xml:space="preserve">
<value>The backchannel authentication request was not correctly extracted.
To extract backchannel authentication requests, create a class implementing 'IOpenIddictServerHandler&lt;ExtractBackchannelAuthenticationRequestContext&gt;' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.</value>
@ -2540,6 +2564,36 @@ To apply backchannel authentication responses, create a class implementing 'IOpe
<data name="ID2224" xml:space="preserve">
<value>The key activation, expiration and retirement dates must be specified and ordered chronologically.</value>
</data>
<data name="ID2225" xml:space="preserve">
<value>The specified DPoP proof is malformed or invalid.</value>
</data>
<data name="ID2226" xml:space="preserve">
<value>The '{0}' claim of the DPoP proof is missing or invalid.</value>
</data>
<data name="ID2227" xml:space="preserve">
<value>The specified DPoP proof has already been used.</value>
</data>
<data name="ID2228" xml:space="preserve">
<value>A valid DPoP proof is required to use this endpoint.</value>
</data>
<data name="ID2229" xml:space="preserve">
<value>A server-provided nonce must be included in the DPoP proof.</value>
</data>
<data name="ID2230" xml:space="preserve">
<value>A DPoP-based proof-of-possession is required to use this token.</value>
</data>
<data name="ID2231" xml:space="preserve">
<value>The specified DPoP-based proof-of-possession is not valid.</value>
</data>
<data name="ID2232" xml:space="preserve">
<value>The specified token is not bound to the key used to sign the DPoP proof.</value>
</data>
<data name="ID2233" xml:space="preserve">
<value>The key used to sign the DPoP proof doesn't match the '{0}' parameter.</value>
</data>
<data name="ID2234" xml:space="preserve">
<value>A single DPoP proof must be specified.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>
@ -3443,6 +3497,18 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6310" xml:space="preserve">
<value>The automatically managed key '{KeyId}' could not be unprotected and was ignored.</value>
</data>
<data name="ID6311" xml:space="preserve">
<value>The DPoP proof was rejected because it was invalid ({Reason}).</value>
</data>
<data name="ID6312" xml:space="preserve">
<value>The DPoP proof was rejected because it was already used.</value>
</data>
<data name="ID6313" xml:space="preserve">
<value>The DPoP proof was rejected because it didn't contain a valid server-provided nonce.</value>
</data>
<data name="ID6314" xml:space="preserve">
<value>The token was rejected because the DPoP proof was missing or didn't match the confirmation claim.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

5
src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs

@ -57,6 +57,11 @@ public sealed class OpenIddictConfiguration
/// </summary>
public HashSet<string> DeviceAuthorizationEndpointAuthMethodsSupported { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets the signing algorithms supported by the server for DPoP proofs.
/// </summary>
public HashSet<string> DPoPSigningAlgValuesSupported { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the URI of the end session endpoint.
/// </summary>

9
src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs

@ -318,6 +318,15 @@ public class OpenIddictRequest : OpenIddictMessage
set => SetParameter(OpenIddictConstants.Parameters.Display, value);
}
/// <summary>
/// Gets or sets the "dpop_jkt" parameter.
/// </summary>
public string? DPoPJkt
{
get => (string?) GetParameter(OpenIddictConstants.Parameters.DPoPJkt);
set => SetParameter(OpenIddictConstants.Parameters.DPoPJkt, value);
}
/// <summary>
/// Gets or sets the "grant_type" parameter.
/// </summary>

4
src/OpenIddict.Client/OpenIddict.Client.csproj

@ -17,6 +17,10 @@ To use the client feature on ASP.NET Core or OWIN/Katana, reference the OpenIddi
<ProjectReference Include="..\OpenIddict.Abstractions\OpenIddict.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\shared\OpenIddict.Extensions\IdentityModel\*.cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />

6
src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs

@ -11,6 +11,12 @@ namespace OpenIddict.Server.AspNetCore;
/// </summary>
public static class OpenIddictServerAspNetCoreConstants
{
public static class Headers
{
public const string DPoP = "DPoP";
public const string DPoPNonce = "DPoP-Nonce";
}
public static class Properties
{
public const string AccessTokenPrincipal = ".access_token_principal";

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

@ -49,6 +49,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractPostRequest<ExtractPushedAuthorizationRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractClientCertificate<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractDPoPProof<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractPushedAuthorizationRequestContext>.Descriptor,
/*
@ -57,6 +58,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
AttachHttpResponseCode<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
ProcessJsonResponse<ApplyPushedAuthorizationResponseContext>.Descriptor
];

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

@ -20,6 +20,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractPostRequest<ExtractTokenRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractTokenRequestContext>.Descriptor,
ExtractClientCertificate<ExtractTokenRequestContext>.Descriptor,
ExtractDPoPProof<ExtractTokenRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractTokenRequestContext>.Descriptor,
/*
@ -33,6 +34,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
AttachHttpResponseCode<ApplyTokenResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyTokenResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyTokenResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyTokenResponseContext>.Descriptor,
ProcessJsonResponse<ApplyTokenResponseContext>.Descriptor
];
}

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

@ -20,6 +20,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractGetOrPostRequest<ExtractUserInfoRequestContext>.Descriptor,
ExtractAccessToken<ExtractUserInfoRequestContext>.Descriptor,
ExtractClientCertificate<ExtractUserInfoRequestContext>.Descriptor,
ExtractDPoPProof<ExtractUserInfoRequestContext>.Descriptor,
/*
* UserInfo request handling:
@ -31,6 +32,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
*/
AttachHttpResponseCode<ApplyUserInfoResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyUserInfoResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyUserInfoResponseContext>.Descriptor,
ProcessChallengeErrorResponse<ApplyUserInfoResponseContext>.Descriptor,
ProcessJsonResponse<ApplyUserInfoResponseContext>.Descriptor
];

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

@ -102,6 +102,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
context.BaseUri = CreateUri(UriHelper.BuildAbsolute(request.Scheme, host, request.PathBase));
context.RequestUri = CreateUri(UriHelper.BuildAbsolute(request.Scheme, host, request.PathBase, request.Path, request.QueryString));
context.Transaction.RequestMethod = request.Method;
return ValueTask.CompletedTask;
@ -713,6 +714,60 @@ public static partial class OpenIddictServerAspNetCoreHandlers
}
}
/// <summary>
/// Contains the logic responsible for extracting the DPoP proof from the request headers.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ExtractDPoPProof<TContext> : IOpenIddictServerHandler<TContext>
where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpRequest>()
.AddFilter<RequireDPoPSupportEnabled>()
.UseSingletonHandler<ExtractDPoPProof<TContext>>()
.SetOrder(ExtractClientCertificate<TContext>.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// 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.
var request = context.Transaction.GetHttpRequest()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
var values = request.Headers[OpenIddictServerAspNetCoreConstants.Headers.DPoP];
if (values.Count is 0)
{
return ValueTask.CompletedTask;
}
// Requests MUST NOT contain more than one DPoP header (or a comma-separated list of proofs).
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-4.3 for more information.
if (values.Count is not 1 || string.IsNullOrEmpty(values[0]) || values[0]!.Contains(',', StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2234),
uri: SR.FormatID8000(SR.ID2234));
return ValueTask.CompletedTask;
}
context.Transaction.DPoPProof = values[0];
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting client credentials from the standard HTTP Authorization header.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
@ -840,13 +895,31 @@ public static partial class OpenIddictServerAspNetCoreHandlers
Debug.Assert(context.Transaction.Request is not null, SR.GetResourceString(SR.ID4008));
string? header = request.Headers[HeaderNames.Authorization];
if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
if (string.IsNullOrEmpty(header))
{
return ValueTask.CompletedTask;
}
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["Bearer ".Length..];
if (header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["Bearer ".Length..];
context.Transaction.AccessTokenScheme = Schemes.Bearer;
return ValueTask.CompletedTask;
}
// If DPoP support was enabled, also accept access tokens sent using the "DPoP" scheme.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7.1 for more information.
if (context.Options.EnableDPoPSupport && header.StartsWith("DPoP ", StringComparison.OrdinalIgnoreCase))
{
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["DPoP ".Length..];
context.Transaction.AccessTokenScheme = Schemes.DPoP;
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
@ -945,6 +1018,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// as part of the standard WWW-Authenticate header. For more information, see
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfoError.
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidToken or Errors.MissingToken) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// When client authentication is made using basic authentication, the authorization server
@ -1046,6 +1120,12 @@ public static partial class OpenIddictServerAspNetCoreHandlers
// logic as errors returned by API endpoints implementing bearer token authentication and
// MUST be returned as part of the standard WWW-Authenticate header. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#UserInfoError.
//
// Note: when DPoP is used, the "DPoP" scheme is returned instead of the "Bearer" scheme.
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7.1 for more information.
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) when string.Equals(
context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) => Schemes.Bearer,
// When client authentication is made using basic authentication, the authorization server
@ -1095,6 +1175,12 @@ public static partial class OpenIddictServerAspNetCoreHandlers
parameters[parameter.Key] = value;
}
// When using the DPoP scheme, return the list of supported algorithms.
if (scheme is Schemes.DPoP && context.Options.DPoPSigningAlgorithms.Count is > 0)
{
parameters[Parameters.Algs] = string.Join(' ', context.Options.DPoPSigningAlgorithms);
}
var builder = new StringBuilder(scheme);
foreach (var parameter in parameters)
@ -1120,6 +1206,43 @@ public static partial class OpenIddictServerAspNetCoreHandlers
}
}
/// <summary>
/// Contains the logic responsible for attaching the DPoP nonce to the "DPoP-Nonce" response header, if applicable.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class AttachDPoPNonceHeader<TContext> : IOpenIddictServerHandler<TContext> where TContext : BaseRequestContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireHttpRequest>()
.AddFilter<RequireDPoPSupportEnabled>()
.UseSingletonHandler<AttachDPoPNonceHeader<TContext>>()
.SetOrder(AttachWwwAuthenticateHeader<TContext>.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// 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.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (!string.IsNullOrEmpty(context.Transaction.DPoPNonce))
{
response.Headers[OpenIddictServerAspNetCoreConstants.Headers.DPoPNonce] = context.Transaction.DPoPNonce;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for processing challenge responses that contain a WWW-Authenticate header.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.

2
src/OpenIddict.Server.Owin/OpenIddictServerOwinConstants.cs

@ -16,6 +16,8 @@ public static class OpenIddictServerOwinConstants
public const string Authorization = "Authorization";
public const string CacheControl = "Cache-Control";
public const string ContentType = "Content-Type";
public const string DPoP = "DPoP";
public const string DPoPNonce = "DPoP-Nonce";
public const string Expires = "Expires";
public const string Host = "Host";
public const string Pragma = "Pragma";

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

@ -49,6 +49,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractPostRequest<ExtractPushedAuthorizationRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractClientCertificate<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractDPoPProof<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractPushedAuthorizationRequestContext>.Descriptor,
/*
@ -59,6 +60,7 @@ public static partial class OpenIddictServerOwinHandlers
SuppressFormsAuthenticationRedirect<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
ProcessJsonResponse<ApplyPushedAuthorizationResponseContext>.Descriptor,
];

2
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs

@ -20,6 +20,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractPostRequest<ExtractTokenRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractTokenRequestContext>.Descriptor,
ExtractClientCertificate<ExtractTokenRequestContext>.Descriptor,
ExtractDPoPProof<ExtractTokenRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractTokenRequestContext>.Descriptor,
/*
@ -35,6 +36,7 @@ public static partial class OpenIddictServerOwinHandlers
SuppressFormsAuthenticationRedirect<ApplyTokenResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyTokenResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyTokenResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyTokenResponseContext>.Descriptor,
ProcessJsonResponse<ApplyTokenResponseContext>.Descriptor
];
}

2
src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs

@ -20,6 +20,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractGetOrPostRequest<ExtractUserInfoRequestContext>.Descriptor,
ExtractAccessToken<ExtractUserInfoRequestContext>.Descriptor,
ExtractClientCertificate<ExtractUserInfoRequestContext>.Descriptor,
ExtractDPoPProof<ExtractUserInfoRequestContext>.Descriptor,
/*
* UserInfo request handling:
@ -33,6 +34,7 @@ public static partial class OpenIddictServerOwinHandlers
AttachOwinResponseChallenge<ApplyUserInfoResponseContext>.Descriptor,
SuppressFormsAuthenticationRedirect<ApplyUserInfoResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyUserInfoResponseContext>.Descriptor,
AttachDPoPNonceHeader<ApplyUserInfoResponseContext>.Descriptor,
ProcessChallengeErrorResponse<ApplyUserInfoResponseContext>.Descriptor,
ProcessJsonResponse<ApplyUserInfoResponseContext>.Descriptor
];

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

@ -100,6 +100,7 @@ public static partial class OpenIddictServerOwinHandlers
context.BaseUri = CreateUri(request.Scheme + Uri.SchemeDelimiter + host + request.PathBase);
context.RequestUri = CreateUri(request.Scheme + Uri.SchemeDelimiter + host + request.PathBase + request.Path + request.QueryString);
context.Transaction.RequestMethod = request.Method;
return ValueTask.CompletedTask;
@ -790,6 +791,60 @@ public static partial class OpenIddictServerOwinHandlers
}
}
/// <summary>
/// Contains the logic responsible for extracting the DPoP proof from the request headers.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
/// </summary>
public sealed class ExtractDPoPProof<TContext> : IOpenIddictServerHandler<TContext>
where TContext : BaseValidatingContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireOwinRequest>()
.AddFilter<RequireDPoPSupportEnabled>()
.UseSingletonHandler<ExtractDPoPProof<TContext>>()
.SetOrder(ExtractClientCertificate<TContext>.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// 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.
var request = context.Transaction.GetOwinRequest()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var values = request.Headers.GetValues(Headers.DPoP) ?? [];
if (values.Count is 0)
{
return ValueTask.CompletedTask;
}
// Requests MUST NOT contain more than one DPoP header (or a comma-separated list of proofs).
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-4.3 for more information.
if (values.Count is not 1 || string.IsNullOrEmpty(values[0]) || values[0]!.Contains(',', StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2234),
uri: SR.FormatID8000(SR.ID2234));
return ValueTask.CompletedTask;
}
context.Transaction.DPoPProof = values[0];
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for extracting client credentials from the standard HTTP Authorization header.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
@ -917,13 +972,31 @@ public static partial class OpenIddictServerOwinHandlers
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
var header = request.Headers[Headers.Authorization];
if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
if (string.IsNullOrEmpty(header))
{
return ValueTask.CompletedTask;
}
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["Bearer ".Length..];
if (header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["Bearer ".Length..];
context.Transaction.AccessTokenScheme = Schemes.Bearer;
return ValueTask.CompletedTask;
}
// If DPoP support was enabled, also accept access tokens sent using the "DPoP" scheme.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7.1 for more information.
if (context.Options.EnableDPoPSupport && header.StartsWith("DPoP ", StringComparison.OrdinalIgnoreCase))
{
// Attach the access token to the request message.
context.Transaction.Request.AccessToken = header["DPoP ".Length..];
context.Transaction.AccessTokenScheme = Schemes.DPoP;
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
@ -1022,6 +1095,7 @@ public static partial class OpenIddictServerOwinHandlers
// as part of the standard WWW-Authenticate header. For more information, see
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfoError.
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidToken or Errors.MissingToken) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => 401,
(OpenIddictServerEndpointType.UserInfo, Errors.InsufficientAccess or Errors.InsufficientScope) => 403,
// When client authentication is made using basic authentication, the authorization server
@ -1237,6 +1311,12 @@ public static partial class OpenIddictServerOwinHandlers
// logic as errors returned by API endpoints implementing bearer token authentication and
// MUST be returned as part of the standard WWW-Authenticate header. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#UserInfoError.
//
// Note: when DPoP is used, the "DPoP" scheme is returned instead of the "Bearer" scheme.
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7.1 for more information.
(OpenIddictServerEndpointType.UserInfo, Errors.InvalidDPoPProof or Errors.UseDPoPNonce) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) when string.Equals(
context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase) => Schemes.DPoP,
(OpenIddictServerEndpointType.UserInfo, _) => Schemes.Bearer,
// When client authentication is made using basic authentication, the authorization server
@ -1286,6 +1366,12 @@ public static partial class OpenIddictServerOwinHandlers
parameters[parameter.Key] = value;
}
// When using the DPoP scheme, return the list of supported algorithms.
if (scheme is Schemes.DPoP && context.Options.DPoPSigningAlgorithms.Count is > 0)
{
parameters[Parameters.Algs] = string.Join(" ", context.Options.DPoPSigningAlgorithms);
}
var builder = new StringBuilder(scheme);
foreach (var parameter in parameters)
@ -1311,6 +1397,43 @@ public static partial class OpenIddictServerOwinHandlers
}
}
/// <summary>
/// Contains the logic responsible for attaching the DPoP nonce to the "DPoP-Nonce" response header, if applicable.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.
/// </summary>
public sealed class AttachDPoPNonceHeader<TContext> : IOpenIddictServerHandler<TContext> where TContext : BaseRequestContext
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.AddFilter<RequireOwinRequest>()
.AddFilter<RequireDPoPSupportEnabled>()
.UseSingletonHandler<AttachDPoPNonceHeader<TContext>>()
.SetOrder(AttachWwwAuthenticateHeader<TContext>.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(TContext context)
{
ArgumentNullException.ThrowIfNull(context);
// 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.
var response = context.Transaction.GetOwinRequest()?.Context.Response
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0120));
if (!string.IsNullOrEmpty(context.Transaction.DPoPNonce))
{
response.Headers[Headers.DPoPNonce] = context.Transaction.DPoPNonce;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for processing challenge responses that contain a WWW-Authenticate header.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by OWIN.

4
src/OpenIddict.Server/OpenIddict.Server.csproj

@ -16,6 +16,10 @@ To use the server feature on ASP.NET Core or OWIN/Katana, reference the OpenIddi
<ProjectReference Include="..\OpenIddict.Abstractions\OpenIddict.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\shared\OpenIddict.Extensions\IdentityModel\*.cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />

46
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -1836,6 +1836,52 @@ public sealed class OpenIddictServerBuilder
public OpenIddictServerBuilder EnableRequestObjectSupport()
=> Configure(options => options.EnableRequestObjectSupport = true);
/// <summary>
/// Enables OAuth 2.0 Demonstrating Proof of Possession (DPoP, RFC 9449) support, which allows client applications
/// to send DPoP proofs to the token, pushed authorization and userinfo endpoints. When a valid proof is received
/// by the token endpoint, access tokens (and refresh tokens issued to public clients) are bound to the proof key.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder EnableDPoPSupport()
=> Configure(options => options.EnableDPoPSupport = true);
/// <summary>
/// Configures OpenIddict to require a valid DPoP proof for all token requests.
/// </summary>
/// <remarks>
/// Note: DPoP support must be enabled using <see cref="EnableDPoPSupport"/>.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder RequireDPoP()
=> Configure(options => options.RequireDPoP = true);
/// <summary>
/// Configures OpenIddict to require a server-provided nonce in DPoP proofs. When a proof doesn't
/// contain a valid nonce, a "use_dpop_nonce" error is returned with a new "DPoP-Nonce" header.
/// </summary>
/// <remarks>
/// Note: DPoP support must be enabled using <see cref="EnableDPoPSupport"/>.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder RequireDPoPNonces()
=> Configure(options => options.RequireDPoPNonces = true);
/// <summary>
/// Sets the maximum difference allowed between the issuance date of a DPoP proof and the current date.
/// </summary>
/// <param name="lifetime">The DPoP proof lifetime.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetDPoPProofLifetime(TimeSpan lifetime)
=> Configure(options => options.DPoPProofLifetime = lifetime);
/// <summary>
/// Sets the lifetime of the DPoP nonces issued by the server.
/// </summary>
/// <param name="lifetime">The DPoP nonce lifetime.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder SetDPoPNonceLifetime(TimeSpan lifetime)
=> Configure(options => options.DPoPNonceLifetime = lifetime);
/// <summary>
/// Sets the access token lifetime, after which client applications must retrieve
/// a new access token by making a grant_type=refresh_token token request

22
src/OpenIddict.Server/OpenIddictServerConfiguration.cs

@ -335,6 +335,28 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
builder.AddError(SR.GetResourceString(SR.ID0524));
}
// Ensure the DPoP configuration is consistent.
if (options.RequireDPoP && !options.EnableDPoPSupport)
{
builder.AddError(SR.GetResourceString(SR.ID0544));
}
if (options.RequireDPoPNonces && !options.EnableDPoPSupport)
{
builder.AddError(SR.GetResourceString(SR.ID0545));
}
if (options.EnableDPoPSupport && (options.DPoPSigningAlgorithms.Count is 0 || options.DPoPSigningAlgorithms.Any(
static algorithm => !OpenIddictDPoPHelpers.SupportedAlgorithms.Contains(algorithm, StringComparer.Ordinal))))
{
builder.AddError(SR.GetResourceString(SR.ID0546));
}
if (options.DPoPProofLifetime <= TimeSpan.Zero || options.DPoPNonceLifetime <= TimeSpan.Zero)
{
builder.AddError(SR.GetResourceString(SR.ID0547));
}
// Ensure the client authentication methods/client assertion types configuration is consistent.
if (options.ClientAuthenticationMethods.Contains(ClientAuthenticationMethods.PrivateKeyJwt) &&
!options.ClientAssertionTypes.Contains(ClientAssertionTypes.JwtBearer))

1
src/OpenIddict.Server/OpenIddictServerExtensions.cs

@ -59,6 +59,7 @@ public static class OpenIddictServerExtensions
builder.Services.TryAddSingleton<RequireAuthenticationRequestIdValidated>();
builder.Services.TryAddSingleton<RequireBackchannelAuthenticationRequest>();
builder.Services.TryAddSingleton<RequireDeviceAuthorizationRequest>();
builder.Services.TryAddSingleton<RequireDPoPSupportEnabled>();
builder.Services.TryAddSingleton<RequireDeviceCodeGenerated>();
builder.Services.TryAddSingleton<RequireDeviceCodeValidated>();
builder.Services.TryAddSingleton<RequireEndpointPermissionsEnabled>();

14
src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs

@ -851,6 +851,20 @@ public static class OpenIddictServerHandlerFilters
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if DPoP support was not enabled.
/// </summary>
public sealed class RequireDPoPSupportEnabled : IOpenIddictServerHandlerFilter<BaseContext>
{
/// <inheritdoc/>
public ValueTask<bool> IsActiveAsync(BaseContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new(context.Options.EnableDPoPSupport);
}
}
/// <summary>
/// Represents a filter that excludes the associated handlers if token storage was not enabled.
/// </summary>

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

@ -889,6 +889,13 @@ public static partial class OpenIddictServerHandlers
context.Metadata[Metadata.RequireSignedRequestObject] = context.Options.RequireSignedRequestObjects;
}
// If DPoP support was enabled, return the signing algorithms allowed for DPoP proofs.
if (context.Options.EnableDPoPSupport)
{
context.Metadata[Metadata.DPoPSigningAlgValuesSupported] = new JsonArray(
[.. context.Options.DPoPSigningAlgorithms.Select(static algorithm => (JsonNode) algorithm)]);
}
// As of 3.2.0, OpenIddict automatically returns an "iss" parameter containing its identity as
// part of authorization responses to help clients mitigate mix-up attacks. For more information,
// see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-iss-auth-resp-05.

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

@ -58,9 +58,11 @@ public static partial class OpenIddictServerHandlers
ValidateAudiencePermissions.Descriptor,
ValidateResourcePermissions.Descriptor,
ValidateProofKeyForCodeExchangeRequirement.Descriptor,
ValidateDPoPRequirement.Descriptor,
ValidateAuthorizedParty.Descriptor,
ValidateRedirectUri.Descriptor,
ValidateCodeVerifier.Descriptor,
ValidateDPoPJwkThumbprint.Descriptor,
ValidateGrantedScopes.Descriptor,
/*
@ -1564,6 +1566,58 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for rejecting token requests made by
/// applications for which DPoP was enforced and that don't include a DPoP proof.
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public sealed class ValidateDPoPRequirement : IOpenIddictServerHandler<ValidateTokenRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenRequestContext>()
.AddFilter<RequireClientIdParameter>()
.AddFilter<RequireDegradedModeDisabled>()
.UseSingletonHandler<ValidateDPoPRequirement>()
.SetOrder(ValidateProofKeyForCodeExchangeRequirement.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ValidateTokenRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// If a valid DPoP proof was received, the request is always considered valid.
if (context.Transaction.DPoPProofPrincipal is not null)
{
return;
}
Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId));
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0032));
if (await manager.HasRequirementAsync(application, Requirements.Features.DPoP, context.CancellationToken))
{
context.Logger.LogInformation(6311, SR.GetResourceString(SR.ID6311), SR.GetResourceString(SR.ID2228));
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2228),
uri: SR.FormatID8000(SR.ID2228));
return;
}
}
}
/// <summary>
/// Contains the logic responsible for rejecting token requests that specify a token
/// that cannot be used by the client application sending the token request.
@ -2018,6 +2072,60 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for rejecting authorization code token requests whose
/// DPoP proof key doesn't match the "dpop_jkt" value attached to the authorization code.
/// </summary>
public sealed class ValidateDPoPJwkThumbprint : IOpenIddictServerHandler<ValidateTokenRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenRequestContext>()
.UseSingletonHandler<ValidateDPoPJwkThumbprint>()
.SetOrder(ValidateCodeVerifier.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Request.IsAuthorizationCodeGrantType())
{
return ValueTask.CompletedTask;
}
Debug.Assert(context.AuthorizationCodePrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var thumbprint = context.AuthorizationCodePrincipal.GetClaim(Claims.Private.DPoPJwkThumbprint);
if (string.IsNullOrEmpty(thumbprint))
{
return ValueTask.CompletedTask;
}
// If the authorization code was bound to a DPoP key, the token request MUST include
// a DPoP proof signed using the same key. For more information, see
// https://datatracker.ietf.org/doc/html/rfc9449#section-10.
if (!OpenIddictDPoPHelpers.FixedTimeEquals(thumbprint,
context.Transaction.DPoPProofPrincipal?.GetClaim(Claims.Private.DPoPJwkThumbprint)))
{
context.Logger.LogInformation(6314, SR.GetResourceString(SR.ID6314));
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.FormatID2233(Parameters.DPoPJkt),
uri: SR.FormatID8000(SR.ID2233));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting refresh token requests that specify scopes
/// that were not initially granted by the resource owner during the authorization request.

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

@ -758,6 +758,12 @@ public static partial class OpenIddictServerHandlers
// and https://tools.ietf.org/html/rfc6749#section-5.1 for more information.
TokenTypeIdentifiers.AccessToken when context.Confirmation is null => TokenTypes.Bearer,
// DPoP-bound access tokens use the specific "DPoP" token type.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-6.2 for more information.
TokenTypeIdentifiers.AccessToken when context.Confirmation?.ContainsKey(Claims.JsonWebKeyThumbprint) is true
=> TokenTypes.DPoP,
_ => null
};

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

@ -1156,6 +1156,22 @@ public static partial class OpenIddictServerHandlers
var confirmation = context.Principal.GetClaim(Claims.Confirmation);
if (string.IsNullOrEmpty(confirmation))
{
// Access tokens sent using the "DPoP" authentication scheme MUST be bound to a DPoP key.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7.1 for more information.
if (context.Principal.HasTokenType(TokenTypeIdentifiers.AccessToken) &&
string.Equals(context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase))
{
context.Logger.LogInformation(6314, SR.GetResourceString(SR.ID6314));
context.Reject(
error: Errors.InvalidToken,
description: SR.GetResourceString(SR.ID2232),
uri: SR.FormatID8000(SR.ID2232));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
@ -1164,6 +1180,47 @@ public static partial class OpenIddictServerHandlers
throw new InvalidOperationException(SR.GetResourceString(SR.ID2199));
}
if (!node.ContainsKey(JsonWebKeyParameterNames.X5tS256) && !node.ContainsKey(Claims.JsonWebKeyThumbprint))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID2196));
}
if (node.ContainsKey(Claims.JsonWebKeyThumbprint))
{
var thumbprint = (string?) node[Claims.JsonWebKeyThumbprint];
if (string.IsNullOrEmpty(thumbprint))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID2199));
}
// If no valid DPoP proof was provided (e.g because the access token was sent using the
// "Bearer" scheme), return an error as the proof-of-possession cannot be validated.
if (context.Transaction.DPoPProofPrincipal?.GetClaim(Claims.Private.DPoPJwkThumbprint) is not { Length: > 0 } value)
{
context.Logger.LogInformation(6314, SR.GetResourceString(SR.ID6314));
context.Reject(
error: Errors.InvalidToken,
description: SR.GetResourceString(SR.ID2230),
uri: SR.FormatID8000(SR.ID2230));
return ValueTask.CompletedTask;
}
// If the thumbprint of the DPoP proof key doesn't match the confirmation claim, return an error.
if (!OpenIddictDPoPHelpers.FixedTimeEquals(value, thumbprint))
{
context.Logger.LogInformation(6314, SR.GetResourceString(SR.ID6314));
context.Reject(
error: Errors.InvalidToken,
description: SR.GetResourceString(SR.ID2231),
uri: SR.FormatID8000(SR.ID2231));
return ValueTask.CompletedTask;
}
}
if (node.ContainsKey(JsonWebKeyParameterNames.X5tS256))
{
var thumbprint = (string?) node[JsonWebKeyParameterNames.X5tS256];
@ -1206,7 +1263,7 @@ public static partial class OpenIddictServerHandlers
return ValueTask.CompletedTask;
}
throw new InvalidOperationException(SR.GetResourceString(SR.ID2196));
return ValueTask.CompletedTask;
}
}

470
src/OpenIddict.Server/OpenIddictServerHandlers.cs

@ -51,6 +51,7 @@ public static partial class OpenIddictServerHandlers
ValidateClientType.Descriptor,
ValidateClientSecret.Descriptor,
ValidateClientCertificate.Descriptor,
ValidateDPoPProof.Descriptor,
ValidateRequestToken.Descriptor,
ValidateRequestTokenType.Descriptor,
ValidateAccessToken.Descriptor,
@ -1454,6 +1455,195 @@ public static partial class OpenIddictServerHandlers
}
}
/// <summary>
/// Contains the logic responsible for validating the DPoP proof sent to the token,
/// pushed authorization and userinfo endpoints, if applicable.
/// </summary>
public sealed class ValidateDPoPProof : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireDPoPSupportEnabled>()
.UseSingletonHandler<ValidateDPoPProof>()
.SetOrder(ValidateClientCertificate.Descriptor.Order + 500)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (context.EndpointType is not (OpenIddictServerEndpointType.Token or
OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.UserInfo))
{
return;
}
// Note: DPoP proofs sent to the userinfo endpoint are only validated when the
// access token is sent using the "DPoP" scheme. Access tokens sent using the
// "Bearer" scheme are treated as bearer tokens (and DPoP-bound tokens are rejected).
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-7 for more information.
if (context.EndpointType is OpenIddictServerEndpointType.UserInfo &&
!string.Equals(context.Transaction.AccessTokenScheme, Schemes.DPoP, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (string.IsNullOrEmpty(context.Transaction.DPoPProof))
{
if (context.EndpointType is OpenIddictServerEndpointType.UserInfo ||
(context.EndpointType is OpenIddictServerEndpointType.Token && context.Options.RequireDPoP))
{
context.Logger.LogInformation(6311, SR.GetResourceString(SR.ID6311), SR.GetResourceString(SR.ID2228));
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2228),
uri: SR.FormatID8000(SR.ID2228));
return;
}
return;
}
if (string.IsNullOrEmpty(context.Transaction.RequestMethod) || context.RequestUri is not { IsAbsoluteUri: true } uri)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0549));
}
var date = context.Options.TimeProvider.GetUtcNow();
var result = await OpenIddictDPoPHelpers.ValidateProofAsync(
proof : context.Transaction.DPoPProof,
method : context.Transaction.RequestMethod,
uri : uri,
algorithms: context.Options.DPoPSigningAlgorithms,
date : date,
lifetime : context.Options.DPoPProofLifetime,
token : context.EndpointType is OpenIddictServerEndpointType.UserInfo ? context.AccessToken : null);
if (result is not { Error: OpenIddictDPoPHelpers.ProofError.None, Token: JsonWebToken token, Thumbprint: string thumbprint })
{
context.Logger.LogInformation(6311, SR.GetResourceString(SR.ID6311), result.Claim ?? result.Error.ToString());
context.Reject(
error: Errors.InvalidDPoPProof,
description: result.Claim is not null ? SR.FormatID2226(result.Claim) : SR.GetResourceString(SR.ID2225),
uri: SR.FormatID8000(result.Claim is not null ? SR.ID2226 : SR.ID2225));
return;
}
// If nonces are required, ensure the proof contains a valid nonce issued by this server.
if (context.Options.RequireDPoPNonces && !await ValidateDPoPNonceAsync(context.Transaction, OpenIddictDPoPHelpers.GetNonce(token)))
{
context.Logger.LogInformation(6313, SR.GetResourceString(SR.ID6313));
context.Transaction.DPoPNonce = await CreateDPoPNonceAsync(context.Transaction);
context.Reject(
error: Errors.UseDPoPNonce,
description: SR.GetResourceString(SR.ID2229),
uri: SR.FormatID8000(SR.ID2229));
return;
}
// When token storage is enabled, prevent the proof from being replayed by storing
// a token entry whose reference identifier is derived from the key and the proof "jti".
if (!context.Options.EnableDegradedMode && !context.Options.DisableTokenStorage)
{
var manager = context.ServiceProvider.GetService<IOpenIddictTokenManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var identifier = thumbprint + "." + OpenIddictDPoPHelpers.GetJwtId(token);
if (await manager.FindByReferenceIdAsync(identifier, context.CancellationToken) is not null)
{
context.Logger.LogInformation(6312, SR.GetResourceString(SR.ID6312));
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2227),
uri: SR.FormatID8000(SR.ID2227));
return;
}
var issued = new DateTimeOffset(token.IssuedAt, TimeSpan.Zero);
try
{
await manager.CreateAsync(new OpenIddictTokenDescriptor
{
CreationDate = date,
ExpirationDate = (issued > date ? issued : date) + context.Options.DPoPProofLifetime,
ReferenceId = identifier,
Status = Statuses.Redeemed,
Type = TokenTypeIdentifiers.Private.DPoPProof
}, context.CancellationToken);
}
// If the token entry couldn't be created because a concurrent request using the same
// proof created it first (e.g because a unique index exists), reject the request.
catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception))
{
if (await manager.FindByReferenceIdAsync(identifier, context.CancellationToken) is null)
{
throw;
}
context.Logger.LogInformation(6312, SR.GetResourceString(SR.ID6312));
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.GetResourceString(SR.ID2227),
uri: SR.FormatID8000(SR.ID2227));
return;
}
}
// When the proof is sent to the pushed authorization endpoint, bind the authorization code that will
// be issued to the proof key, unless a "dpop_jkt" parameter was specified, in which case both must match.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-10.1 for more information.
if (context.EndpointType is OpenIddictServerEndpointType.PushedAuthorization)
{
if (string.IsNullOrEmpty(context.Request.DPoPJkt))
{
context.Request.DPoPJkt = thumbprint;
}
else if (!OpenIddictDPoPHelpers.FixedTimeEquals(context.Request.DPoPJkt, thumbprint))
{
context.Reject(
error: Errors.InvalidDPoPProof,
description: SR.FormatID2233(Parameters.DPoPJkt),
uri: SR.FormatID8000(SR.ID2233));
return;
}
}
var principal = new ClaimsPrincipal(new ClaimsIdentity(token.Claims,
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role));
principal.SetClaim(Claims.Private.DPoPJwkThumbprint, thumbprint);
context.Transaction.DPoPProofPrincipal = principal;
}
}
/// <summary>
/// Contains the logic responsible for validating the request token resolved from the context.
/// </summary>
@ -3676,20 +3866,17 @@ public static partial class OpenIddictServerHandlers
context.Logger.LogDebug(6010, SR.GetResourceString(SR.ID6010), scopes);
}
// If certificate-bound access tokens are enabled and a client certificate was used, bind the access
// token to the certificate by storing a confirmation claim containing the certificate thumbprint.
if (context.Options.UseClientCertificateBoundAccessTokens &&
context.Transaction.RemoteCertificate is X509Certificate2 certificate)
// If certificate-bound access tokens are enabled and a client certificate was used or if a valid DPoP
// proof was sent, bind the access token by storing a confirmation claim containing the thumbprint
// of the certificate and/or the thumbprint of the DPoP proof key.
if (CreateConfirmationClaim(context.Transaction,
certificate: context.Options.UseClientCertificateBoundAccessTokens,
proof: true) is JsonObject confirmation)
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
principal.SetClaim(Claims.Confirmation, confirmation);
}
context.AccessTokenPrincipal = principal;
static JsonNode CreateConfirmationClaim(X509Certificate2 certificate) => new JsonObject
{
[JsonWebKeyParameterNames.X5tS256] = Base64Url.EncodeToString(certificate.GetCertHash(HashAlgorithmName.SHA256))
};
}
}
@ -3796,6 +3983,16 @@ public static partial class OpenIddictServerHandlers
// the token endpoint as part of the JWT identity token.
principal.SetClaim(Claims.Private.Nonce, context.Request.Nonce);
// If DPoP support is enabled and a "dpop_jkt" parameter was specified (or inferred from the
// DPoP proof sent to the pushed authorization endpoint), attach it to the authorization code
// to ensure the same key is used to sign the DPoP proof sent when redeeming the code.
//
// See https://datatracker.ietf.org/doc/html/rfc9449#section-10 for more information.
if (context.Options.EnableDPoPSupport && !string.IsNullOrEmpty(context.Request.DPoPJkt))
{
principal.SetClaim(Claims.Private.DPoPJwkThumbprint, context.Request.DPoPJkt);
}
context.AuthorizationCodePrincipal = principal;
}
}
@ -4214,60 +4411,30 @@ public static partial class OpenIddictServerHandlers
principal.SetClaim(Claims.ClientId, context.ClientId);
}
if (context.Transaction.RemoteCertificate is X509Certificate2 certificate)
// If certificate-bound access tokens are enabled and a client certificate was used or if a valid DPoP
// proof was sent, bind the access token by storing a confirmation claim containing the thumbprint
// of the certificate and/or the thumbprint of the DPoP proof key.
if (context.IssuedTokenType is TokenTypeIdentifiers.AccessToken &&
CreateConfirmationClaim(context.Transaction,
certificate: context.Options.UseClientCertificateBoundAccessTokens,
proof: true) is JsonObject confirmation)
{
// If certificate-bound access tokens are enabled and a client certificate was used, bind the access
// token to the certificate by storing a confirmation claim containing the certificate thumbprint.
if (context.IssuedTokenType is TokenTypeIdentifiers.AccessToken &&
context.Options.UseClientCertificateBoundAccessTokens)
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
}
// If certificate-bound refresh tokens are enabled and a client certificate was used, bind the refresh
// token to the certificate by storing a confirmation claim containing the certificate thumbprint.
if (context.IssuedTokenType is TokenTypeIdentifiers.RefreshToken &&
context.Options.UseClientCertificateBoundRefreshTokens &&
!string.IsNullOrEmpty(context.ClientId))
{
// If the degraded mode was enabled, it is impossible to determine whether
// the client is a public or confidential application. In this case, the
// confirmation claim is always added to the principal by default.
//
// Applications that need to use a different logic can implement their
// own event handler and remove the confirmation claim from the principal.
if (context.Options.EnableDegradedMode)
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
}
principal.SetClaim(Claims.Confirmation, confirmation);
}
else
{
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
// Note: refresh tokens are only bound to the provided certificate when the client
// is a public application, as refresh tokens issued to confidential applications
// are already sender-constrained via standard client authentication, which is more
// flexible than certificate-based token binding, as rotating client credentials is
// easier in that case (specially when using PKI-based mTLS client authentication).
if (await manager.HasClientTypeAsync(application, ClientTypes.Public, context.CancellationToken))
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
}
}
}
// If certificate-bound refresh tokens are enabled and a client certificate was used or if a valid DPoP
// proof was sent, bind the refresh token issued to public clients by storing a confirmation claim.
else if (context.IssuedTokenType is TokenTypeIdentifiers.RefreshToken &&
!string.IsNullOrEmpty(context.ClientId) &&
CreateConfirmationClaim(context.Transaction,
certificate: context.Options.UseClientCertificateBoundRefreshTokens,
proof: true) is JsonObject node &&
await IsRefreshTokenBindingRequiredAsync(context, context.ClientId))
{
principal.SetClaim(Claims.Confirmation, node);
}
context.IssuedTokenPrincipal = principal;
static JsonNode CreateConfirmationClaim(X509Certificate2 certificate) => new JsonObject
{
[JsonWebKeyParameterNames.X5tS256] = Base64Url.EncodeToString(certificate.GetCertHash(HashAlgorithmName.SHA256))
};
}
}
@ -4482,49 +4649,19 @@ public static partial class OpenIddictServerHandlers
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0496))
});
// If certificate-bound refresh tokens are enabled and a client certificate was used, bind the refresh
// token to the certificate by storing a confirmation claim containing the certificate thumbprint.
if (context.Options.UseClientCertificateBoundRefreshTokens &&
context.Transaction.RemoteCertificate is X509Certificate2 certificate &&
!string.IsNullOrEmpty(context.ClientId))
// If certificate-bound refresh tokens are enabled and a client certificate was used or if a valid DPoP
// proof was sent, bind the refresh token issued to public clients by storing a confirmation claim
// containing the thumbprint of the certificate and/or the thumbprint of the DPoP proof key.
if (!string.IsNullOrEmpty(context.ClientId) &&
CreateConfirmationClaim(context.Transaction,
certificate: context.Options.UseClientCertificateBoundRefreshTokens,
proof: true) is JsonObject confirmation &&
await IsRefreshTokenBindingRequiredAsync(context, context.ClientId))
{
// If the degraded mode was enabled, it is impossible to determine whether
// the client is a public or confidential application. In this case, the
// confirmation claim is always added to the principal by default.
//
// Applications that need to use a different logic can implement their
// own event handler and remove the confirmation claim from the principal.
if (context.Options.EnableDegradedMode)
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
}
else
{
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(context.ClientId, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
// Note: refresh tokens are only bound to the provided certificate when the client
// is a public application, as refresh tokens issued to confidential applications
// are already sender-constrained via standard client authentication, which is more
// flexible than certificate-based token binding, as rotating client credentials is
// easier in that case (specially when using PKI-based mTLS client authentication).
if (await manager.HasClientTypeAsync(application, ClientTypes.Public, context.CancellationToken))
{
principal.SetClaim(Claims.Confirmation, CreateConfirmationClaim(certificate));
}
}
principal.SetClaim(Claims.Confirmation, confirmation);
}
context.RefreshTokenPrincipal = principal;
static JsonNode CreateConfirmationClaim(X509Certificate2 certificate) => new JsonObject
{
[JsonWebKeyParameterNames.X5tS256] = Base64Url.EncodeToString(certificate.GetCertHash(HashAlgorithmName.SHA256))
};
}
}
@ -5657,7 +5794,7 @@ public static partial class OpenIddictServerHandlers
if (context.IncludeAccessToken)
{
context.Response.AccessToken = context.AccessToken;
context.Response.TokenType = TokenTypes.Bearer;
context.Response.TokenType = IsDPoPBoundToken(context.AccessTokenPrincipal) ? TokenTypes.DPoP : TokenTypes.Bearer;
// If the principal is available, attach additional metadata.
if (context.AccessTokenPrincipal is not null)
@ -5714,9 +5851,13 @@ 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.
context.Response.AccessToken = context.IssuedToken;
context.Response.IssuedTokenType = context.IssuedTokenType;
context.Response.TokenType = context.IssuedTokenType is TokenTypeIdentifiers.AccessToken
? TokenTypes.Bearer
: TokenTypes.NotApplicable;
context.Response.TokenType = context.IssuedTokenType switch
{
TokenTypeIdentifiers.AccessToken when IsDPoPBoundToken(context.IssuedTokenPrincipal) => TokenTypes.DPoP,
TokenTypeIdentifiers.AccessToken => TokenTypes.Bearer,
_ => TokenTypes.NotApplicable
};
// If the principal is available, attach additional metadata.
if (context.IssuedTokenPrincipal is not null)
@ -6044,4 +6185,129 @@ public static partial class OpenIddictServerHandlers
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Creates a confirmation claim containing the thumbprint of the client certificate
/// and/or the thumbprint of the DPoP proof key, if applicable.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="certificate">Whether the client certificate should be used, if available.</param>
/// <param name="proof">Whether the DPoP proof key should be used, if available.</param>
/// <returns>The confirmation claim or <see langword="null"/> if no binding is applicable.</returns>
private static JsonObject? CreateConfirmationClaim(OpenIddictServerTransaction transaction, bool certificate, bool proof)
{
var node = new JsonObject();
if (certificate && transaction.RemoteCertificate is X509Certificate2 value)
{
node[JsonWebKeyParameterNames.X5tS256] = Base64Url.EncodeToString(value.GetCertHash(HashAlgorithmName.SHA256));
}
if (proof && transaction.DPoPProofPrincipal?.GetClaim(Claims.Private.DPoPJwkThumbprint) is { Length: > 0 } thumbprint)
{
node[Claims.JsonWebKeyThumbprint] = thumbprint;
}
return node.Count is > 0 ? node : null;
}
/// <summary>
/// Determines whether refresh tokens issued to the specified client must be bound
/// to the client certificate or DPoP proof key (i.e whether the client is public).
/// </summary>
/// <param name="context">The context.</param>
/// <param name="identifier">The client identifier.</param>
/// <returns><see langword="true"/> if refresh tokens must be bound, <see langword="false"/> otherwise.</returns>
private static async ValueTask<bool> IsRefreshTokenBindingRequiredAsync(ProcessSignInContext context, string identifier)
{
// If the degraded mode was enabled, it is impossible to determine whether
// the client is a public or confidential application. In this case, the
// confirmation claim is always added to the principal by default.
//
// Applications that need to use a different logic can implement their
// own event handler and remove the confirmation claim from the principal.
if (context.Options.EnableDegradedMode)
{
return true;
}
var manager = context.ServiceProvider.GetService<IOpenIddictApplicationManager>()
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
var application = await manager.FindByClientIdAsync(identifier, context.CancellationToken)
?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0017));
// Note: refresh tokens are only bound when the client is a public application, as refresh tokens
// issued to confidential applications are already sender-constrained via standard client authentication,
// which is more flexible than token binding, as rotating client credentials is easier in that case.
return await manager.HasClientTypeAsync(application, ClientTypes.Public, context.CancellationToken);
}
/// <summary>
/// Determines whether the specified principal contains a DPoP confirmation ("jkt") claim.
/// </summary>
/// <param name="principal">The principal.</param>
/// <returns><see langword="true"/> if the token is bound to a DPoP key, <see langword="false"/> otherwise.</returns>
internal static bool IsDPoPBoundToken(ClaimsPrincipal? principal)
=> principal?.GetClaim(Claims.Confirmation) is { Length: > 0 } value &&
JsonNode.Parse(value) is JsonObject node && node.ContainsKey(Claims.JsonWebKeyThumbprint);
/// <summary>
/// Creates a new DPoP nonce signed using the signing credentials of the server.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <returns>The nonce.</returns>
internal static async ValueTask<string> CreateDPoPNonceAsync(OpenIddictServerTransaction transaction)
{
var credentials = await OpenIddictServerKeyRing.ResolveCredentialsAsync(transaction);
if (credentials.SigningCredentials is not [SigningCredentials signing, ..])
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0266));
}
var date = transaction.Options.TimeProvider.GetUtcNow();
return new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = false }.CreateToken(new SecurityTokenDescriptor
{
Claims = new Dictionary<string, object>(StringComparer.Ordinal)
{
[Claims.ExpiresAt] = (date + transaction.Options.DPoPNonceLifetime).ToUnixTimeSeconds(),
[Claims.IssuedAt] = date.ToUnixTimeSeconds()
},
SigningCredentials = signing,
TokenType = JsonWebTokenTypes.Private.DPoPNonce
});
}
/// <summary>
/// Determines whether the specified DPoP nonce was issued by the server and is not expired.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="nonce">The nonce.</param>
/// <returns><see langword="true"/> if the nonce is valid, <see langword="false"/> otherwise.</returns>
internal static async ValueTask<bool> ValidateDPoPNonceAsync(OpenIddictServerTransaction transaction, string? nonce)
{
if (string.IsNullOrEmpty(nonce))
{
return false;
}
var credentials = await OpenIddictServerKeyRing.ResolveCredentialsAsync(transaction);
var result = await new JsonWebTokenHandler().ValidateTokenAsync(nonce, new TokenValidationParameters
{
IssuerSigningKeys = credentials.SigningCredentials.Select(static credentials => credentials.Key).ToList(),
RequireExpirationTime = true,
RequireSignedTokens = true,
TryAllIssuerSigningKeys = true,
ValidateAudience = false,
ValidateIssuer = false,
// Note: the lifetime is manually validated to use the time provider attached to the options.
ValidateLifetime = false,
ValidTypes = [JsonWebTokenTypes.Private.DPoPNonce]
});
return result is { IsValid: true, SecurityToken: JsonWebToken token } &&
new DateTimeOffset(token.ValidTo, TimeSpan.Zero) > transaction.Options.TimeProvider.GetUtcNow();
}
}

50
src/OpenIddict.Server/OpenIddictServerOptions.cs

@ -605,6 +605,56 @@ public sealed class OpenIddictServerOptions
/// </summary>
public bool EnableRequestObjectSupport { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether OAuth 2.0 Demonstrating Proof of Possession (DPoP, RFC 9449)
/// is supported. When enabled, DPoP proofs sent to the token, pushed authorization and userinfo endpoints
/// are validated and access tokens (and refresh tokens issued to public clients) are bound to the proof key.
/// </summary>
public bool EnableDPoPSupport { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether all token requests must include a valid DPoP proof.
/// </summary>
/// <remarks>
/// Note: this option requires enabling DPoP support using <see cref="EnableDPoPSupport"/>.
/// </remarks>
public bool RequireDPoP { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether DPoP proofs must include a server-provided nonce.
/// </summary>
/// <remarks>
/// Note: this option requires enabling DPoP support using <see cref="EnableDPoPSupport"/>.
/// </remarks>
public bool RequireDPoPNonces { get; set; }
/// <summary>
/// Gets or sets the maximum difference allowed between the issuance date of a DPoP proof and the current date.
/// </summary>
public TimeSpan DPoPProofLifetime { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>
/// Gets or sets the lifetime of the DPoP nonces issued when <see cref="RequireDPoPNonces"/> is enabled.
/// </summary>
public TimeSpan DPoPNonceLifetime { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>
/// Gets the asymmetric signing algorithms allowed for DPoP proofs.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public HashSet<string> DPoPSigningAlgorithms { get; } = new(StringComparer.Ordinal)
{
SecurityAlgorithms.EcdsaSha256,
SecurityAlgorithms.EcdsaSha384,
SecurityAlgorithms.EcdsaSha512,
SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.RsaSha384,
SecurityAlgorithms.RsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.RsaSsaPssSha384,
SecurityAlgorithms.RsaSsaPssSha512
};
/// <summary>
/// Gets the OAuth 2.0 resources enabled for this application (typically used
/// with the OAuth 2.0 Token Exchange flow and with authorization or pushed

30
src/OpenIddict.Server/OpenIddictServerTransaction.cs

@ -5,6 +5,7 @@
*/
using System.ComponentModel;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
namespace OpenIddict.Server;
@ -30,6 +31,35 @@ public sealed class OpenIddictServerTransaction
/// </summary>
public X509Certificate2? RemoteCertificate { get; set; }
/// <summary>
/// Gets or sets the authentication scheme used to send the access token
/// in the Authorization header (e.g "Bearer" or "DPoP"), if applicable.
/// </summary>
public string? AccessTokenScheme { get; set; }
/// <summary>
/// Gets or sets the raw DPoP proof sent by the remote peer, if available.
/// </summary>
public string? DPoPProof { get; set; }
/// <summary>
/// Gets or sets the principal extracted from the validated DPoP proof, if available.
/// </summary>
/// <remarks>
/// Note: the RFC 7638 thumbprint of the proof key is stored in the private "oi_dpop_jkt" claim.
/// </remarks>
public ClaimsPrincipal? DPoPProofPrincipal { get; set; }
/// <summary>
/// Gets or sets the DPoP nonce returned to the remote peer using the "DPoP-Nonce" header, if applicable.
/// </summary>
public string? DPoPNonce { get; set; }
/// <summary>
/// Gets or sets the HTTP method of the current transaction, if available.
/// </summary>
public string? RequestMethod { get; set; }
/// <summary>
/// Gets or sets the type of the endpoint processing the current transaction.
/// </summary>

5
src/OpenIddict.Validation/OpenIddict.Validation.csproj

@ -17,6 +17,11 @@ To use the validation feature on ASP.NET Core or OWIN/Katana, reference the Open
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\shared\OpenIddict.Extensions\IdentityModel\*.cs" Visible="false" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
<PackageReference Include="Microsoft.IdentityModel.Protocols" />

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

@ -176,11 +176,34 @@ public class OpenIddictServerIntegrationTestClient : IAsyncDisposable
ArgumentNullException.ThrowIfNull(request);
using var message = CreateRequestMessage(request, method, uri);
foreach (var header in RequestHeaders)
{
message.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
using var response = await HttpClient.SendAsync(message);
ResponseHeaders.Clear();
foreach (var header in response.Headers)
{
ResponseHeaders[header.Key] = [.. header.Value];
}
return await GetResponseAsync(response);
}
/// <summary>
/// Gets the additional headers attached to all the requests sent by this client.
/// </summary>
public Dictionary<string, string[]> RequestHeaders { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets the headers returned in the last response received by this client.
/// </summary>
public Dictionary<string, string[]> ResponseHeaders { get; } = new(StringComparer.OrdinalIgnoreCase);
private HttpRequestMessage CreateRequestMessage(OpenIddictRequest request, HttpMethod method, Uri uri)
{
if (!uri.IsAbsoluteUri)

1125
test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.DPoP.cs

File diff suppressed because it is too large

24
test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs

@ -1966,6 +1966,30 @@ public class OpenIddictServerBuilderTests
Assert.Null(options.PollingInterval);
}
[Fact]
public void EnableDPoPSupport_DPoPOptionsAreCorrectlySet()
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.EnableDPoPSupport()
.RequireDPoP()
.RequireDPoPNonces()
.SetDPoPProofLifetime(TimeSpan.FromMinutes(2))
.SetDPoPNonceLifetime(TimeSpan.FromMinutes(3));
var options = GetOptions(services);
// Assert
Assert.True(options.EnableDPoPSupport);
Assert.True(options.RequireDPoP);
Assert.True(options.RequireDPoPNonces);
Assert.Equal(TimeSpan.FromMinutes(2), options.DPoPProofLifetime);
Assert.Equal(TimeSpan.FromMinutes(3), options.DPoPNonceLifetime);
}
[Fact]
public void EnableRequestObjectSupport_RequestObjectSupportIsEnabled()
{

49
test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs

@ -316,6 +316,55 @@ public class OpenIddictServerConfigurationTests
Assert.Contains(SR.GetResourceString(SR.ID0524), result.Failures!, StringComparer.Ordinal);
}
[Theory]
[InlineData(true, false, "ID0544")]
[InlineData(false, true, "ID0545")]
public void Validate_ReturnsAnErrorWhenDPoPIsRequiredWithoutDPoPSupport(bool proofs, bool nonces, string identifier)
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.RequireDPoP = proofs;
options.RequireDPoPNonces = nonces;
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(identifier), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenSymmetricDPoPAlgorithmIsAllowed()
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.EnableDPoPSupport = true;
options.DPoPSigningAlgorithms.Add(SecurityAlgorithms.HmacSha256);
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0546), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_ReturnsAnErrorWhenDPoPProofLifetimeIsNotPositive()
{
// Arrange
var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider());
var options = CreateBaseOptions();
options.DPoPProofLifetime = TimeSpan.Zero;
// Act
var result = configuration.Validate(name: null, options);
// Assert
Assert.Contains(SR.GetResourceString(SR.ID0547), result.Failures!, StringComparer.Ordinal);
}
[Fact]
public void Validate_DoesNotReturnAnErrorWhenSignedRequestObjectsAreRequiredWithRequestObjectSupport()
{

Loading…
Cancel
Save