Skip to content
Merged
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
37 changes: 37 additions & 0 deletions NetDevPack.Identity.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,64 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Pack", "Pack", "{7985C809-6
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCore.Jwt.Sample", "src\Samples\AspNetCore.Jwt.Sample\AspNetCore.Jwt.Sample.csproj", "{B5BE907B-0C79-489F-99BD-2AD82FA727E3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetDevPack.Identity.Tests", "tests\NetDevPack.Identity.Tests\NetDevPack.Identity.Tests.csproj", "{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|x64.ActiveCfg = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|x64.Build.0 = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|x86.ActiveCfg = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Debug|x86.Build.0 = Debug|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|Any CPU.Build.0 = Release|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|x64.ActiveCfg = Release|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|x64.Build.0 = Release|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|x86.ActiveCfg = Release|Any CPU
{43A11876-765D-4387-BC28-4C9371DDD62D}.Release|x86.Build.0 = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|x64.ActiveCfg = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|x64.Build.0 = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|x86.ActiveCfg = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Debug|x86.Build.0 = Debug|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|Any CPU.Build.0 = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|x64.ActiveCfg = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|x64.Build.0 = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|x86.ActiveCfg = Release|Any CPU
{B5BE907B-0C79-489F-99BD-2AD82FA727E3}.Release|x86.Build.0 = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|x64.ActiveCfg = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|x64.Build.0 = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|x86.ActiveCfg = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Debug|x86.Build.0 = Debug|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|Any CPU.Build.0 = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|x64.ActiveCfg = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|x64.Build.0 = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|x86.ActiveCfg = Release|Any CPU
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{43A11876-765D-4387-BC28-4C9371DDD62D} = {7985C809-6CBD-44C2-BEA7-1AD828707F3E}
{B5BE907B-0C79-489F-99BD-2AD82FA727E3} = {8A673A3F-D855-4F9B-BA0B-0D2B5DE369EB}
{85BF6109-3FD5-4E5E-908E-4192A26EA8AB} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C92C10D5-BEA9-4EC0-BD95-6228657E412D}
Expand Down
9 changes: 9 additions & 0 deletions global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature"
},
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
62 changes: 45 additions & 17 deletions src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
private string _email;
private string _username;

private const string RefreshTokenJwtType = "rt+jwt";

private bool _useClaims;
private bool _useRoles;
private bool _useRt;
Expand Down Expand Up @@ -135,9 +137,7 @@

var handler = new JwtSecurityTokenHandler();

var issuer = _settings.Value.Issuer;
if (string.IsNullOrEmpty(issuer))
issuer = $"{_httpContext.HttpContext.Request.Scheme}://{_httpContext.HttpContext.Request.Host}";
var issuer = GetIssuer();

var securityToken = handler.CreateToken(new SecurityTokenDescriptor
{
Expand All @@ -147,7 +147,7 @@
Subject = identityClaims,
NotBefore = DateTime.UtcNow,
Expires = DateTime.UtcNow.AddDays(_settings.Value.RefreshTokenExpiration),
TokenType = "rt+jwt"
TokenType = RefreshTokenJwtType
});
await UpdateLastGeneratedClaim(jti, user);
var encodedJwt = handler.WriteToken(securityToken);
Expand Down Expand Up @@ -196,9 +196,7 @@
_identityClaims.AddClaims(_userClaims);
}

var issuer = _settings.Value.Issuer;
if (string.IsNullOrEmpty(issuer))
issuer = $"{_httpContext.HttpContext.Request.Scheme}://{_httpContext.HttpContext.Request.Host}";
var issuer = GetIssuer();

var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
Expand Down Expand Up @@ -235,10 +233,10 @@

private Task<SigningCredentials> GetCurrentKey()
{
if (string.IsNullOrEmpty(_settings.Value.SecretKey))

Check warning on line 236 in src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs

View workflow job for this annotation

GitHub Actions / build

'AppJwtSettings.SecretKey' is obsolete: 'For better security use IJwtBuilder and set null for this field'

Check warning on line 236 in src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs

View workflow job for this annotation

GitHub Actions / build

'AppJwtSettings.SecretKey' is obsolete: 'For better security use IJwtBuilder and set null for this field'
return _jwtService.GetCurrentSigningCredentials();

return Task.FromResult(new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.SecretKey)), SecurityAlgorithms.HmacSha256Signature));

Check warning on line 239 in src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs

View workflow job for this annotation

GitHub Actions / build

'AppJwtSettings.SecretKey' is obsolete: 'For better security use IJwtBuilder and set null for this field'

Check warning on line 239 in src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs

