Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,12 @@ public class DPoPProofTokenValidationParameters
SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.RsaSha384,
SecurityAlgorithms.RsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.EcdsaSha256,
SecurityAlgorithms.EcdsaSha384,
SecurityAlgorithms.EcdsaSha512
SecurityAlgorithms.EcdsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.RsaSsaPssSha384,
SecurityAlgorithms.RsaSsaPssSha512
};

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace Fhi.Auth.IntegrationTests
Expand Down Expand Up @@ -282,6 +283,91 @@ public async Task GIVEN_accessing_DPoPprotected_endpoint_WHEN_invalid_dpop_jwk_a
response.AssertWWWAuthenticate("error=\"invalid_dpop_proof\", error_description=\"Disallowed algorithm\"");
}

// Ensure this matches actual list
private static readonly string[] RsaAndPssAlgorithms =
{
SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.RsaSha384,
SecurityAlgorithms.RsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.RsaSsaPssSha384,
SecurityAlgorithms.RsaSsaPssSha512
};

Comment on lines +286 to +296
/// <summary>
/// Tests that default RSA algorithms works as aspected
/// </summary>
Comment on lines +297 to +299
/// <returns></returns>
[TestCaseSource(nameof(RsaAndPssAlgorithms))]
public async Task GIVEN_accessing_DPoPprotected_endpoint_WHEN_using_default_rsa_algorithms_THEN_returns_200(string algorithm)
{
FakeDPoPTokenBuilder.UseKey(FakeDPoPTokenBuilder.FakeDPoPKeys.CreateRsa());

var client = new DPoPTestServerBuilder()
.AddServiceConfiguration(services => services.AddAuthentication().AddJwtDpop(configure: options => options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "http://authority",
ValidAudience = "api_audience",
IssuerSigningKey = FakeDPoPTokenBuilder.SecurityKey,
}))
.AppPipeline(app => app.MapGet("/api/dpopEndpoint", [Authorize(AuthenticationSchemes = "DPoP")] () => "OK"))
.Start();

var token = FakeDPoPTokenBuilder.CreateDPoPToken("http://authority", "api_audience", alg: algorithm);
var proof = FakeDPoPTokenBuilder.CreateDPoPProof("http://localhost/api/dpopEndpoint", "GET", token, alg: algorithm);

client.AddDPoPAuthorizationHeader(token).AddDPoPHeader(proof);

var response = await client.GetAsync("/api/dpopEndpoint");

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}

// Ensure this matches actual list
private static readonly string[] EcAlgorithms =
{
SecurityAlgorithms.EcdsaSha256,
SecurityAlgorithms.EcdsaSha384,
SecurityAlgorithms.EcdsaSha512
};

/// <summary>
/// Tests that default EC algorithms works as aspected
/// </summary>
Comment on lines +334 to +336
/// <returns></returns>
[TestCaseSource(nameof(EcAlgorithms))]
public async Task GIVEN_accessing_DPoPprotected_endpoint_WHEN_using_default_ec_algorithms_THEN_returns_200(string algorithm)
{
// 1. Select key first
if (algorithm == SecurityAlgorithms.EcdsaSha256)
FakeDPoPTokenBuilder.UseKey(FakeDPoPTokenBuilder.FakeDPoPKeys.CreateEc(ECCurve.NamedCurves.nistP256, "EC"));
else if (algorithm == SecurityAlgorithms.EcdsaSha384)
FakeDPoPTokenBuilder.UseKey(FakeDPoPTokenBuilder.FakeDPoPKeys.CreateEc(ECCurve.NamedCurves.nistP384, "EC"));
else if (algorithm == SecurityAlgorithms.EcdsaSha512)
FakeDPoPTokenBuilder.UseKey(FakeDPoPTokenBuilder.FakeDPoPKeys.CreateEc(ECCurve.NamedCurves.nistP521, "EC"));

// 2. Now build server with the chosen key
var client = new DPoPTestServerBuilder()
.AddServiceConfiguration(services => services.AddAuthentication().AddJwtDpop(configure: options => options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "http://authority",
ValidAudience = "api_audience",
IssuerSigningKey = FakeDPoPTokenBuilder.SecurityKey,
}))
.AppPipeline(app => app.MapGet("/api/dpopEndpoint", [Authorize(AuthenticationSchemes = "DPoP")] () => "OK"))
.Start();

