diff --git a/Directory.Packages.props b/Directory.Packages.props
index 40909ed4..9642911f 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -31,6 +31,7 @@
+
@@ -114,6 +115,7 @@
+
diff --git a/shared/OpenIddict.Extensions/IdentityModel/OpenIddictDPoPHelpers.cs b/shared/OpenIddict.Extensions/IdentityModel/OpenIddictDPoPHelpers.cs
new file mode 100644
index 00000000..5c2bb29a
--- /dev/null
+++ b/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;
+
+///
+/// Exposes the helpers used to create and validate OAuth 2.0 Demonstrating Proof of Possession (DPoP) proofs.
+///
+///
+/// See https://datatracker.ietf.org/doc/html/rfc9449 for more information.
+///
+internal static class OpenIddictDPoPHelpers
+{
+ ///
+ /// Represents the errors that can be returned when validating a DPoP proof.
+ ///
+ internal enum ProofError
+ {
+ None = 0,
+ Malformed,
+ InvalidType,
+ InvalidAlgorithm,
+ InvalidKey,
+ InvalidSignature,
+ InvalidClaim
+ }
+
+ ///
+ /// Represents the result of a DPoP proof validation.
+ ///
+ /// The error, if applicable.
+ /// The name of the missing or invalid claim, if applicable.
+ /// The validated proof.
+ /// The RFC 7638 thumbprint of the public key contained in the proof.
+ internal sealed record class ProofValidationResult(
+ ProofError Error, string? Claim, JsonWebToken? Token, string? Thumbprint);
+
+ ///
+ /// Gets the asymmetric signing algorithms that can be used to create DPoP proofs.
+ ///
+ internal static IReadOnlyList SupportedAlgorithms { get; } =
+ [
+ SecurityAlgorithms.EcdsaSha256,
+ SecurityAlgorithms.EcdsaSha384,
+ SecurityAlgorithms.EcdsaSha512,
+ SecurityAlgorithms.RsaSha256,
+ SecurityAlgorithms.RsaSha384,
+ SecurityAlgorithms.RsaSha512,
+ SecurityAlgorithms.RsaSsaPssSha256,
+ SecurityAlgorithms.RsaSsaPssSha384,
+ SecurityAlgorithms.RsaSsaPssSha512
+ ];
+
+ ///
+ /// Computes the "ath" value (i.e the base64url-encoded SHA-256 hash of the ASCII representation) of an access token.
+ ///
+ /// The access token.
+ /// The base64url-encoded hash.
+ internal static string ComputeAccessTokenHash(string token)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(token);
+
+ return Base64Url.EncodeToString(SHA256.HashData(Encoding.ASCII.GetBytes(token)));
+ }
+
+ ///
+ /// Determines whether the two specified strings are equal using a time-constant comparison.
+ ///
+ /// The first string.
+ /// The second string.
+ /// if the two strings are equal, otherwise.
+ 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()));
+ }
+
+ ///
+ /// Determines whether the specified "htu" value matches the specified request URI,
+ /// ignoring the query string and fragment components, as required by RFC 9449.
+ ///
+ /// The "htu" value extracted from the DPoP proof.
+ /// The request URI.
+ /// if the URIs match, otherwise.
+ 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);
+ }
+
+ ///
+ /// Computes the RFC 7638 thumbprint of the public key attached to the specified signing credentials.
+ ///
+ /// The signing credentials.
+ /// The base64url-encoded thumbprint.
+ internal static string ComputeJsonWebKeyThumbprint(SigningCredentials credentials)
+ {
+ ArgumentNullException.ThrowIfNull(credentials);
+
+ return Base64UrlEncoder.Encode(new JsonWebKey(CreatePublicJsonWebKey(credentials.Key).ToJsonString()).ComputeJwkThumbprint());
+ }
+
+ ///
+ /// Creates a DPoP proof using the specified signing credentials.
+ ///
+ /// The asymmetric signing credentials.
+ /// The HTTP method of the request.
+ /// The URI of the request.
+ /// The issuance date.
+ /// The access token, if applicable.
+ /// The server-provided nonce, if applicable.
+ /// The DPoP proof.
+ 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(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(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
+ };
+ }
+
+ ///
+ /// Validates the specified DPoP proof.
+ ///
+ /// The DPoP proof.
+ /// The HTTP method of the request.
+ /// The URI of the request.
+ /// The allowed signing algorithms.
+ /// The current date.
+ /// The maximum difference allowed between the current date and the "iat" claim.
+ /// The access token, if the "ath" claim must be validated.
+ /// The validation result.
+ internal static async ValueTask ValidateProofAsync(string proof, string method, Uri uri,
+ IReadOnlyCollection 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);
+ }
+
+ ///
+ /// Resolves the unique identifier ("jti") of the specified DPoP proof.
+ ///
+ /// The DPoP proof.
+ /// The unique identifier.
+ internal static string? GetJwtId(JsonWebToken token)
+ => token.TryGetPayloadValue(OpenIddictConstants.Claims.JwtId, out string? value) ? value : null;
+
+ ///
+ /// Resolves the nonce attached to the specified DPoP proof, if applicable.
+ ///
+ /// The DPoP proof.
+ /// The nonce, if applicable.
+ internal static string? GetNonce(JsonWebToken token)
+ => token.TryGetPayloadValue(OpenIddictConstants.Claims.Nonce, out string? value) ? value : null;
+
+ ///
+ /// Creates a JSON Web Key containing only the public members of the specified asymmetric key.
+ ///
+ /// The asymmetric key.
+ /// The JSON representation of the public key.
+ 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)
+ };
+ }
+}
diff --git a/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj b/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj
index a577891e..ffdd77a3 100644
--- a/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj
+++ b/shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj
@@ -10,6 +10,10 @@
+
+
+
+
diff --git a/src/OpenIddict.Abstractions/OpenIddictConstants.cs b/src/OpenIddict.Abstractions/OpenIddictConstants.cs
index 17685af5..7efceb79 100644
--- a/src/OpenIddict.Abstractions/OpenIddictConstants.cs
+++ b/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";
}
}
diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index 8b4838aa..af9ef350 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -1858,6 +1858,30 @@ To use ASP.NET Core Data Protection, reference the 'OpenIddict.Server.DataProtec
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.
+
+ DPoP proofs cannot be required when DPoP support is not enabled.
+To enable DPoP support, call 'services.AddOpenIddict().AddServer().EnableDPoPSupport()'.
+
+
+ DPoP nonces cannot be required when DPoP support is not enabled.
+To enable DPoP support, call 'services.AddOpenIddict().AddServer().EnableDPoPSupport()'.
+
+
+ At least one asymmetric signing algorithm (e.g ES256 or PS256) must be allowed for DPoP proofs and only asymmetric algorithms can be used.
+
+
+ The DPoP proof and nonce lifetimes must be positive.
+
+
+ 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.
+
+
+ The HTTP method of the current request couldn't be resolved, which is required to validate DPoP proofs.
+
+
+ No DPoP signing credentials were attached to the client registration.
+To enable DPoP, call 'services.AddOpenIddict().AddClient().EnableDPoPTokenBinding()'.
+
The backchannel authentication request was not correctly extracted.
To extract backchannel authentication requests, create a class implementing 'IOpenIddictServerHandler<ExtractBackchannelAuthenticationRequestContext>' and register it using 'services.AddOpenIddict().AddServer().AddEventHandler()'.
@@ -2540,6 +2564,36 @@ To apply backchannel authentication responses, create a class implementing 'IOpe
The key activation, expiration and retirement dates must be specified and ordered chronologically.
+
+ The specified DPoP proof is malformed or invalid.
+
+
+ The '{0}' claim of the DPoP proof is missing or invalid.
+
+
+ The specified DPoP proof has already been used.
+
+
+ A valid DPoP proof is required to use this endpoint.
+
+
+ A server-provided nonce must be included in the DPoP proof.
+
+
+ A DPoP-based proof-of-possession is required to use this token.
+
+
+ The specified DPoP-based proof-of-possession is not valid.
+
+
+ The specified token is not bound to the key used to sign the DPoP proof.
+
+
+ The key used to sign the DPoP proof doesn't match the '{0}' parameter.
+
+
+ A single DPoP proof must be specified.
+
The '{0}' parameter shouldn't be null or empty at this point.
@@ -3443,6 +3497,18 @@ This may indicate that the hashed entry is corrupted or malformed.
The automatically managed key '{KeyId}' could not be unprotected and was ignored.
+
+ The DPoP proof was rejected because it was invalid ({Reason}).
+
+
+ The DPoP proof was rejected because it was already used.
+
+
+ The DPoP proof was rejected because it didn't contain a valid server-provided nonce.
+
+
+ The token was rejected because the DPoP proof was missing or didn't match the confirmation claim.
+
https://documentation.openiddict.com/errors/{0}
diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
index 24927152..f997b7a4 100644
--- a/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
+++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictConfiguration.cs
@@ -57,6 +57,11 @@ public sealed class OpenIddictConfiguration
///
public HashSet DeviceAuthorizationEndpointAuthMethodsSupported { get; } = new(StringComparer.Ordinal);
+ ///
+ /// Gets the signing algorithms supported by the server for DPoP proofs.
+ ///
+ public HashSet DPoPSigningAlgValuesSupported { get; } = new(StringComparer.Ordinal);
+
///
/// Gets or sets the URI of the end session endpoint.
///
diff --git a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs
index 294e5d2d..0a3049e8 100644
--- a/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs
+++ b/src/OpenIddict.Abstractions/Primitives/OpenIddictRequest.cs
@@ -318,6 +318,15 @@ public class OpenIddictRequest : OpenIddictMessage
set => SetParameter(OpenIddictConstants.Parameters.Display, value);
}
+ ///
+ /// Gets or sets the "dpop_jkt" parameter.
+ ///
+ public string? DPoPJkt
+ {
+ get => (string?) GetParameter(OpenIddictConstants.Parameters.DPoPJkt);
+ set => SetParameter(OpenIddictConstants.Parameters.DPoPJkt, value);
+ }
+
///
/// Gets or sets the "grant_type" parameter.
///
diff --git a/src/OpenIddict.Client/OpenIddict.Client.csproj b/src/OpenIddict.Client/OpenIddict.Client.csproj
index 590c71f9..b3da3a39 100644
--- a/src/OpenIddict.Client/OpenIddict.Client.csproj
+++ b/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
+
+
+
+
diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs
index 70e6cbf2..f4b9690c 100644
--- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs
+++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreConstants.cs
@@ -11,6 +11,12 @@ namespace OpenIddict.Server.AspNetCore;
///
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";
diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs
index c65599c1..71436281 100644
--- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs
+++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Authentication.cs
@@ -49,6 +49,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractPostRequest.Descriptor,
ValidateClientAuthenticationMethod.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
ExtractBasicAuthenticationCredentials.Descriptor,
/*
@@ -57,6 +58,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
AttachHttpResponseCode.Descriptor,
AttachCacheControlHeader.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessJsonResponse.Descriptor
];
diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Exchange.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Exchange.cs
index fbc3d97a..d5739d32 100644
--- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Exchange.cs
+++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Exchange.cs
@@ -20,6 +20,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractPostRequest.Descriptor,
ValidateClientAuthenticationMethod.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
ExtractBasicAuthenticationCredentials.Descriptor,
/*
@@ -33,6 +34,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
AttachHttpResponseCode.Descriptor,
AttachCacheControlHeader.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessJsonResponse.Descriptor
];
}
diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Userinfo.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Userinfo.cs
index a077d104..6a575e95 100644
--- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Userinfo.cs
+++ b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.Userinfo.cs
@@ -20,6 +20,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
ExtractGetOrPostRequest.Descriptor,
ExtractAccessToken.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
/*
* UserInfo request handling:
@@ -31,6 +32,7 @@ public static partial class OpenIddictServerAspNetCoreHandlers
*/
AttachHttpResponseCode.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessChallengeErrorResponse.Descriptor,
ProcessJsonResponse.Descriptor
];
diff --git a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs b/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
index 1432a049..b6a1c623 100644
--- a/src/OpenIddict.Server.AspNetCore/OpenIddictServerAspNetCoreHandlers.cs
+++ b/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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class ExtractDPoPProof : IOpenIddictServerHandler
+ where TContext : BaseValidatingContext
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .AddFilter()
+ .UseSingletonHandler>()
+ .SetOrder(ExtractClientCertificate.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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;
+ }
+ }
+
///
/// 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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class AttachDPoPNonceHeader : IOpenIddictServerHandler where TContext : BaseRequestContext
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .AddFilter()
+ .UseSingletonHandler>()
+ .SetOrder(AttachWwwAuthenticateHeader.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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;
+ }
+ }
+
///
/// 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.
diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinConstants.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinConstants.cs
index 487cba0c..0337d33c 100644
--- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinConstants.cs
+++ b/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";
diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs
index 1fc9a32b..a5ab9ee4 100644
--- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs
+++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Authentication.cs
@@ -49,6 +49,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractPostRequest.Descriptor,
ValidateClientAuthenticationMethod.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
ExtractBasicAuthenticationCredentials.Descriptor,
/*
@@ -59,6 +60,7 @@ public static partial class OpenIddictServerOwinHandlers
SuppressFormsAuthenticationRedirect.Descriptor,
AttachCacheControlHeader.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessJsonResponse.Descriptor,
];
diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs
index 5e6d6054..7152adc5 100644
--- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs
+++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Exchange.cs
@@ -20,6 +20,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractPostRequest.Descriptor,
ValidateClientAuthenticationMethod.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
ExtractBasicAuthenticationCredentials.Descriptor,
/*
@@ -35,6 +36,7 @@ public static partial class OpenIddictServerOwinHandlers
SuppressFormsAuthenticationRedirect.Descriptor,
AttachCacheControlHeader.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessJsonResponse.Descriptor
];
}
diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs
index c47cf54d..882d7a0e 100644
--- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs
+++ b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.Userinfo.cs
@@ -20,6 +20,7 @@ public static partial class OpenIddictServerOwinHandlers
ExtractGetOrPostRequest.Descriptor,
ExtractAccessToken.Descriptor,
ExtractClientCertificate.Descriptor,
+ ExtractDPoPProof.Descriptor,
/*
* UserInfo request handling:
@@ -33,6 +34,7 @@ public static partial class OpenIddictServerOwinHandlers
AttachOwinResponseChallenge.Descriptor,
SuppressFormsAuthenticationRedirect.Descriptor,
AttachWwwAuthenticateHeader.Descriptor,
+ AttachDPoPNonceHeader.Descriptor,
ProcessChallengeErrorResponse.Descriptor,
ProcessJsonResponse.Descriptor
];
diff --git a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs b/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
index 9032c461..999e90fd 100644
--- a/src/OpenIddict.Server.Owin/OpenIddictServerOwinHandlers.cs
+++ b/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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class ExtractDPoPProof : IOpenIddictServerHandler
+ where TContext : BaseValidatingContext
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .AddFilter()
+ .UseSingletonHandler>()
+ .SetOrder(ExtractClientCertificate.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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;
+ }
+ }
+
///
/// 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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class AttachDPoPNonceHeader : IOpenIddictServerHandler where TContext : BaseRequestContext
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .AddFilter()
+ .UseSingletonHandler>()
+ .SetOrder(AttachWwwAuthenticateHeader.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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;
+ }
+ }
+
///
/// 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.
diff --git a/src/OpenIddict.Server/OpenIddict.Server.csproj b/src/OpenIddict.Server/OpenIddict.Server.csproj
index 12cf0c52..ea78647f 100644
--- a/src/OpenIddict.Server/OpenIddict.Server.csproj
+++ b/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
+
+
+
+
diff --git a/src/OpenIddict.Server/OpenIddictServerBuilder.cs b/src/OpenIddict.Server/OpenIddictServerBuilder.cs
index 72a00c54..1edaa4dc 100644
--- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs
+++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs
@@ -1836,6 +1836,52 @@ public sealed class OpenIddictServerBuilder
public OpenIddictServerBuilder EnableRequestObjectSupport()
=> Configure(options => options.EnableRequestObjectSupport = true);
+ ///
+ /// 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.
+ ///
+ /// The instance.
+ public OpenIddictServerBuilder EnableDPoPSupport()
+ => Configure(options => options.EnableDPoPSupport = true);
+
+ ///
+ /// Configures OpenIddict to require a valid DPoP proof for all token requests.
+ ///
+ ///
+ /// Note: DPoP support must be enabled using .
+ ///
+ /// The instance.
+ public OpenIddictServerBuilder RequireDPoP()
+ => Configure(options => options.RequireDPoP = true);
+
+ ///
+ /// 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.
+ ///
+ ///
+ /// Note: DPoP support must be enabled using .
+ ///
+ /// The instance.
+ public OpenIddictServerBuilder RequireDPoPNonces()
+ => Configure(options => options.RequireDPoPNonces = true);
+
+ ///
+ /// Sets the maximum difference allowed between the issuance date of a DPoP proof and the current date.
+ ///
+ /// The DPoP proof lifetime.
+ /// The instance.
+ public OpenIddictServerBuilder SetDPoPProofLifetime(TimeSpan lifetime)
+ => Configure(options => options.DPoPProofLifetime = lifetime);
+
+ ///
+ /// Sets the lifetime of the DPoP nonces issued by the server.
+ ///
+ /// The DPoP nonce lifetime.
+ /// The instance.
+ public OpenIddictServerBuilder SetDPoPNonceLifetime(TimeSpan lifetime)
+ => Configure(options => options.DPoPNonceLifetime = lifetime);
+
///
/// Sets the access token lifetime, after which client applications must retrieve
/// a new access token by making a grant_type=refresh_token token request
diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs
index 47fb9256..8eec9e2b 100644
--- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs
+++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs
@@ -335,6 +335,28 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions !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))
diff --git a/src/OpenIddict.Server/OpenIddictServerExtensions.cs b/src/OpenIddict.Server/OpenIddictServerExtensions.cs
index 2ab1ebe1..1b45f517 100644
--- a/src/OpenIddict.Server/OpenIddictServerExtensions.cs
+++ b/src/OpenIddict.Server/OpenIddictServerExtensions.cs
@@ -59,6 +59,7 @@ public static class OpenIddictServerExtensions
builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton();
+ builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton();
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
index 3d9559de..cba2c29a 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
+++ b/src/OpenIddict.Server/OpenIddictServerHandlerFilters.cs
@@ -851,6 +851,20 @@ public static class OpenIddictServerHandlerFilters
}
}
+ ///
+ /// Represents a filter that excludes the associated handlers if DPoP support was not enabled.
+ ///
+ public sealed class RequireDPoPSupportEnabled : IOpenIddictServerHandlerFilter
+ {
+ ///
+ public ValueTask IsActiveAsync(BaseContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+
+ return new(context.Options.EnableDPoPSupport);
+ }
+ }
+
///
/// Represents a filter that excludes the associated handlers if token storage was not enabled.
///
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
index 1fa6d823..5a678c50 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
+++ b/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.
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
index aca1e669..a750d89b 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Exchange.cs
+++ b/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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class ValidateDPoPRequirement : IOpenIddictServerHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(ValidateProofKeyForCodeExchangeRequirement.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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()
+ ?? 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;
+ }
+ }
+ }
+
///
/// 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
}
}
+ ///
+ /// 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.
+ ///
+ public sealed class ValidateDPoPJwkThumbprint : IOpenIddictServerHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .UseSingletonHandler()
+ .SetOrder(ValidateCodeVerifier.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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;
+ }
+ }
+
///
/// 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.
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs
index ac1ee416..87770634 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Introspection.cs
+++ b/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
};
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
index 09144b78..4ac287ca 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
+++ b/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;
}
}
diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs
index 5ab8fa61..caa32ba9 100644
--- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs
+++ b/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
}
}
+ ///
+ /// Contains the logic responsible for validating the DPoP proof sent to the token,
+ /// pushed authorization and userinfo endpoints, if applicable.
+ ///
+ public sealed class ValidateDPoPProof : IOpenIddictServerHandler
+ {
+ ///
+ /// Gets the default descriptor definition assigned to this handler.
+ ///
+ public static OpenIddictServerHandlerDescriptor Descriptor { get; }
+ = OpenIddictServerHandlerDescriptor.CreateBuilder()
+ .AddFilter()
+ .UseSingletonHandler()
+ .SetOrder(ValidateClientCertificate.Descriptor.Order + 500)
+ .SetType(OpenIddictServerHandlerType.BuiltIn)
+ .Build();
+
+ ///
+ 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()
+ ?? 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;
+ }
+ }
+
///
/// Contains the logic responsible for validating the request token resolved from the context.
///
@@ -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()
- ?? 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()
- ?? 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;
}
}
+
+ ///
+ /// Creates a confirmation claim containing the thumbprint of the client certificate
+ /// and/or the thumbprint of the DPoP proof key, if applicable.
+ ///
+ /// The transaction.
+ /// Whether the client certificate should be used, if available.
+ /// Whether the DPoP proof key should be used, if available.
+ /// The confirmation claim or if no binding is applicable.
+ 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;
+ }
+
+ ///
+ /// 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).
+ ///
+ /// The context.
+ /// The client identifier.
+ /// if refresh tokens must be bound, otherwise.
+ private static async ValueTask 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()
+ ?? 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);
+ }
+
+ ///
+ /// Determines whether the specified principal contains a DPoP confirmation ("jkt") claim.
+ ///
+ /// The principal.
+ /// if the token is bound to a DPoP key, otherwise.
+ internal static bool IsDPoPBoundToken(ClaimsPrincipal? principal)
+ => principal?.GetClaim(Claims.Confirmation) is { Length: > 0 } value &&
+ JsonNode.Parse(value) is JsonObject node && node.ContainsKey(Claims.JsonWebKeyThumbprint);
+
+ ///
+ /// Creates a new DPoP nonce signed using the signing credentials of the server.
+ ///
+ /// The transaction.
+ /// The nonce.
+ internal static async ValueTask 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(StringComparer.Ordinal)
+ {
+ [Claims.ExpiresAt] = (date + transaction.Options.DPoPNonceLifetime).ToUnixTimeSeconds(),
+ [Claims.IssuedAt] = date.ToUnixTimeSeconds()
+ },
+ SigningCredentials = signing,
+ TokenType = JsonWebTokenTypes.Private.DPoPNonce
+ });
+ }
+
+ ///
+ /// Determines whether the specified DPoP nonce was issued by the server and is not expired.
+ ///
+ /// The transaction.
+ /// The nonce.
+ /// if the nonce is valid, otherwise.
+ internal static async ValueTask 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();
+ }
}
diff --git a/src/OpenIddict.Server/OpenIddictServerOptions.cs b/src/OpenIddict.Server/OpenIddictServerOptions.cs
index 0b8cad93..c0475606 100644
--- a/src/OpenIddict.Server/OpenIddictServerOptions.cs
+++ b/src/OpenIddict.Server/OpenIddictServerOptions.cs
@@ -605,6 +605,56 @@ public sealed class OpenIddictServerOptions
///
public bool EnableRequestObjectSupport { get; set; }
+ ///
+ /// 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.
+ ///
+ public bool EnableDPoPSupport { get; set; }
+
+ ///
+ /// Gets or sets a boolean indicating whether all token requests must include a valid DPoP proof.
+ ///
+ ///
+ /// Note: this option requires enabling DPoP support using .
+ ///
+ public bool RequireDPoP { get; set; }
+
+ ///
+ /// Gets or sets a boolean indicating whether DPoP proofs must include a server-provided nonce.
+ ///
+ ///
+ /// Note: this option requires enabling DPoP support using .
+ ///
+ public bool RequireDPoPNonces { get; set; }
+
+ ///
+ /// Gets or sets the maximum difference allowed between the issuance date of a DPoP proof and the current date.
+ ///
+ public TimeSpan DPoPProofLifetime { get; set; } = TimeSpan.FromMinutes(5);
+
+ ///
+ /// Gets or sets the lifetime of the DPoP nonces issued when is enabled.
+ ///
+ public TimeSpan DPoPNonceLifetime { get; set; } = TimeSpan.FromMinutes(5);
+
+ ///
+ /// Gets the asymmetric signing algorithms allowed for DPoP proofs.
+ ///
+ [EditorBrowsable(EditorBrowsableState.Advanced)]
+ public HashSet DPoPSigningAlgorithms { get; } = new(StringComparer.Ordinal)
+ {
+ SecurityAlgorithms.EcdsaSha256,
+ SecurityAlgorithms.EcdsaSha384,
+ SecurityAlgorithms.EcdsaSha512,
+ SecurityAlgorithms.RsaSha256,
+ SecurityAlgorithms.RsaSha384,
+ SecurityAlgorithms.RsaSha512,
+ SecurityAlgorithms.RsaSsaPssSha256,
+ SecurityAlgorithms.RsaSsaPssSha384,
+ SecurityAlgorithms.RsaSsaPssSha512
+ };
+
///
/// 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
diff --git a/src/OpenIddict.Server/OpenIddictServerTransaction.cs b/src/OpenIddict.Server/OpenIddictServerTransaction.cs
index 43bd0ebf..ebf5feab 100644
--- a/src/OpenIddict.Server/OpenIddictServerTransaction.cs
+++ b/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
///
public X509Certificate2? RemoteCertificate { get; set; }
+ ///
+ /// Gets or sets the authentication scheme used to send the access token
+ /// in the Authorization header (e.g "Bearer" or "DPoP"), if applicable.
+ ///
+ public string? AccessTokenScheme { get; set; }
+
+ ///
+ /// Gets or sets the raw DPoP proof sent by the remote peer, if available.
+ ///
+ public string? DPoPProof { get; set; }
+
+ ///
+ /// Gets or sets the principal extracted from the validated DPoP proof, if available.
+ ///
+ ///
+ /// Note: the RFC 7638 thumbprint of the proof key is stored in the private "oi_dpop_jkt" claim.
+ ///
+ public ClaimsPrincipal? DPoPProofPrincipal { get; set; }
+
+ ///
+ /// Gets or sets the DPoP nonce returned to the remote peer using the "DPoP-Nonce" header, if applicable.
+ ///
+ public string? DPoPNonce { get; set; }
+
+ ///
+ /// Gets or sets the HTTP method of the current transaction, if available.
+ ///
+ public string? RequestMethod { get; set; }
+
///
/// Gets or sets the type of the endpoint processing the current transaction.
///
diff --git a/src/OpenIddict.Validation/OpenIddict.Validation.csproj b/src/OpenIddict.Validation/OpenIddict.Validation.csproj
index 6f475b77..f3da17d6 100644
--- a/src/OpenIddict.Validation/OpenIddict.Validation.csproj
+++ b/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
+
+
+
+
+
diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs
index 071bce07..457d1721 100644
--- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTestClient.cs
+++ b/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);
}
+ ///
+ /// Gets the additional headers attached to all the requests sent by this client.
+ ///
+ public Dictionary RequestHeaders { get; } = new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Gets the headers returned in the last response received by this client.
+ ///
+ public Dictionary ResponseHeaders { get; } = new(StringComparer.OrdinalIgnoreCase);
+
private HttpRequestMessage CreateRequestMessage(OpenIddictRequest request, HttpMethod method, Uri uri)
{
if (!uri.IsAbsoluteUri)
diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.DPoP.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.DPoP.cs
new file mode 100644
index 00000000..e4fde9a2
--- /dev/null
+++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.DPoP.cs
@@ -0,0 +1,1125 @@
+/*
+ * 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.Collections.Immutable;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.IdentityModel.JsonWebTokens;
+using Microsoft.IdentityModel.Tokens;
+using Moq;
+using Xunit;
+using static OpenIddict.Server.OpenIddictServerEvents;
+using static OpenIddict.Server.OpenIddictServerHandlers;
+using static OpenIddict.Server.OpenIddictServerHandlers.Protection;
+
+namespace OpenIddict.Server.IntegrationTests;
+
+public abstract partial class OpenIddictServerIntegrationTests
+{
+ private const string DPoPTokenEndpoint = "http://localhost/connect/token";
+ private const string DPoPUserInfoEndpoint = "http://localhost/connect/userinfo";
+
+ private static readonly ECDsa DPoPAlgorithm = ECDsa.Create(ECCurve.NamedCurves.nistP256);
+
+ [Fact]
+ public async Task HandleConfigurationRequest_DPoPSigningAlgorithmsAreReturnedWhenDPoPIsEnabled()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.GetAsync("/.well-known/openid-configuration");
+
+ // Assert
+ var algorithms = (ImmutableArray?) response[Metadata.DPoPSigningAlgValuesSupported];
+ Assert.NotNull(algorithms);
+ Assert.Contains(SecurityAlgorithms.EcdsaSha256, algorithms.Value, StringComparer.Ordinal);
+ Assert.Contains(SecurityAlgorithms.RsaSsaPssSha256, algorithms.Value, StringComparer.Ordinal);
+ Assert.DoesNotContain(SecurityAlgorithms.HmacSha256, algorithms.Value, StringComparer.Ordinal);
+ }
+
+ [Fact]
+ public async Task HandleConfigurationRequest_DPoPSigningAlgorithmsAreNotReturnedWhenDPoPIsDisabled()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options => options.EnableDegradedMode());
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.GetAsync("/.well-known/openid-configuration");
+
+ // Assert
+ Assert.Null(response[Metadata.DPoPSigningAlgValuesSupported]);
+ }
+
+ [Fact]
+ public async Task ProcessSignIn_DPoPBoundAccessTokenIsReturnedWhenValidProofIsSent()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureDPoPPasswordServer(options);
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.NotNull(context.AccessTokenPrincipal);
+ Assert.Equal(ComputeDPoPThumbprint(), GetConfirmationThumbprint(context.AccessTokenPrincipal));
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(PrepareAccessTokenPrincipal.Descriptor.Order + 1);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.NotNull(response.AccessToken);
+ Assert.Equal(TokenTypes.DPoP, response.TokenType);
+ }
+
+ [Fact]
+ public async Task ProcessSignIn_BearerAccessTokenIsReturnedWhenNoProofIsSent()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPPasswordServer);
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.NotNull(response.AccessToken);
+ Assert.Equal(TokenTypes.Bearer, response.TokenType);
+ }
+
+ [Fact]
+ public async Task ProcessSignIn_DPoPProofIsIgnoredWhenDPoPSupportIsDisabled()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+
+ options.AddEventHandler(builder =>
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetClaim(Claims.Subject, "Bob le Magnifique");
+
+ return ValueTask.CompletedTask;
+ }));
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = ["invalid_proof"];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(TokenTypes.Bearer, response.TokenType);
+ }
+
+ [Fact]
+ public async Task ProcessSignIn_DPoPBoundRefreshTokenIsReturnedInDegradedMode()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureDPoPPasswordServer(options);
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.NotNull(context.RefreshTokenPrincipal);
+ Assert.Equal(ComputeDPoPThumbprint(), GetConfirmationThumbprint(context.RefreshTokenPrincipal));
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(PrepareRefreshTokenPrincipal.Descriptor.Order + 1);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+
+ // Act
+ var request = CreateDPoPPasswordRequest();
+ request.ClientId = "Fabrikam";
+
+ var response = await client.PostAsync("/connect/token", request);
+
+ // Assert
+ Assert.NotNull(response.RefreshToken);
+ }
+
+ [Theory]
+ [InlineData(ClientTypes.Public, true)]
+ [InlineData(ClientTypes.Confidential, false)]
+ public async Task ProcessSignIn_RefreshTokenIsOnlyBoundForPublicClients(string type, bool bound)
+ {
+ // Arrange
+ var application = new OpenIddictApplication();
+
+ var manager = CreateApplicationManager(mock =>
+ {
+ mock.Setup(manager => manager.FindByClientIdAsync("Fabrikam", It.IsAny()))
+ .ReturnsAsync(application);
+
+ mock.Setup(manager => manager.HasClientTypeAsync(application, ClientTypes.Public, It.IsAny()))
+ .ReturnsAsync(type is ClientTypes.Public);
+
+ mock.Setup(manager => manager.HasClientTypeAsync(application, ClientTypes.Confidential, It.IsAny()))
+ .ReturnsAsync(type is ClientTypes.Confidential);
+
+ mock.Setup(manager => manager.ValidateClientSecretAsync(application, "7Fjfp0ZBr1KtDRbnfVdmIw", It.IsAny()))
+ .ReturnsAsync(true);
+
+ mock.Setup(manager => manager.GetSettingsAsync(application, It.IsAny()))
+ .ReturnsAsync(ImmutableDictionary.Create(StringComparer.Ordinal));
+ });
+
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDPoPSupport();
+ options.DisableTokenStorage();
+ options.DisableAuthorizationStorage();
+ options.Services.AddSingleton(manager);
+
+ // Note: the device authorization flow requires token storage.
+ options.Configure(options =>
+ {
+ options.GrantTypes.Remove(GrantTypes.DeviceCode);
+ options.DeviceAuthorizationEndpointUris.Clear();
+ options.EndUserVerificationEndpointUris.Clear();
+ });
+
+ options.AddEventHandler(builder =>
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetScopes(Scopes.OfflineAccess)
+ .SetClaim(Claims.Subject, "Bob le Magnifique");
+
+ return ValueTask.CompletedTask;
+ }));
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.NotNull(context.RefreshTokenPrincipal);
+ Assert.Equal(bound ? ComputeDPoPThumbprint() : null, GetConfirmationThumbprint(context.RefreshTokenPrincipal));
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(PrepareRefreshTokenPrincipal.Descriptor.Order + 1);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+
+ // Act
+ var request = CreateDPoPPasswordRequest();
+ request.ClientId = "Fabrikam";
+ request.ClientSecret = type is ClientTypes.Confidential ? "7Fjfp0ZBr1KtDRbnfVdmIw" : null;
+
+ var response = await client.PostAsync("/connect/token", request);
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.NotNull(response.RefreshToken);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_MissingProofIsRejectedWhenDPoPIsGloballyRequired()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureDPoPPasswordServer(options);
+ options.RequireDPoP();
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2228), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2228), response.ErrorUri);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_MissingProofIsRejectedWhenDPoPIsRequiredForClient()
+ {
+ // Arrange
+ var application = new OpenIddictApplication();
+
+ var manager = CreateApplicationManager(mock =>
+ {
+ mock.Setup(manager => manager.FindByClientIdAsync("Fabrikam", It.IsAny()))
+ .ReturnsAsync(application);
+
+ mock.Setup(manager => manager.HasClientTypeAsync(application, ClientTypes.Public, It.IsAny()))
+ .ReturnsAsync(true);
+
+ mock.Setup(manager => manager.HasRequirementAsync(application, Requirements.Features.DPoP, It.IsAny()))
+ .ReturnsAsync(true);
+ });
+
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDPoPSupport();
+ options.Services.AddSingleton(manager);
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var request = CreateDPoPPasswordRequest();
+ request.ClientId = "Fabrikam";
+
+ var response = await client.PostAsync("/connect/token", request);
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2228), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2228), response.ErrorUri);
+
+ Mock.Get(manager).Verify(manager => manager.HasRequirementAsync(application, Requirements.Features.DPoP, It.IsAny()), Times.Once());
+ }
+
+ [Theory]
+ [InlineData("method")]
+ [InlineData("uri")]
+ [InlineData("uri_with_different_path")]
+ [InlineData("expired")]
+ [InlineData("future")]
+ [InlineData("jti")]
+ public async Task ValidateTokenRequest_ProofWithInvalidClaimIsRejected(string scenario)
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPPasswordServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["DPoP"] = [scenario switch
+ {
+ "method" => CreateDPoPProof(method: "GET"),
+ "uri" => CreateDPoPProof(uri: "https://localhost/connect/token"),
+ "uri_with_different_path" => CreateDPoPProof(uri: "http://localhost/connect/token2"),
+ "expired" => CreateDPoPProof(issuedAt: DateTimeOffset.UtcNow - TimeSpan.FromHours(1)),
+ "future" => CreateDPoPProof(issuedAt: DateTimeOffset.UtcNow + TimeSpan.FromHours(1)),
+ "jti" => CreateDPoPProof(jti: string.Empty),
+
+ _ => throw new NotSupportedException()
+ }];
+
+ var claim = scenario switch
+ {
+ "method" => Claims.HttpMethod,
+ "uri" or "uri_with_different_path" => Claims.HttpUri,
+ "expired" or "future" => Claims.IssuedAt,
+ _ => Claims.JwtId
+ };
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.FormatID2226(claim), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2226), response.ErrorUri);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_ProofWithQueryStringInUriIsAccepted()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPPasswordServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: "HTTP://LOCALHOST:80/connect/token?query=value#fragment")];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.Equal(TokenTypes.DPoP, response.TokenType);
+ }
+
+ [Theory]
+ [InlineData("type")]
+ [InlineData("private_key")]
+ [InlineData("symmetric")]
+ [InlineData("none")]
+ [InlineData("signature")]
+ [InlineData("malformed")]
+ public async Task ValidateTokenRequest_InvalidProofIsRejected(string scenario)
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPPasswordServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["DPoP"] = [scenario switch
+ {
+ "type" => CreateDPoPProof(type: JsonWebTokenTypes.GenericJsonWebToken),
+ "private_key" => CreateDPoPProof(includePrivateKey: true),
+ "symmetric" => CreateSymmetricDPoPProof(),
+ "none" => CreateUnsignedDPoPProof(),
+ "signature" => CreateDPoPProof(jwk: CreateJsonWebKey(ECDsa.Create(ECCurve.NamedCurves.nistP256))),
+ "malformed" => "malformed_proof",
+
+ _ => throw new NotSupportedException()
+ }];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2225), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2225), response.ErrorUri);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_MultipleProofsAreRejected()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPPasswordServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(), CreateDPoPProof()];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2234), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2234), response.ErrorUri);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_ReplayedProofIsRejected()
+ {
+ // Arrange
+ var token = new OpenIddictToken();
+
+ var manager = CreateTokenManager(mock =>
+ {
+ mock.Setup(manager => manager.FindByReferenceIdAsync(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(token);
+ });
+
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDPoPSupport();
+ options.Services.AddSingleton(manager);
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(jti: "replayed_identifier")];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2227), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2227), response.ErrorUri);
+
+ Mock.Get(manager).Verify(manager => manager.FindByReferenceIdAsync(
+ ComputeDPoPThumbprint() + ".replayed_identifier", It.IsAny()), Times.Once());
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_TokenEntryIsCreatedForNewProofWhenTokenStorageIsEnabled()
+ {
+ // Arrange
+ var manager = CreateTokenManager(mock =>
+ {
+ mock.Setup(manager => manager.FindByReferenceIdAsync(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(value: null);
+
+ mock.Setup(manager => manager.CreateAsync(It.IsAny(), It.IsAny()))
+ .ReturnsAsync(new OpenIddictToken());
+ });
+
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDPoPSupport();
+ options.Services.AddSingleton(manager);
+
+ options.AddEventHandler(builder =>
+ builder.UseInlineHandler(context =>
+ {
+ context.Reject(error: "custom_error");
+
+ return ValueTask.CompletedTask;
+ }));
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(jti: "new_identifier")];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal("custom_error", response.Error);
+
+ Mock.Get(manager).Verify(manager => manager.CreateAsync(
+ It.Is(descriptor =>
+ descriptor.ReferenceId == ComputeDPoPThumbprint() + ".new_identifier" &&
+ descriptor.Status == Statuses.Redeemed &&
+ descriptor.Type == TokenTypeIdentifiers.Private.DPoPProof &&
+ descriptor.ExpirationDate != null),
+ It.IsAny()), Times.Once());
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_NonceIsRequiredAndAcceptedWhenNoncesAreEnabled()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ ConfigureDPoPPasswordServer(options);
+ options.RequireDPoPNonces();
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+
+ // Act
+ var response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.UseDPoPNonce, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2229), response.ErrorDescription);
+ Assert.True(client.ResponseHeaders.TryGetValue("DPoP-Nonce", out var nonces));
+
+ var nonce = Assert.Single(nonces);
+
+ // Act
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(nonce: nonce)];
+ response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.Equal(TokenTypes.DPoP, response.TokenType);
+
+ // Act
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(nonce: "invalid_nonce")];
+ response = await client.PostAsync("/connect/token", CreateDPoPPasswordRequest());
+
+ // Assert
+ Assert.Equal(Errors.UseDPoPNonce, response.Error);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_RefreshTokenBoundToDPoPKeyRequiresMatchingProof()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.Equal("8xLOxBtZp8", context.Token);
+
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetTokenType(TokenTypeIdentifiers.RefreshToken)
+ .SetClaim(Claims.Subject, "Bob le Magnifique")
+ .SetClaim(Claims.Confirmation, new JsonObject { [Claims.JsonWebKeyThumbprint] = ComputeDPoPThumbprint() });
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/token", new OpenIddictRequest
+ {
+ GrantType = GrantTypes.RefreshToken,
+ RefreshToken = "8xLOxBtZp8"
+ });
+
+ // Assert
+ Assert.Equal(Errors.InvalidGrant, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2230), response.ErrorDescription);
+
+ using var algorithm = ECDsa.Create(ECCurve.NamedCurves.nistP256);
+
+ // Act
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(jwk: CreateJsonWebKey(algorithm), signingKey: new ECDsaSecurityKey(algorithm))];
+ response = await client.PostAsync("/connect/token", new OpenIddictRequest
+ {
+ GrantType = GrantTypes.RefreshToken,
+ RefreshToken = "8xLOxBtZp8"
+ });
+
+ // Assert
+ Assert.Equal(Errors.InvalidGrant, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2231), response.ErrorDescription);
+
+ // Act
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+ response = await client.PostAsync("/connect/token", new OpenIddictRequest
+ {
+ GrantType = GrantTypes.RefreshToken,
+ RefreshToken = "8xLOxBtZp8"
+ });
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.Equal(TokenTypes.DPoP, response.TokenType);
+ }
+
+ [Fact]
+ public async Task ValidateTokenRequest_AuthorizationCodeBoundToDPoPKeyRequiresMatchingProof()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetTokenType(TokenTypeIdentifiers.Private.AuthorizationCode)
+ .SetPresenters("Fabrikam")
+ .SetClaim(Claims.Subject, "Bob le Bricoleur")
+ .SetClaim(Claims.Private.DPoPJwkThumbprint, ComputeDPoPThumbprint());
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ var request = new OpenIddictRequest
+ {
+ ClientId = "Fabrikam",
+ Code = "SplxlOBeZQQYbYS6WxSbIA",
+ GrantType = GrantTypes.AuthorizationCode
+ };
+
+ // Act
+ var response = await client.PostAsync("/connect/token", request);
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.FormatID2233(Parameters.DPoPJkt), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2233), response.ErrorUri);
+
+ // Act
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof()];
+ response = await client.PostAsync("/connect/token", request);
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.Equal(TokenTypes.DPoP, response.TokenType);
+ }
+
+ [Fact]
+ public async Task ProcessSignIn_DPoPJktParameterIsAttachedToAuthorizationCode()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetClaim(Claims.Subject, "Bob le Magnifique");
+
+ return ValueTask.CompletedTask;
+ }));
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.NotNull(context.AuthorizationCodePrincipal);
+ Assert.Equal("jkt_value", context.AuthorizationCodePrincipal.GetClaim(Claims.Private.DPoPJwkThumbprint));
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(PrepareAuthorizationCodePrincipal.Descriptor.Order + 1);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/authorize", new OpenIddictRequest
+ {
+ ClientId = "Fabrikam",
+ DPoPJkt = "jkt_value",
+ Nonce = "n-0S6_WzA2Mj",
+ RedirectUri = "http://www.fabrikam.com/path",
+ ResponseType = ResponseTypes.Code,
+ Scope = Scopes.OpenId
+ });
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.NotNull(response.Code);
+ }
+
+ [Fact]
+ public async Task ValidatePushedAuthorizationRequest_ProofThumbprintIsAttachedAsDPoPJkt()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.Equal(ComputeDPoPThumbprint(), context.Request.DPoPJkt);
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(PrepareRequestTokenPrincipal.Descriptor.Order - 1);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: "http://localhost/connect/par")];
+
+ // Act
+ var response = await client.PostAsync("/connect/par", new OpenIddictRequest
+ {
+ ClientId = "Fabrikam",
+ Nonce = "n-0S6_WzA2Mj",
+ RedirectUri = "http://www.fabrikam.com/path",
+ ResponseType = ResponseTypes.Code,
+ Scope = Scopes.OpenId
+ });
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.NotNull(response.RequestUri);
+ }
+
+ [Fact]
+ public async Task ValidatePushedAuthorizationRequest_MismatchingDPoPJktIsRejected()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+ });
+
+ await using var client = await server.CreateClientAsync();
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: "http://localhost/connect/par")];
+
+ // Act
+ var response = await client.PostAsync("/connect/par", new OpenIddictRequest
+ {
+ ClientId = "Fabrikam",
+ DPoPJkt = "invalid_thumbprint",
+ RedirectUri = "http://www.fabrikam.com/path",
+ ResponseType = ResponseTypes.Code
+ });
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.FormatID2233(Parameters.DPoPJkt), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2233), response.ErrorUri);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_DPoPBoundAccessTokenIsAcceptedWithValidProof()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPUserInfoServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["Authorization"] = ["DPoP SlAV32hkKG"];
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: DPoPUserInfoEndpoint, accessToken: "SlAV32hkKG")];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Null(response.Error);
+ Assert.Equal("Bob le Magnifique", (string?) response[Claims.Subject]);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_DPoPBoundAccessTokenIsRejectedWhenSentAsBearerToken()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPUserInfoServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["Authorization"] = ["Bearer SlAV32hkKG"];
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: DPoPUserInfoEndpoint, accessToken: "SlAV32hkKG")];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidToken, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2230), response.ErrorDescription);
+ Assert.Equal(SR.FormatID8000(SR.ID2230), response.ErrorUri);
+ Assert.StartsWith(Schemes.Bearer, Assert.Single(client.ResponseHeaders["WWW-Authenticate"]), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_ProofWithInvalidAccessTokenHashIsRejected()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPUserInfoServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["Authorization"] = ["DPoP SlAV32hkKG"];
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: DPoPUserInfoEndpoint, accessToken: "another_token")];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.FormatID2226(Claims.DPoPAccessTokenHash), response.ErrorDescription);
+
+ var header = Assert.Single(client.ResponseHeaders["WWW-Authenticate"]);
+ Assert.StartsWith(Schemes.DPoP + " ", header, StringComparison.Ordinal);
+ Assert.Contains("algs=\"", header, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_MissingProofIsRejectedWhenDPoPSchemeIsUsed()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPUserInfoServer);
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["Authorization"] = ["DPoP SlAV32hkKG"];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidDPoPProof, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2228), response.ErrorDescription);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_ProofSignedWithDifferentKeyIsRejected()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(ConfigureDPoPUserInfoServer);
+ await using var client = await server.CreateClientAsync();
+
+ using var algorithm = ECDsa.Create(ECCurve.NamedCurves.nistP256);
+
+ client.RequestHeaders["Authorization"] = ["DPoP SlAV32hkKG"];
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: DPoPUserInfoEndpoint, accessToken: "SlAV32hkKG",
+ jwk: CreateJsonWebKey(algorithm), signingKey: new ECDsaSecurityKey(algorithm))];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidToken, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2231), response.ErrorDescription);
+ }
+
+ [Fact]
+ public async Task HandleUserInfoRequest_UnboundAccessTokenIsRejectedWhenDPoPSchemeIsUsed()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetTokenType(TokenTypeIdentifiers.AccessToken)
+ .SetClaim(Claims.Subject, "Bob le Magnifique");
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
+ });
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ client.RequestHeaders["Authorization"] = ["DPoP SlAV32hkKG"];
+ client.RequestHeaders["DPoP"] = [CreateDPoPProof(uri: DPoPUserInfoEndpoint, accessToken: "SlAV32hkKG")];
+
+ // Act
+ var response = await client.PostAsync("/connect/userinfo", new OpenIddictRequest());
+
+ // Assert
+ Assert.Equal(Errors.InvalidToken, response.Error);
+ Assert.Equal(SR.GetResourceString(SR.ID2232), response.ErrorDescription);
+ }
+
+ [Fact]
+ public async Task HandleIntrospectionRequest_DPoPTokenTypeIsReturnedForDPoPBoundToken()
+ {
+ // Arrange
+ await using var server = await CreateServerAsync(options =>
+ {
+ options.EnableDegradedMode();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetTokenType(TokenTypeIdentifiers.AccessToken)
+ .SetClaim(Claims.Subject, "Bob le Magnifique")
+ .SetClaim(Claims.Confirmation, new JsonObject { [Claims.JsonWebKeyThumbprint] = "jkt_value" });
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
+ });
+
+ options.RemoveEventHandler(ValidateExpirationDate.Descriptor);
+ });
+
+ await using var client = await server.CreateClientAsync();
+
+ // Act
+ var response = await client.PostAsync("/connect/introspect", new OpenIddictRequest
+ {
+ Token = "2YotnFZFEjr1zCsicMWpAA",
+ TokenTypeHint = TokenTypeHints.AccessToken
+ });
+
+ // Assert
+ Assert.True((bool) response[Claims.Active]);
+ Assert.Equal(TokenTypes.DPoP, (string?) response[Claims.TokenType]);
+ Assert.Equal("jkt_value", (string?) response[Claims.Confirmation]?[Claims.JsonWebKeyThumbprint]);
+ }
+
+ private static void ConfigureDPoPPasswordServer(OpenIddictServerBuilder options)
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ builder.UseInlineHandler(context =>
+ {
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetScopes(Scopes.OfflineAccess)
+ .SetClaim(Claims.Subject, "Bob le Magnifique");
+
+ return ValueTask.CompletedTask;
+ }));
+ }
+
+ private static void ConfigureDPoPUserInfoServer(OpenIddictServerBuilder options)
+ {
+ options.EnableDegradedMode();
+ options.EnableDPoPSupport();
+
+ options.AddEventHandler(builder =>
+ {
+ builder.UseInlineHandler(context =>
+ {
+ Assert.Equal("SlAV32hkKG", context.Token);
+
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
+ .SetTokenType(TokenTypeIdentifiers.AccessToken)
+ .SetClaim(Claims.Subject, "Bob le Magnifique")
+ .SetClaim(Claims.Confirmation, new JsonObject { [Claims.JsonWebKeyThumbprint] = ComputeDPoPThumbprint() });
+
+ return ValueTask.CompletedTask;
+ });
+
+ builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
+ });
+ }
+
+ private static OpenIddictRequest CreateDPoPPasswordRequest() => new()
+ {
+ GrantType = GrantTypes.Password,
+ Username = "johndoe",
+ Password = "A3ddj3w",
+ Scope = Scopes.OfflineAccess
+ };
+
+ private static string? GetConfirmationThumbprint(ClaimsPrincipal principal)
+ => principal.GetClaim(Claims.Confirmation) is { Length: > 0 } value
+ ? (string?) JsonNode.Parse(value)?[Claims.JsonWebKeyThumbprint]
+ : null;
+
+ private static Dictionary CreateJsonWebKey(ECDsa algorithm, bool includePrivateKey = false)
+ {
+ var parameters = algorithm.ExportParameters(includePrivateParameters: includePrivateKey);
+
+ var key = new Dictionary(StringComparer.Ordinal)
+ {
+ [JsonWebKeyParameterNames.Crv] = JsonWebKeyECTypes.P256,
+ [JsonWebKeyParameterNames.Kty] = JsonWebAlgorithmsKeyTypes.EllipticCurve,
+ [JsonWebKeyParameterNames.X] = Base64UrlEncoder.Encode(parameters.Q.X),
+ [JsonWebKeyParameterNames.Y] = Base64UrlEncoder.Encode(parameters.Q.Y)
+ };
+
+ if (includePrivateKey)
+ {
+ key[JsonWebKeyParameterNames.D] = Base64UrlEncoder.Encode(parameters.D);
+ }
+
+ return key;
+ }
+
+ private static string ComputeDPoPThumbprint()
+ => Base64UrlEncoder.Encode(new JsonWebKey(JsonSerializer.Serialize(CreateJsonWebKey(DPoPAlgorithm))).ComputeJwkThumbprint());
+
+ private static string CreateDPoPProof(
+ string method = "POST",
+ string uri = DPoPTokenEndpoint,
+ string type = JsonWebTokenTypes.DPoPProof,
+ string? algorithm = SecurityAlgorithms.EcdsaSha256,
+ DateTimeOffset? issuedAt = null,
+ string? accessToken = null,
+ string? nonce = null,
+ string? jti = null,
+ bool includePrivateKey = false,
+ Dictionary? jwk = null,
+ SecurityKey? signingKey = null)
+ {
+ var claims = new Dictionary(StringComparer.Ordinal)
+ {
+ [Claims.HttpMethod] = method,
+ [Claims.HttpUri] = uri,
+ [Claims.IssuedAt] = (issuedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(),
+ [Claims.JwtId] = jti ?? Guid.NewGuid().ToString()
+ };
+
+ if (!string.IsNullOrEmpty(accessToken))
+ {
+ claims[Claims.DPoPAccessTokenHash] = Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(accessToken)));
+ }
+
+ if (!string.IsNullOrEmpty(nonce))
+ {
+ claims[Claims.Nonce] = nonce;
+ }
+
+ return new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = false }.CreateToken(new SecurityTokenDescriptor
+ {
+ AdditionalHeaderClaims = new Dictionary(StringComparer.Ordinal)
+ {
+ [JwtHeaderParameterNames.Jwk] = jwk ?? CreateJsonWebKey(DPoPAlgorithm, includePrivateKey)
+ },
+ Claims = claims,
+ SigningCredentials = new SigningCredentials(signingKey ?? new ECDsaSecurityKey(DPoPAlgorithm), algorithm ?? SecurityAlgorithms.EcdsaSha256),
+ TokenType = type
+ });
+ }
+
+ private static string CreateSymmetricDPoPProof()
+ {
+ var bytes = RandomNumberGenerator.GetBytes(32);
+
+ return new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = false }.CreateToken(new SecurityTokenDescriptor
+ {
+ AdditionalHeaderClaims = new Dictionary(StringComparer.Ordinal)
+ {
+ [JwtHeaderParameterNames.Jwk] = new Dictionary(StringComparer.Ordinal)
+ {
+ [JsonWebKeyParameterNames.Kty] = JsonWebAlgorithmsKeyTypes.Octet,
+ [JsonWebKeyParameterNames.K] = Base64UrlEncoder.Encode(bytes)
+ }
+ },
+ Claims = new Dictionary(StringComparer.Ordinal)
+ {
+ [Claims.HttpMethod] = "POST",
+ [Claims.HttpUri] = DPoPTokenEndpoint,
+ [Claims.IssuedAt] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
+ [Claims.JwtId] = Guid.NewGuid().ToString()
+ },
+ SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(bytes), SecurityAlgorithms.HmacSha256),
+ TokenType = JsonWebTokenTypes.DPoPProof
+ });
+ }
+
+ private static string CreateUnsignedDPoPProof()
+ {
+ var header = new JsonObject
+ {
+ [JwtHeaderParameterNames.Alg] = "none",
+ [JwtHeaderParameterNames.Typ] = JsonWebTokenTypes.DPoPProof,
+ [JwtHeaderParameterNames.Jwk] = JsonSerializer.SerializeToNode(CreateJsonWebKey(DPoPAlgorithm))
+ };
+
+ var payload = new JsonObject
+ {
+ [Claims.HttpMethod] = "POST",
+ [Claims.HttpUri] = DPoPTokenEndpoint,
+ [Claims.IssuedAt] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
+ [Claims.JwtId] = Guid.NewGuid().ToString()
+ };
+
+ return Base64UrlEncoder.Encode(header.ToJsonString()) + "." + Base64UrlEncoder.Encode(payload.ToJsonString()) + ".";
+ }
+}
diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs
index 2883bffa..e724b18c 100644
--- a/test/OpenIddict.Server.Tests/OpenIddictServerBuilderTests.cs
+++ b/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()
{
diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs
index b3f780e1..d38b7a1b 100644
--- a/test/OpenIddict.Server.Tests/OpenIddictServerConfigurationTests.cs
+++ b/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()
{