View workflow job for this annotation

GitHub Actions / build

'AppJwtSettings.SecretKey' is obsolete: 'For better security use IJwtBuilder and set null for this field'
}

public async Task<UserResponse> BuildUserResponse()
Expand All @@ -262,21 +260,29 @@

public async Task<RefreshTokenValidation> ValidateRefreshToken(string refreshToken)
{
if (string.IsNullOrWhiteSpace(refreshToken))
return new RefreshTokenValidation(false, reason: "Invalid refresh token");

var handler = new JsonWebTokenHandler();

var result = handler.ValidateToken(refreshToken, new TokenValidationParameters()
// RequireSignedTokens is true by default: unsigned ("alg": "none") tokens are rejected.
// ValidTypes makes sure an access token (at+jwt) can't be used as a refresh token.
var result = await handler.ValidateTokenAsync(refreshToken, new TokenValidationParameters
{
RequireSignedTokens = false,
ValidIssuer = _settings.Value.Issuer,
ValidIssuer = GetIssuer(),
ValidAudience = _settings.Value.Audience,
IssuerSigningKey = await _jwtService.GetCurrentSecurityKey(),
IssuerSigningKeys = await GetValidationKeys(),
ValidTypes = new[] { RefreshTokenJwtType },
});

if (!result.IsValid)
return new RefreshTokenValidation(false);
return new RefreshTokenValidation(false, reason: "Invalid refresh token");

var userId = result.ClaimsIdentity.GetUserId();
var user = string.IsNullOrEmpty(userId) ? null : await _userManager.FindByIdAsync(userId);
if (user is null)
return new RefreshTokenValidation(false, reason: "User not found");

var user = await _userManager.FindByIdAsync(result.ClaimsIdentity.GetUserId());
var claims = await _userManager.GetClaimsAsync(user);

var jti = result.ClaimsIdentity.GetJwtId();
Expand All @@ -285,11 +291,33 @@
if (!claims.Any(c => c.Type == "LastRefreshToken" && c.Value == jti))
return new RefreshTokenValidation(false, reason: "Refresh Token already used");

if (user.LockoutEnabled)
if (user.LockoutEnd < DateTime.Now)
return new RefreshTokenValidation(false, reason: "User blocked");
if (await _userManager.IsLockedOutAsync(user))
return new RefreshTokenValidation(false, reason: "User blocked");

return new RefreshTokenValidation(true, user.Id.ToString());
}

private string GetIssuer()
{
var issuer = _settings.Value.Issuer;
if (string.IsNullOrEmpty(issuer))
issuer = $"{_httpContext.HttpContext.Request.Scheme}://{_httpContext.HttpContext.Request.Host}";
return issuer;
}

/// <summary>
/// Keys that may have signed a refresh token: the configured symmetric key, or the last keys of the JWKS store
/// (so tokens signed before a key rotation are still accepted until they expire).
/// </summary>
private async Task<IEnumerable<SecurityKey>> GetValidationKeys()
{
#pragma warning disable CS0618 // SecretKey is obsolete but still supported
if (!string.IsNullOrEmpty(_settings.Value.SecretKey))
return new[] { new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_settings.Value.SecretKey)) };
#pragma warning restore CS0618

return new RefreshTokenValidation(true, result.ClaimsIdentity.GetUserId());
var keys = await _jwtService.GetLastKeys();
return keys.Select(k => (SecurityKey)k.GetSecurityKey()).ToList();
}

private static long ToUnixEpochDate(DateTime date)
Expand Down
20 changes: 15 additions & 5 deletions src/NetDevPack.Identity/NetDevPack.Identity.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,19 @@
</PropertyGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.23" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.23" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.34" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.34" />
<!-- Patched versions of vulnerable transitive packages (DataProtection / NetDevPack.Security.Jwt) -->
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="8.0.2" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="8.0.5" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.15" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.15" />
<!-- Patched versions of vulnerable transitive packages (DataProtection / NetDevPack.Security.Jwt) -->
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.15" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.15" />
</ItemGroup>

<Target Name="CopyHook" AfterTargets="AfterBuild" Condition="'$(Configuration)' == 'Debug'">
Expand All @@ -44,9 +50,13 @@
</None>
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="NetDevPack.Identity.Tests" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="NetDevPack.Security.Jwt.AspNetCore" Version="8.2.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.23.0" />
</ItemGroup>


