Skip to content
This repository has been archived by the owner on Feb 23, 2025. It is now read-only.

Commit

Permalink
Merge pull request #409 from IdentityModel/joe/wilson
Browse files Browse the repository at this point in the history
Update Wilson and IdentityModel dependencies
  • Loading branch information
brockallen authored Feb 27, 2024
2 parents 9b017ae + c6c180a commit 9b48585
Show file tree
Hide file tree
Showing 17 changed files with 106 additions and 45 deletions.
7 changes: 5 additions & 2 deletions src/DPoP/DPoP.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
<!-- Recommended: Embed symbols containing Source Link in the main file (exe/dll) -->
<DebugType>embedded</DebugType>

<!-- Enable Trimming Warnings to allow consumers to publish as trimmed -->
<IsTrimmable Condition="'$(TargetFramework)' == 'net6.0'">true</IsTrimmable>

<ContinuousIntegrationBuild Condition="'$(GITHUB_ACTIONS)' == 'true'">True</ContinuousIntegrationBuild>

<AssemblyOriginatorKeyFile>../../key.snk</AssemblyOriginatorKeyFile>
Expand All @@ -40,9 +43,9 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="IdentityModel" Version="7.0.0-preview.3" />
<PackageReference Include="minver" Version="4.3.0" PrivateAssets="All" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.30.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.1" />

<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
Expand Down
1 change: 0 additions & 1 deletion src/DPoP/DPoPProof.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


namespace IdentityModel.OidcClient.DPoP;

/// <summary>
Expand Down
28 changes: 28 additions & 0 deletions src/DPoP/DPoPProofPayload.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using System.Text.Json.Serialization;

namespace IdentityModel.OidcClient.DPoP;

/// <summary>
/// Internal class to aid serialization of DPoP proof token payloads. Giving
/// each claim a property allows us to add this type to the source generated
/// serialization
/// </summary>
internal class DPoPProofPayload
{
[JsonPropertyName(JwtClaimTypes.JwtId)]
public string JwtId { get; set; } = default!;
[JsonPropertyName(JwtClaimTypes.DPoPHttpMethod)]
public string DPoPHttpMethod { get; set; } = default!;
[JsonPropertyName(JwtClaimTypes.DPoPHttpUrl)]
public string DPoPHttpUrl { get; set; } = default!;
[JsonPropertyName(JwtClaimTypes.IssuedAt)]
public long IssuedAt { get; set; }
[JsonPropertyName(JwtClaimTypes. DPoPAccessTokenHash)]
public string? DPoPAccessTokenHash { get; set; }
[JsonPropertyName(JwtClaimTypes. Nonce)]
public string? Nonce { get; set; }
}
36 changes: 18 additions & 18 deletions src/DPoP/DPoPProofTokenFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,24 @@ public DPoPProof CreateProofToken(DPoPProofRequest request)

// jwk: representing the public key chosen by the client, in JSON Web Key (JWK) [RFC7517] format,
// as defined in Section 4.1.3 of [RFC7515]. MUST NOT contain a private key.
object jwk;
Dictionary<string, object> jwk;
if (string.Equals(jsonWebKey.Kty, JsonWebAlgorithmsKeyTypes.EllipticCurve))
{
jwk = new
jwk = new Dictionary<string, object>
{
kty = jsonWebKey.Kty,
x = jsonWebKey.X,
y = jsonWebKey.Y,
crv = jsonWebKey.Crv
{ "kty", jsonWebKey.Kty },
{ "x", jsonWebKey.X },
{ "y", jsonWebKey.Y },
{ "crv", jsonWebKey.Crv }
};
}
else if (string.Equals(jsonWebKey.Kty, JsonWebAlgorithmsKeyTypes.RSA))
{
jwk = new
jwk = new Dictionary<string, object>
{
kty = jsonWebKey.Kty,
e = jsonWebKey.E,
n = jsonWebKey.N
{ "kty", jsonWebKey.Kty },
{ "e", jsonWebKey.E },
{ "n", jsonWebKey.N }
};
}
else
Expand All @@ -71,12 +71,12 @@ public DPoPProof CreateProofToken(DPoPProofRequest request)
{ JwtClaimTypes.JsonWebKey, jwk },
};

var payload = new Dictionary<string, object>
var payload = new DPoPProofPayload
{
{ JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId() },
{ JwtClaimTypes.DPoPHttpMethod, request.Method },
{ JwtClaimTypes.DPoPHttpUrl, request.Url },
{ JwtClaimTypes.IssuedAt, DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
JwtId = CryptoRandom.CreateUniqueId(),
DPoPHttpMethod = request.Method,
DPoPHttpUrl = request.Url,
IssuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
};

if (!string.IsNullOrWhiteSpace(request.AccessToken))
Expand All @@ -87,17 +87,17 @@ public DPoPProof CreateProofToken(DPoPProofRequest request)
var hash = sha256.ComputeHash(Encoding.ASCII.GetBytes(request.AccessToken));
var ath = Base64Url.Encode(hash);

payload.Add(JwtClaimTypes.DPoPAccessTokenHash, ath);
payload.DPoPAccessTokenHash = ath;
}