// 3. Use matching alg for token + proof
var token = FakeDPoPTokenBuilder.CreateDPoPToken("http://authority", "api_audience", alg: algorithm);
var proof = FakeDPoPTokenBuilder.CreateDPoPProof("http://localhost/api/dpopEndpoint", "GET", token, alg: algorithm);

client.AddDPoPAuthorizationHeader(token).AddDPoPHeader(proof);

var response = await client.GetAsync("/api/dpopEndpoint");

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}

/// <summary>
/// 6. The JWT signature verifies with the public key contained in the jwk JOSE Header Parameter
/// </summary>
Expand All @@ -308,7 +394,6 @@ public async Task GIVEN_accessing_DPoPprotected_endpoint_WHEN_DPoPProof_invalid_
response.AssertWWWAuthenticate("DPoP error=\"invalid_dpop_proof\", error_description=\"Invalid DPoP proof signature.\"");
}


/// <summary>
/// 7. The jwk JOSE Header Parameter does not contain a private key
/// </summary>
Expand Down
156 changes: 121 additions & 35 deletions tests/Fhi.Authentication.JwtDPoP.Tests/Setup/FakeDPoPTokenBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,97 @@ namespace Fhi.Authentication.JwtDPoP.Tests.Setup
{
public static class FakeDPoPTokenBuilder
{
private static readonly RsaSecurityKey _rsaKey;
private static readonly Dictionary<string, string> _publicKeyParams;
private static readonly string _jwkThumbprint;
public class FakeDpopKeyPair
{
public SecurityKey? PrivateKey { get; init; }
public IDictionary<string, string>? PublicJwk { get; init; }
public string? JwkThumbprint { get; init; }
}

public static RsaSecurityKey SecurityKey => _rsaKey;
public static string JwkThumbprint => _jwkThumbprint;
public static SecurityKey SecurityKey => _keyPair.PrivateKey!;

static FakeDPoPTokenBuilder()
{
var rsa = RSA.Create(2048);
_rsaKey = new RsaSecurityKey(rsa);
public static string JwkThumbprint => _keyPair.JwkThumbprint!;

var parameters = rsa.ExportParameters(false);
_publicKeyParams = new Dictionary<string, string>
public static class FakeDPoPKeys
{
public static FakeDpopKeyPair CreateRsa()
{
["kid"] = "kid",
["kty"] = "RSA",
["n"] = Base64UrlEncoder.Encode(parameters.Modulus!),
["e"] = Base64UrlEncoder.Encode(parameters.Exponent!),
};

var jwk = new JsonWebKey
var rsa = RSA.Create(2048);
var key = new RsaSecurityKey(rsa);

var p = rsa.ExportParameters(false);

var jwk = new Dictionary<string, string>
{
["kty"] = "RSA",
["kid"] = "kid",
["n"] = Base64UrlEncoder.Encode(p.Modulus!),
["e"] = Base64UrlEncoder.Encode(p.Exponent!)
};

var thumb = new JsonWebKey
{
Kty = "RSA",
Kid = "kid",
N = jwk["n"],
E = jwk["e"]
}.ComputeJwkThumbprint();

return new FakeDpopKeyPair
{
PrivateKey = key,
PublicJwk = jwk,
JwkThumbprint = Base64UrlEncoder.Encode(thumb)
};
}

public static FakeDpopKeyPair CreateEc(ECCurve curve, string kty)
{
Kid = "kid",
Kty = "RSA",
N = _publicKeyParams["n"],
E = _publicKeyParams["e"],
};
_jwkThumbprint = Base64UrlEncoder.Encode(jwk.ComputeJwkThumbprint());
var ec = ECDsa.Create(curve);
var key = new ECDsaSecurityKey(ec);

var p = ec.ExportParameters(false);

string crv = curve.Oid.FriendlyName switch
{
"nistP256" => "P-256",
"nistP384" => "P-384",
"nistP521" => "P-521",
_ => throw new NotSupportedException($"Unsupported curve: {curve.Oid.FriendlyName}")
};

var jwk = new Dictionary<string, string>
{
["kty"] = kty,
["kid"] = "kid",
["crv"] = crv,
["x"] = Base64UrlEncoder.Encode(p.Q.X!),
["y"] = Base64UrlEncoder.Encode(p.Q.Y!)
};

var thumb = new JsonWebKey
{
Kty = kty,
Kid = "kid",
Crv = crv,
X = jwk["x"],
Y = jwk["y"]
}.ComputeJwkThumbprint();

return new FakeDpopKeyPair
{
PrivateKey = key,
PublicJwk = jwk,
JwkThumbprint = Base64UrlEncoder.Encode(thumb)
};
}
}

private static FakeDpopKeyPair _keyPair = FakeDPoPKeys.CreateRsa();

public static void UseKey(FakeDpopKeyPair pair)
{
_keyPair = pair;
}

public static string CreateDPoPToken(
Expand All @@ -59,7 +121,7 @@ public static string CreateDPoPToken(
string jkt,
string alg = SecurityAlgorithms.RsaSha256)
{
var signingCredentials = new SigningCredentials(_rsaKey, alg);
var signingCredentials = new SigningCredentials(_keyPair.PrivateKey, alg);

var tokenDescriptor = new SecurityTokenDescriptor
{
Expand Down Expand Up @@ -108,12 +170,12 @@ public static string CreateDPoPProof(
SigningCredentials? signingCredentials = null,
string alg = SecurityAlgorithms.RsaSha256)
{
signingCredentials ??= new SigningCredentials(_rsaKey, alg);
signingCredentials ??= new SigningCredentials(_keyPair.PrivateKey, alg);

var header = new JwtHeader(signingCredentials)
{
["typ"] = typ,
["jwk"] = jwk ?? _publicKeyParams,
["jwk"] = jwk ?? _keyPair.PublicJwk
};

var payload = new JwtPayload();
Expand Down Expand Up @@ -141,17 +203,41 @@ public static string CreateDPoPProof(
/// </summary>
public static string CreateDPoPProofWithPrivateKey(string url, string httpMethod, string accessToken)
{
var privateParams = _rsaKey.Rsa.ExportParameters(true);
var jwkWithPrivateKey = new Dictionary<string, string>
if (_keyPair.PrivateKey is not RsaSecurityKey rsaKey)
throw new InvalidOperationException("Current key is not RSA");

var p = rsaKey.Rsa.ExportParameters(true);

var jwkWithPrivate = new Dictionary<string, string>
{
["kty"] = "RSA",
["n"] = Base64UrlEncoder.Encode(privateParams.Modulus!),
["e"] = Base64UrlEncoder.Encode(privateParams.Exponent!),
["d"] = Base64UrlEncoder.Encode(privateParams.D!),
["p"] = Base64UrlEncoder.Encode(privateParams.P!),
["q"] = Base64UrlEncoder.Encode(privateParams.Q!),
["n"] = Base64UrlEncoder.Encode(p.Modulus!),
["e"] = Base64UrlEncoder.Encode(p.Exponent!),
["d"] = Base64UrlEncoder.Encode(p.D!),
["p"] = Base64UrlEncoder.Encode(p.P!),
["q"] = Base64UrlEncoder.Encode(p.Q!)
};
return CreateDPoPProof(url, httpMethod, accessToken, jwk: jwkWithPrivateKey);

return CreateDPoPProof(url, httpMethod, accessToken, jwk: jwkWithPrivate);
}

public static string CreateDPoPProofWithPrivateEcKey(string url, string httpMethod, string accessToken)
{
if (_keyPair.PrivateKey is not ECDsaSecurityKey ecKey)
throw new InvalidOperationException("Current key is not EC");

var p = ecKey.ECDsa.ExportParameters(true);

var jwkWithPrivate = new Dictionary<string, string>
{
["kty"] = "EC",
["crv"] = ecKey.ECDsa.ExportParameters(false).Curve.Oid.FriendlyName!,
["x"] = Base64UrlEncoder.Encode(p.Q.X!),
["y"] = Base64UrlEncoder.Encode(p.Q.Y!),
["d"] = Base64UrlEncoder.Encode(p.D!)
};
Comment on lines +229 to +238

return CreateDPoPProof(url, httpMethod, accessToken, jwk: jwkWithPrivate);
}

/// <summary>
Expand Down