Expand Down
12 changes: 6 additions & 6 deletions src/Samples/AspNetCore.Jwt.Sample/AspNetCore.Jwt.Sample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@
</PropertyGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.23" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.23" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.23">
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.34" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.34" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.34">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.2">
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
127 changes: 127 additions & 0 deletions tests/NetDevPack.Identity.Tests/JwksIntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
using AwesomeAssertions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using NetDevPack.Identity.Interfaces;
using NetDevPack.Identity.Jwt;
using Xunit;
using JwtRegisteredClaimNames = System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames;

namespace NetDevPack.Identity.Tests;

/// <summary>
/// The point of NetDevPack.Identity is to issue tokens that other services validate through JWKS:
/// they only need the public keys published at /jwks, never a shared secret.
/// </summary>
public class JwksIntegrationTests : IAsyncLifetime
{
private const string Issuer = "https://identity.netdevpack.test";
private const string Audience = "netdevpack-api";
private const string Email = "user@netdevpack.test";

private WebApplication _app = null!;
private HttpClient _http = null!;
private IdentityUser _user = null!;

public async ValueTask InitializeAsync()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
var databaseName = Guid.NewGuid().ToString();
builder.Services.AddIdentityEntityFrameworkContextConfiguration(o => o.UseInMemoryDatabase(databaseName));
builder.Services.AddIdentityConfiguration();
builder.Services.Configure<AppJwtSettings>(o =>
{
o.Issuer = Issuer;
o.Audience = Audience;
});
builder.Services.AddNetDevPackIdentity().PersistKeysInMemory();

_app = builder.Build();
_app.UseJwksDiscovery();
await _app.StartAsync();
_http = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) };

using var scope = _app.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
_user = new IdentityUser { UserName = "netdevpack", Email = Email };
(await users.CreateAsync(_user, "NetDevPack@2026!")).Succeeded.Should().BeTrue();
}

public async ValueTask DisposeAsync()
{
_http.Dispose();
await _app.DisposeAsync();
}

private async Task<JsonWebKeySet> GetPublishedJwks() =>
new(await _http.GetStringAsync("/jwks", TestContext.Current.CancellationToken));

[Fact]
public async Task JwksEndpoint_ShouldPublishOnlyPublicKeys()
{
// Issue a token first so the store has a key
using (var scope = _app.Services.CreateScope())
await scope.ServiceProvider.GetRequiredService<IJwtBuilder>().WithEmail(Email).WithJwtClaims().BuildToken();

var jwks = await GetPublishedJwks();

jwks.Keys.Should().NotBeEmpty();
jwks.Keys.Should().OnlyContain(k => k.D == null && k.P == null && k.Q == null && k.DP == null && k.DQ == null && k.QI == null && k.K == null,
"the JWKS document must never expose private or symmetric key material");
}

[Fact]
public async Task AccessToken_ShouldBeValidatedByThirdPartyUsingOnlyThePublishedJwks()
{
string accessToken;
using (var scope = _app.Services.CreateScope())
{
accessToken = (await scope.ServiceProvider.GetRequiredService<IJwtBuilder>()
.WithEmail(Email).WithJwtClaims().WithRefreshToken().BuildUserResponse()).AccessToken;
}

// A resource server only knows the issuer, the audience and the JWKS URL
var jwks = await GetPublishedJwks();
var result = await new JsonWebTokenHandler().ValidateTokenAsync(accessToken, new TokenValidationParameters
{
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKeys = jwks.GetSigningKeys(),
});

result.IsValid.Should().BeTrue(result.Exception?.Message);
result.ClaimsIdentity.FindFirst(JwtRegisteredClaimNames.Sub)!.Value.Should().Be(_user.Id);
((JsonWebToken)result.SecurityToken).Alg.Should().NotStartWith("HS", "tokens must be signed with the asymmetric JWKS key, not a shared secret");
}

[Fact]
public async Task RefreshToken_ShouldBeSignedWithTheJwksKeyAndStillWork()
{
string refreshToken;
using (var scope = _app.Services.CreateScope())
{
refreshToken = (await scope.ServiceProvider.GetRequiredService<IJwtBuilder>()
.WithEmail(Email).WithRefreshToken().BuildUserResponse()).RefreshToken;
}

var jwks = await GetPublishedJwks();
var signature = await new JsonWebTokenHandler().ValidateTokenAsync(refreshToken, new TokenValidationParameters
{
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKeys = jwks.GetSigningKeys(),
});
signature.IsValid.Should().BeTrue(signature.Exception?.Message);

using (var scope = _app.Services.CreateScope())
{
var validation = await scope.ServiceProvider.GetRequiredService<IJwtBuilder>().ValidateRefreshToken(refreshToken);
validation.IsValid.Should().BeTrue(validation.Reason);
}
}
}
Loading
Loading