if (!string.IsNullOrEmpty(request.DPoPNonce))
{
payload.Add(JwtClaimTypes.Nonce, request.DPoPNonce!);
payload.Nonce = request.DPoPNonce!;
}

var handler = new JsonWebTokenHandler() { SetDefaultTimesOnTokenCreation = false };
var key = new SigningCredentials(jsonWebKey, jsonWebKey.Alg);
var proofToken = handler.CreateToken(JsonSerializer.Serialize(payload), key, header);
var proofToken = handler.CreateToken(JsonSerializer.Serialize(payload, SourceGenerationContext.Default.DPoPProofPayload), key, header);

return new DPoPProof { ProofToken = proofToken! };
}
Expand Down
4 changes: 2 additions & 2 deletions src/DPoP/JsonWebKeys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static JsonWebKey CreateRsa(string algorithm = OidcConstants.Algorithms.A
/// </summary>
public static string CreateRsaJson(string algorithm = OidcConstants.Algorithms.Asymmetric.PS256)
{
return JsonSerializer.Serialize(CreateRsa(algorithm));
return JsonSerializer.Serialize(CreateRsa(algorithm), SourceGenerationContext.Default.JsonWebKey);
}

/// <summary>
Expand All @@ -53,7 +53,7 @@ public static JsonWebKey CreateECDsa(string algorithm = OidcConstants.Algorithms
/// </summary>
public static string CreateECDsaJson(string algorithm = OidcConstants.Algorithms.Asymmetric.ES256)
{
return JsonSerializer.Serialize(CreateECDsa(algorithm));
return JsonSerializer.Serialize(CreateECDsa(algorithm), SourceGenerationContext.Default.JsonWebKey);
}

internal static string GetCurveNameFromSigningAlgorithm(string alg)
Expand Down
16 changes: 16 additions & 0 deletions src/DPoP/SourceGenerationContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Text.Json.Serialization;
using Microsoft.IdentityModel.Tokens;

namespace IdentityModel.OidcClient.DPoP
{
[JsonSourceGenerationOptions(
WriteIndented = false,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
GenerationMode = JsonSourceGenerationMode.Metadata,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(JsonWebKey))]
[JsonSerializable(typeof(DPoPProofPayload))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
}
5 changes: 4 additions & 1 deletion src/IdentityTokenValidator/IdentityTokenValidator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
<!-- Recommended: Embed symbols containing Source Link in the main file (exe/dll) -->
<DebugType>embedded</DebugType>

<!-- Enable Trimming Warnings to allow consumers to publish as trimmed -->
<IsTrimmable Condition="'$(TargetFramework)' == 'net6.0'">true</IsTrimmable>

<ContinuousIntegrationBuild Condition="'$(GITHUB_ACTIONS)' == 'true'">True</ContinuousIntegrationBuild>

<AssemblyOriginatorKeyFile>../../key.snk</AssemblyOriginatorKeyFile>
Expand All @@ -38,7 +41,7 @@
<ItemGroup>
<PackageReference Include="minver" Version="4.3.0" PrivateAssets="All" />

<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.30.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public async Task<IdentityTokenValidationResult> ValidateAsync(string identityTo
};
}

var result = ValidateSignature(identityToken, handler, parameters, options, logger);
var result = await ValidateSignatureAsync(identityToken, handler, parameters, options, logger);
if (result.IsValid == false)
{
if (result.Exception is SecurityTokenSignatureKeyNotFoundException)
Expand Down Expand Up @@ -123,7 +123,7 @@ public async Task<IdentityTokenValidationResult> ValidateAsync(string identityTo
};
}

private TokenValidationResult ValidateSignature(string identityToken, JsonWebTokenHandler handler, TokenValidationParameters parameters, OidcClientOptions options, ILogger logger)
private async Task<TokenValidationResult> ValidateSignatureAsync(string identityToken, JsonWebTokenHandler handler, TokenValidationParameters parameters, OidcClientOptions options, ILogger logger)
{
if (parameters.RequireSignedTokens)
{
Expand Down Expand Up @@ -174,7 +174,7 @@ private TokenValidationResult ValidateSignature(string identityToken, JsonWebTok
parameters.IssuerSigningKeys = keys;
}

return handler.ValidateToken(identityToken, parameters);
return await handler.ValidateTokenAsync(identityToken, parameters);
}

private static string CheckRequiredClaim(ClaimsPrincipal user)
Expand Down
2 changes: 1 addition & 1 deletion src/OidcClient/OidcClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="IdentityModel" Version="7.0.0-preview.3" />
<PackageReference Include="minver" Version="4.3.0" PrivateAssets="All" />

<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
Expand Down
8 changes: 4 additions & 4 deletions test/DPoPTests/DPoPTests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>net8.0</TargetFrameworks>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -17,9 +17,9 @@

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="6.0.0" />
<PackageReference Include="Duende.IdentityServer" Version="6.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.2" />
<PackageReference Include="Duende.IdentityServer" Version="7.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.2" />

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
Expand Down
3 changes: 2 additions & 1 deletion test/DPoPTests/Framework/DPoP/DPoPJwtBearerEvents.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using IdentityModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using System.Text;
Expand Down Expand Up @@ -130,7 +131,7 @@ public override Task Challenge(JwtBearerChallengeContext context)
}
}

context.Response.Headers.Add(HeaderNames.WWWAuthenticate, sb.ToString());
context.Response.Headers.Append(HeaderNames.WWWAuthenticate, sb.ToString());


if (context.HttpContext.Items.ContainsKey("DPoP-Nonce"))
Expand Down
12 changes: 6 additions & 6 deletions test/DPoPTests/Framework/DPoP/DPoPProofValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ protected virtual Task ValidateHeaderAsync(DPoPProofValidatonContext context, DP
return Task.CompletedTask;
}

if (!token.TryGetHeaderValue<IDictionary<string, object>>(JwtClaimTypes.JsonWebKey, out var jwkValues))
if (!token.TryGetHeaderValue<JsonElement>(JwtClaimTypes.JsonWebKey, out var jwkValues))
{
result.IsError = true;
result.ErrorDescription = "Invalid 'jwk' value.";
Expand Down Expand Up @@ -169,7 +169,7 @@ protected virtual Task ValidateHeaderAsync(DPoPProofValidatonContext context, DP
/// <summary>
/// Validates the signature.
/// </summary>
protected virtual Task ValidateSignatureAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result)
protected virtual async Task ValidateSignatureAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result)
{
TokenValidationResult tokenValidationResult;

Expand All @@ -185,27 +185,27 @@ protected virtual Task ValidateSignatureAsync(DPoPProofValidatonContext context,
};

var handler = new JsonWebTokenHandler();
tokenValidationResult = handler.ValidateToken(context.ProofToken, tvp);
tokenValidationResult = await handler.ValidateTokenAsync(context.ProofToken, tvp);
}
catch (Exception ex)
{
Logger.LogDebug("Error parsing DPoP token: {error}", ex.Message);
result.IsError = true;
result.ErrorDescription = "Invalid signature on DPoP token.";
return Task.CompletedTask;
return;
}

if (tokenValidationResult.Exception != null)
{
Logger.LogDebug("Error parsing DPoP token: {error}", tokenValidationResult.Exception.Message);
result.IsError = true;
result.ErrorDescription = "Invalid signature on DPoP token.";
return Task.CompletedTask;
return;
}

result.Payload = tokenValidationResult.Claims;

return Task.CompletedTask;
return;
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion test/JwtValidationTests/Infrastructure/Crypto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static IdentityModel.Jwk.JsonWebKeySet CreateKeySet(RsaSecurityKey key)
public static string CreateJwt(RsaSecurityKey key, string issuer, string audience, params Claim[] claims)
{
var jwtClaims = new List<Claim>(claims);
jwtClaims.Add(new Claim(JwtClaimTypes.IssuedAt, "now"));
jwtClaims.Add(new Claim(JwtClaimTypes.IssuedAt, DateTime.UtcNow.Ticks.ToString(), ClaimValueTypes.Integer64));

SigningCredentials credentials = null;
if (key != null)
Expand Down
5 changes: 3 additions & 2 deletions test/JwtValidationTests/Infrastructure/NetworkHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -86,11 +87,11 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
{
if (_selector != null)
{
response.Content = new StringContent(_selector(request));
response.Content = new StringContent(_selector(request), Encoding.UTF8, "application/json");
}
else
{
response.Content = new StringContent(_document);
response.Content = new StringContent(_document, Encoding.UTF8, "application/json");
}
}

Expand Down
5 changes: 3 additions & 2 deletions test/OidcClient.Tests/Infrastructure/NetworkHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -86,11 +87,11 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
{
if (_selector != null)
{
response.Content = new StringContent(_selector(request));
response.Content = new StringContent(_selector(request), Encoding.UTF8, "application/json");
}
else
{
response.Content = new StringContent(_document);
response.Content = new StringContent(_document, Encoding.UTF8, "application/json");
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/OidcClient.Tests/OidcClient.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.12.0"/>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.1"/>

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4"/>
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
Expand Down
9 changes: 9 additions & 0 deletions test/TrimmableAnalysis/TrimmableAnalysis.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@
<ItemGroup>
<TrimmerRootAssembly Include="IdentityModel.OidcClient" />
<ProjectReference Include="..\..\src\OidcClient\OidcClient.csproj" />

<TrimmerRootAssembly Include="IdentityModel.OidcClient.IdentityTokenValidator" />
<ProjectReference Include="..\..\src\IdentityTokenValidator\IdentityTokenValidator.csproj" />


<TrimmerRootAssembly Include="IdentityModel.OidcClient.DPoP" />
<ProjectReference Include="..\..\src\DPoP\DPoP.csproj" />


</ItemGroup>

</Project>

0 comments on commit 9b48585

Please sign in to comment.