From 770308b7ed42088a93a511392ab06af273fdf97e Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 13:20:37 -0300 Subject: [PATCH 1/6] feat!: target .NET 10 and update dependencies - Target net10.0 only (drop net8.0; remove dead net7.0 conditions) - NetDevPack.Security.Jwt.AspNetCore 8.2.2 -> 10.0.0, Microsoft.* 10.0.15, System.IdentityModel.Tokens.Jwt 8.23.0; pin patched System.Security.Cryptography.Xml/Pkcs 10.0.15 (high severity advisories) - Central Package Management, NuGet Audit as errors, global.json, .editorconfig, dependabot - Sample: Swashbuckle 7 -> 10.3.1 (Microsoft.OpenApi 2 security requirement API) - Add NetDevPack.Identity.Tests (xunit.v3 + AwesomeAssertions): access token claims and signature, user lookup by id/username/email, one-time refresh tokens - CI: actions/checkout v7, setup-dotnet v6; publish now restores, builds and tests before releasing; vulnerable package check; pack/push only on new release - Package metadata: repository/project URL pointed to EduardoPires/NetDevPack, duplicated Authors, README now packed; LangVersion follows the SDK BREAKING CHANGE: the package now targets .NET 10 only and depends on NetDevPack.Security.Jwt 10. Stay on 8.x for .NET 8. --- .editorconfig | 18 ++ .github/dependabot.yml | 23 +++ .github/workflows/publish-package.yml | 45 +++-- .github/workflows/pull-request.yml | 34 ++-- Directory.Build.props | 11 ++ Directory.Packages.props | 37 +++++ NetDevPack.Identity.sln | 37 +++++ README.md | 9 + global.json | 9 + .../NetDevPack.Identity.csproj | 43 ++--- .../AspNetCore.Jwt.Sample.csproj | 40 +---- .../Config/SwaggerConfig.cs | 16 +- .../JwtBuilderTests.cs | 154 ++++++++++++++++++ .../NetDevPack.Identity.Tests.csproj | 21 +++ 14 files changed, 393 insertions(+), 104 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/dependabot.yml create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 global.json create mode 100644 tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs create mode 100644 tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..808f9eb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = crlf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{cs,csproj,props,targets,sln}] +charset = utf-8-bom + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..aac1598 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,23 @@ +version: 2 +updates: + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 10 + commit-message: + prefix: chore + include: scope + groups: + tests: + patterns: ["xunit*", "AwesomeAssertions"] + ignore: + # Never reintroduce FluentAssertions (commercial license since v8) + - dependency-name: "FluentAssertions" + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: ci diff --git a/.github/workflows/publish-package.yml b/.github/workflows/publish-package.yml index c49961f..419c96f 100644 --- a/.github/workflows/publish-package.yml +++ b/.github/workflows/publish-package.yml @@ -7,41 +7,50 @@ on: env: CURRENT_REPO_URL: https://github.com/${{ github.repository }} +permissions: + contents: write + issues: write + pull-requests: write + jobs: - build: + publish: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v3 - - - name: Setup .NET 8 - uses: actions/setup-dotnet@v3 + uses: actions/checkout@v7 with: - dotnet-version: 8.0.x + fetch-depth: 0 - - name: Setup .NET 9 - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 9.0.x - - - name: Setup .NET 10 - uses: actions/setup-dotnet@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v6 with: - dotnet-version: 10.0.x + global-json-file: global.json + + - name: Restore dependencies + run: dotnet restore + + - name: Build + run: dotnet build --no-restore -c Release + + - name: Test + run: dotnet test --no-build -c Release - name: Semantic Release id: semantic uses: cycjimmy/semantic-release-action@v4 with: + semantic_version: 24 extra_plugins: | - @semantic-release/changelog - @semantic-release/git + @semantic-release/changelog@6 + @semantic-release/git@10 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Generate Package - run: dotnet pack -c Release -o out -p:PackageVersion=${{ steps.semantic.outputs.new_release_version }} -p:RepositoryUrl=${{env.CURRENT_REPO_URL}} + if: steps.semantic.outputs.new_release_published == 'true' + run: dotnet pack src/NetDevPack.Identity/NetDevPack.Identity.csproj -c Release -o out -p:Version=${{ steps.semantic.outputs.new_release_version }} -p:RepositoryUrl=${{ env.CURRENT_REPO_URL }} - name: Publish the package to nuget.org - run: dotnet nuget push ./out/*.nupkg --skip-duplicate -n -d -k ${{ secrets.NUGET_AUTH_TOKEN}} -s https://api.nuget.org/v3/index.json + if: steps.semantic.outputs.new_release_published == 'true' + run: dotnet nuget push ./out/*.nupkg --skip-duplicate -k ${{ secrets.NUGET_AUTH_TOKEN }} -s https://api.nuget.org/v3/index.json diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index c6d608c..b4af926 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -1,37 +1,37 @@ -name: Pull Request Analisys +name: NetDevPack - MASTER PR on: pull_request: branches: [ master ] +permissions: + contents: read + jobs: - build: + pull-request: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v3 - - - name: Setup .NET 8 - uses: actions/setup-dotnet@v3 + uses: actions/checkout@v7 with: - dotnet-version: 8.0.x + fetch-depth: 0 - - name: Setup .NET 9 - uses: actions/setup-dotnet@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v6 with: - dotnet-version: 9.0.x - - - name: Setup .NET 10 - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 10.0.x + global-json-file: global.json - name: Restore dependencies run: dotnet restore - name: Build - run: dotnet build --no-restore + run: dotnet build --no-restore -c Release - name: Test - run: dotnet test --no-build \ No newline at end of file + run: dotnet test --no-build -c Release + + - name: Check vulnerable packages + run: | + dotnet list package --vulnerable --include-transitive 2>&1 | tee vulnerable.txt + ! grep -q "has the following vulnerable packages" vulnerable.txt diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..a5c8809 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,11 @@ + + + + latest + + true + all + $(WarningsAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..81f960b --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,37 @@ + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NetDevPack.Identity.sln b/NetDevPack.Identity.sln index 1911d14..10967de 100644 --- a/NetDevPack.Identity.sln +++ b/NetDevPack.Identity.sln @@ -11,20 +11,56 @@ 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", "{791D0389-3723-4B9C-A49C-416B55FE51D5}" +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 + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|x64.ActiveCfg = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|x64.Build.0 = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|x86.ActiveCfg = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Debug|x86.Build.0 = Debug|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|Any CPU.Build.0 = Release|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|x64.ActiveCfg = Release|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|x64.Build.0 = Release|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|x86.ActiveCfg = Release|Any CPU + {791D0389-3723-4B9C-A49C-416B55FE51D5}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -32,6 +68,7 @@ Global GlobalSection(NestedProjects) = preSolution {43A11876-765D-4387-BC28-4C9371DDD62D} = {7985C809-6CBD-44C2-BEA7-1AD828707F3E} {B5BE907B-0C79-489F-99BD-2AD82FA727E3} = {8A673A3F-D855-4F9B-BA0B-0D2B5DE369EB} + {791D0389-3723-4B9C-A49C-416B55FE51D5} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C92C10D5-BEA9-4EC0-BD95-6228657E412D} diff --git a/README.md b/README.md index fe4302c..67c138e 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,15 @@ If you liked the project or if NetDevPack helped you, please give a star ;) dotnet add package NetDevPack.Identity ``` +### Compatibility + +| Version | Target frameworks | NetDevPack.Security.Jwt | +| ------- | ----------------- | ----------------------- | +| 9.x | .NET 10 (LTS) | 10.x | +| 8.x | .NET 8, .NET 10 | 8.x | + +> **Breaking change in v9:** .NET 8 is out of support since 2026-11-10 and is no longer targeted. If you need it, stay on 8.x. The public API did not change. + If you want to use our IdentityDbContext (ASP.NET Identity standard) you will need to create the Identity tables. Set your connection string in the `appsettings.json` and follow the next steps: Add the IdentityDbContext configuration in your `startup.cs`: diff --git a/global.json b/global.json new file mode 100644 index 0000000..1d364c6 --- /dev/null +++ b/global.json @@ -0,0 +1,9 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature" + }, + "test": { + "runner": "Microsoft.Testing.Platform" + } +} diff --git a/src/NetDevPack.Identity/NetDevPack.Identity.csproj b/src/NetDevPack.Identity/NetDevPack.Identity.csproj index 066135e..7aca60f 100644 --- a/src/NetDevPack.Identity/NetDevPack.Identity.csproj +++ b/src/NetDevPack.Identity/NetDevPack.Identity.csproj @@ -1,53 +1,46 @@  - net8.0;net10.0 - 10.0 + net10.0 NetDevPack.Identity NetDevPack.Identity false - Eduardo Pires + EduardoPires desenvolvedor.io .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities - https://github.com/EduardoPires/NetDevPack + https://github.com/NetDevPack/NetDevPack.Identity NetDevPack.Identity IconNuget.png - https://github.com/EduardoPires/NetDevPack - EduardoPires - Public + README.md + https://github.com/NetDevPack/NetDevPack.Identity + git + master MIT - 1.2.0 + 9.0.0 - - - - - - - - + + + + + - + <_CustomFiles Include="../../.github/hooks/commit-msg" /> - + - - True - - + + - - + - diff --git a/src/Samples/AspNetCore.Jwt.Sample/AspNetCore.Jwt.Sample.csproj b/src/Samples/AspNetCore.Jwt.Sample/AspNetCore.Jwt.Sample.csproj index 84cc339..9172e3f 100644 --- a/src/Samples/AspNetCore.Jwt.Sample/AspNetCore.Jwt.Sample.csproj +++ b/src/Samples/AspNetCore.Jwt.Sample/AspNetCore.Jwt.Sample.csproj @@ -1,45 +1,23 @@  - net8.0;net10.0 + net10.0 + false 71366747-6c85-459a-8d8e-f4a249169d76 Linux ..\..\.. - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - + + + diff --git a/src/Samples/AspNetCore.Jwt.Sample/Config/SwaggerConfig.cs b/src/Samples/AspNetCore.Jwt.Sample/Config/SwaggerConfig.cs index 49eadc0..7abf50a 100644 --- a/src/Samples/AspNetCore.Jwt.Sample/Config/SwaggerConfig.cs +++ b/src/Samples/AspNetCore.Jwt.Sample/Config/SwaggerConfig.cs @@ -3,7 +3,7 @@ using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; +using Microsoft.OpenApi; namespace AspNetCore.Jwt.Sample.Config { @@ -31,19 +31,9 @@ public static void AddSwaggerConfiguration(this IServiceCollection services) Type = SecuritySchemeType.ApiKey }); - c.AddSecurityRequirement(new OpenApiSecurityRequirement + c.AddSecurityRequirement(document => new OpenApiSecurityRequirement { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Bearer" - } - }, - new string[] {} - } + [new OpenApiSecuritySchemeReference("Bearer", document)] = [] }); }); } diff --git a/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs b/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs new file mode 100644 index 0000000..832e89e --- /dev/null +++ b/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs @@ -0,0 +1,154 @@ +using System.Security.Claims; +using AwesomeAssertions; +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 NetDevPack.Security.Jwt.Core.Interfaces; +using Xunit; +using JwtRegisteredClaimNames = System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames; + +namespace NetDevPack.Identity.Tests; + +public class JwtBuilderTests : IAsyncLifetime +{ + private const string Issuer = "https://identity.netdevpack.test"; + private const string Audience = "netdevpack-api"; + private const string Email = "user@netdevpack.test"; + + private ServiceProvider _provider = null!; + private IdentityUser _user = null!; + + public async ValueTask InitializeAsync() + { + var services = new ServiceCollection(); + services.AddLogging(); + var databaseName = Guid.NewGuid().ToString(); + services.AddIdentityEntityFrameworkContextConfiguration(o => o.UseInMemoryDatabase(databaseName)); + services.AddIdentityConfiguration(); + services.Configure(o => + { + o.Issuer = Issuer; + o.Audience = Audience; + o.RefreshTokenType = RefreshTokenType.OneTime; + }); + services.AddNetDevPackIdentity().PersistKeysInMemory(); + _provider = services.BuildServiceProvider(); + + using var scope = _provider.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var roles = scope.ServiceProvider.GetRequiredService>(); + + _user = new IdentityUser { UserName = "netdevpack", Email = Email }; + (await users.CreateAsync(_user, "NetDevPack@2026!")).Succeeded.Should().BeTrue(); + (await roles.CreateAsync(new IdentityRole("Admin"))).Succeeded.Should().BeTrue(); + (await users.AddToRoleAsync(_user, "Admin")).Succeeded.Should().BeTrue(); + (await users.AddClaimAsync(_user, new Claim("permission", "orders:read"))).Succeeded.Should().BeTrue(); + } + + public async ValueTask DisposeAsync() => await _provider.DisposeAsync(); + + private async Task ValidateAccessToken(string token) + { + using var scope = _provider.CreateScope(); + var key = await scope.ServiceProvider.GetRequiredService().GetCurrentSecurityKey(); + return await new JsonWebTokenHandler().ValidateTokenAsync(token, new TokenValidationParameters + { + ValidIssuer = Issuer, + ValidAudience = Audience, + IssuerSigningKey = key, + }); + } + + [Fact] + public async Task BuildUserResponse_ShouldIssueAccessTokenSignedWithCurrentJwksKey() + { + using var scope = _provider.CreateScope(); + var builder = scope.ServiceProvider.GetRequiredService(); + + var response = await builder.WithEmail(Email).WithJwtClaims().WithUserClaims().WithUserRoles().BuildUserResponse(); + + var result = await ValidateAccessToken(response.AccessToken); + result.IsValid.Should().BeTrue(result.Exception?.Message); + ((JsonWebToken)result.SecurityToken).Typ.Should().Be("at+jwt"); + result.ClaimsIdentity.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == _user.Id); + result.ClaimsIdentity.Claims.Should().Contain(c => c.Type == JwtRegisteredClaimNames.Email && c.Value == Email); + result.ClaimsIdentity.Claims.Should().Contain(c => c.Type == "role" && c.Value == "Admin"); + result.ClaimsIdentity.Claims.Should().Contain(c => c.Type == "permission" && c.Value == "orders:read"); + + ((string)response.UserToken.Id).Should().Be(_user.Id); + response.UserToken.Email.Should().Be(Email); + response.UserToken.Claims.Should().ContainSingle(c => c.Type == "permission" && c.Value == "orders:read"); + response.ExpiresIn.Should().Be(TimeSpan.FromHours(1).TotalSeconds); + } + + [Fact] + public async Task BuildToken_ShouldFindUserByIdUsernameOrEmail() + { + // IJwtBuilder is scoped and stateful: use one scope per token + async Task Build(Func select) + { + using var scope = _provider.CreateScope(); + return await select(scope.ServiceProvider.GetRequiredService()).WithJwtClaims().BuildToken(); + } + + var byId = await Build(b => b.WithUserId(_user.Id)); + var byName = await Build(b => b.WithUsername("netdevpack")); + var byEmail = await Build(b => b.WithEmail(Email)); + + foreach (var token in new[] { byId, byName, byEmail }) + { + var result = await ValidateAccessToken(token); + result.IsValid.Should().BeTrue(result.Exception?.Message); + result.ClaimsIdentity.FindFirst(JwtRegisteredClaimNames.Sub)!.Value.Should().Be(_user.Id); + } + } + + [Fact] + public async Task BuildToken_WithoutUserIdentifier_ShouldThrow() + { + using var scope = _provider.CreateScope(); + var builder = scope.ServiceProvider.GetRequiredService(); + + await builder.Invoking(b => b.WithJwtClaims().BuildToken()).Should().ThrowAsync(); + } + + [Fact] + public async Task RefreshToken_OneTime_ShouldOnlyAcceptTheLatestToken() + { + string first, second; + using (var scope = _provider.CreateScope()) + first = (await scope.ServiceProvider.GetRequiredService().WithEmail(Email).WithRefreshToken().BuildUserResponse()).RefreshToken; + + using (var scope = _provider.CreateScope()) + { + var validation = await scope.ServiceProvider.GetRequiredService().ValidateRefreshToken(first); + validation.IsValid.Should().BeTrue(); + validation.UserId.Should().Be(_user.Id); + } + + using (var scope = _provider.CreateScope()) + second = (await scope.ServiceProvider.GetRequiredService().WithEmail(Email).WithRefreshToken().BuildUserResponse()).RefreshToken; + + using (var scope = _provider.CreateScope()) + { + var builder = scope.ServiceProvider.GetRequiredService(); + var old = await builder.ValidateRefreshToken(first); + old.IsValid.Should().BeFalse(); + old.Reason.Should().Be("Refresh Token already used"); + (await builder.ValidateRefreshToken(second)).IsValid.Should().BeTrue(); + } + } + + [Fact] + public async Task ValidateRefreshToken_ShouldRejectGarbage() + { + using var scope = _provider.CreateScope(); + var builder = scope.ServiceProvider.GetRequiredService(); + + (await builder.ValidateRefreshToken("not-a-jwt")).IsValid.Should().BeFalse(); + } +} diff --git a/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj new file mode 100644 index 0000000..4e8b9f6 --- /dev/null +++ b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj @@ -0,0 +1,21 @@ + + + + net10.0 + Exe + false + true + enable + + + + + + + + + + + + + From b17dfcd0921eb78adee405003310d7a918d40096 Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 13:21:11 -0300 Subject: [PATCH 2/6] fix: point package URLs to Security.Identity --- .../NetDevPack.Identity.csproj | 92 +++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/src/NetDevPack.Identity/NetDevPack.Identity.csproj b/src/NetDevPack.Identity/NetDevPack.Identity.csproj index 7aca60f..438f661 100644 --- a/src/NetDevPack.Identity/NetDevPack.Identity.csproj +++ b/src/NetDevPack.Identity/NetDevPack.Identity.csproj @@ -1,46 +1,46 @@ - - - - net10.0 - NetDevPack.Identity - NetDevPack.Identity - false - EduardoPires - desenvolvedor.io - .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities - .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities - https://github.com/NetDevPack/NetDevPack.Identity - NetDevPack.Identity - IconNuget.png - README.md - https://github.com/NetDevPack/NetDevPack.Identity - git - master - MIT - 9.0.0 - - - - - - - - - - - - <_CustomFiles Include="../../.github/hooks/commit-msg" /> - - - - - - - - - - - - - - + + + + net10.0 + NetDevPack.Identity + NetDevPack.Identity + false + EduardoPires + desenvolvedor.io + .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities + .NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities + https://github.com/NetDevPack/Security.Identity + NetDevPack.Identity + IconNuget.png + README.md + https://github.com/NetDevPack/Security.Identity + git + master + MIT + 9.0.0 + + + + + + + + + + + + <_CustomFiles Include="../../.github/hooks/commit-msg" /> + + + + + + + + + + + + + + From 9dcba171de722893184d9ec2e2a44328355e78aa Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 13:25:29 -0300 Subject: [PATCH 3/6] ci: use conventionalcommits release preset --- .github/workflows/publish-package.yml | 1 + .releaserc | 31 ++++++++++++++++++--------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/.github/workflows/publish-package.yml b/.github/workflows/publish-package.yml index 419c96f..625dd75 100644 --- a/.github/workflows/publish-package.yml +++ b/.github/workflows/publish-package.yml @@ -44,6 +44,7 @@ jobs: extra_plugins: | @semantic-release/changelog@6 @semantic-release/git@10 + conventional-changelog-conventionalcommits@8 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.releaserc b/.releaserc index ce9cb40..2ffccd3 100644 --- a/.releaserc +++ b/.releaserc @@ -1,11 +1,22 @@ { - "branches": ["master"], - - "plugins": [ - "@semantic-release/commit-analyzer", - "@semantic-release/release-notes-generator", - "@semantic-release/changelog", - "@semantic-release/github", - "@semantic-release/git" - ] -} \ No newline at end of file + "branches": [ + "master" + ], + "plugins": [ + [ + "@semantic-release/commit-analyzer", + { + "preset": "conventionalcommits" + } + ], + [ + "@semantic-release/release-notes-generator", + { + "preset": "conventionalcommits" + } + ], + "@semantic-release/changelog", + "@semantic-release/github", + "@semantic-release/git" + ] +} From 5d7a676a9cea12e31b6d5fad69c8df33db0b6197 Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 18:23:38 -0300 Subject: [PATCH 4/6] fix: validate refresh token signature and type Same fix as #31 (8.x): signed rt+jwt tokens only, last JWKS keys or SecretKey, same issuer logic as creation, deleted users rejected, lockout check fixed (IsLockedOutAsync), async validation. Adds RefreshTokenSecurityTests. --- .../Jwt/JwtBuilderInject.cs | 62 +++++-- .../JwtBuilderTests.cs | 5 +- .../NetDevPack.Identity.Tests.csproj | 1 + .../RefreshTokenSecurityTests.cs | 174 ++++++++++++++++++ 4 files changed, 223 insertions(+), 19 deletions(-) create mode 100644 tests/NetDevPack.Identity.Tests/RefreshTokenSecurityTests.cs diff --git a/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs b/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs index 6b80d9b..1354188 100644 --- a/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs +++ b/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs @@ -39,6 +39,8 @@ internal class JwtBuilderInject : IJwtBuilder private string _email; private string _username; + private const string RefreshTokenJwtType = "rt+jwt"; + private bool _useClaims; private bool _useRoles; private bool _useRt; @@ -135,9 +137,7 @@ public async Task BuildRefreshToken() 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 { @@ -147,7 +147,7 @@ public async Task BuildRefreshToken() 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); @@ -196,9 +196,7 @@ public async Task BuildToken() _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 { @@ -262,21 +260,29 @@ public async Task BuildUserResponse() public async Task 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(); @@ -285,11 +291,33 @@ public async Task ValidateRefreshToken(string refreshTok 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; + } + + /// + /// 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). + /// + private async Task> 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) diff --git a/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs b/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs index 832e89e..3d9e4f9 100644 --- a/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs +++ b/tests/NetDevPack.Identity.Tests/JwtBuilderTests.cs @@ -54,12 +54,13 @@ public async ValueTask InitializeAsync() private async Task ValidateAccessToken(string token) { using var scope = _provider.CreateScope(); - var key = await scope.ServiceProvider.GetRequiredService().GetCurrentSecurityKey(); + // Validate like NetDevPack.Security.Jwt does: against the last keys of the store, not only the current one + var keys = await scope.ServiceProvider.GetRequiredService().GetLastKeys(); return await new JsonWebTokenHandler().ValidateTokenAsync(token, new TokenValidationParameters { ValidIssuer = Issuer, ValidAudience = Audience, - IssuerSigningKey = key, + IssuerSigningKeys = keys.Select(k => (SecurityKey)k.GetSecurityKey()).ToList(), }); } diff --git a/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj index 4e8b9f6..2e02fa2 100644 --- a/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj +++ b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj @@ -6,6 +6,7 @@ false true enable + enable diff --git a/tests/NetDevPack.Identity.Tests/RefreshTokenSecurityTests.cs b/tests/NetDevPack.Identity.Tests/RefreshTokenSecurityTests.cs new file mode 100644 index 0000000..2946f9a --- /dev/null +++ b/tests/NetDevPack.Identity.Tests/RefreshTokenSecurityTests.cs @@ -0,0 +1,174 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using AwesomeAssertions; +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 NetDevPack.Identity.Jwt.Model; +using Xunit; + +namespace NetDevPack.Identity.Tests; + +/// +/// Regression tests for refresh token validation: only signed rt+jwt tokens issued by this +/// application, for an existing and not locked out user, may be accepted. +/// +public class RefreshTokenSecurityTests : IAsyncLifetime +{ + private const string Issuer = "https://identity.netdevpack.test"; + private const string Audience = "netdevpack-api"; + private const string Email = "user@netdevpack.test"; + + private ServiceProvider _provider = null!; + private IdentityUser _user = null!; + + public async ValueTask InitializeAsync() + { + var services = new ServiceCollection(); + services.AddLogging(); + var databaseName = Guid.NewGuid().ToString(); + services.AddIdentityEntityFrameworkContextConfiguration(o => o.UseInMemoryDatabase(databaseName)); + services.AddIdentityConfiguration(); + services.Configure(o => + { + o.Issuer = Issuer; + o.Audience = Audience; + // ReUse skips the "last refresh token" check, so the token itself is the only protection + o.RefreshTokenType = RefreshTokenType.ReUse; + }); + services.AddNetDevPackIdentity().PersistKeysInMemory(); + _provider = services.BuildServiceProvider(); + + using var scope = _provider.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + _user = new IdentityUser { UserName = "netdevpack", Email = Email }; + (await users.CreateAsync(_user, "NetDevPack@2026!")).Succeeded.Should().BeTrue(); + } + + public async ValueTask DisposeAsync() => await _provider.DisposeAsync(); + + private async Task Validate(string token) + { + using var scope = _provider.CreateScope(); + return await scope.ServiceProvider.GetRequiredService().ValidateRefreshToken(token); + } + + private async Task IssueRefreshToken() + { + using var scope = _provider.CreateScope(); + var response = await scope.ServiceProvider.GetRequiredService() + .WithEmail(Email).WithRefreshToken().BuildUserResponse(); + return response.RefreshToken; + } + + private string ForgeToken(SigningCredentials? credentials, string type = "rt+jwt") => + new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor + { + Issuer = Issuer, + Audience = Audience, + Subject = new ClaimsIdentity(new[] + { + new Claim(JwtRegisteredClaimNames.Sub, _user.Id), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + }), + Expires = DateTime.UtcNow.AddDays(1), + SigningCredentials = credentials, + TokenType = type, + }); + + [Fact] + public async Task ShouldAcceptRefreshTokenIssuedByTheApplication() + { + var result = await Validate(await IssueRefreshToken()); + + result.IsValid.Should().BeTrue(result.Reason); + result.UserId.Should().Be(_user.Id); + } + + [Fact] + public async Task ShouldRejectUnsignedRefreshToken() + { + var forged = ForgeToken(credentials: null); + forged.Split('.')[2].Should().BeEmpty("the token must be unsigned (alg: none) for this test"); + + (await Validate(forged)).IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ShouldRejectRefreshTokenSignedWithUnknownKey() + { + using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var forged = ForgeToken(new SigningCredentials(new ECDsaSecurityKey(ecdsa) { KeyId = "attacker" }, SecurityAlgorithms.EcdsaSha256)); + + (await Validate(forged)).IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ShouldRejectAccessTokenUsedAsRefreshToken() + { + using var scope = _provider.CreateScope(); + var accessToken = await scope.ServiceProvider.GetRequiredService() + .WithEmail(Email).WithJwtClaims().BuildToken(); + + (await Validate(accessToken)).IsValid.Should().BeFalse(); + } + + [Theory] + [InlineData("")] + [InlineData("not-a-jwt")] + public async Task ShouldRejectMalformedRefreshToken(string token) + { + (await Validate(token)).IsValid.Should().BeFalse(); + } + + [Fact] + public async Task ShouldRejectRefreshTokenOfLockedOutUser() + { + var token = await IssueRefreshToken(); + using (var scope = _provider.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var user = await users.FindByIdAsync(_user.Id); + (await users.SetLockoutEndDateAsync(user!, DateTimeOffset.UtcNow.AddHours(1))).Succeeded.Should().BeTrue(); + } + + var result = await Validate(token); + + result.IsValid.Should().BeFalse(); + result.Reason.Should().Be("User blocked"); + } + + [Fact] + public async Task ShouldAcceptRefreshTokenWhenLockoutHasExpired() + { + var token = await IssueRefreshToken(); + using (var scope = _provider.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var user = await users.FindByIdAsync(_user.Id); + (await users.SetLockoutEndDateAsync(user!, DateTimeOffset.UtcNow.AddHours(-1))).Succeeded.Should().BeTrue(); + } + + (await Validate(token)).IsValid.Should().BeTrue(); + } + + [Fact] + public async Task ShouldRejectRefreshTokenOfDeletedUser() + { + var token = await IssueRefreshToken(); + using (var scope = _provider.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + (await users.DeleteAsync((await users.FindByIdAsync(_user.Id))!)).Succeeded.Should().BeTrue(); + } + + var result = await Validate(token); + + result.IsValid.Should().BeFalse(); + result.Reason.Should().Be("User not found"); + } +} From a65f6622540bdb2b736959afd625f5d9670417ce Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 18:29:14 -0300 Subject: [PATCH 5/6] style: remove redundant parentheses --- src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs b/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs index 1354188..834f0b1 100644 --- a/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs +++ b/src/NetDevPack.Identity/Jwt/JwtBuilderInject.cs @@ -267,7 +267,7 @@ public async Task ValidateRefreshToken(string refreshTok // 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() + var result = await handler.ValidateTokenAsync(refreshToken, new TokenValidationParameters { ValidIssuer = GetIssuer(), ValidAudience = _settings.Value.Audience, From 561a6d72b472d95d4d55d6ce41951655b8539e4b Mon Sep 17 00:00:00 2001 From: Bruno Brito Date: Tue, 17 Nov 2026 18:46:28 -0300 Subject: [PATCH 6/6] test: cover JWKS issuance end to end Same JwksIntegrationTests as #31: /jwks publishes public keys only, a third party validates the access token with the published JWKS, refresh tokens are signed with the JWKS key. Test parallelization disabled (static in-memory key store). --- .../JwksIntegrationTests.cs | 127 ++++++++++++++++++ .../NetDevPack.Identity.Tests.csproj | 6 + .../xunit.runner.json | 4 + 3 files changed, 137 insertions(+) create mode 100644 tests/NetDevPack.Identity.Tests/JwksIntegrationTests.cs create mode 100644 tests/NetDevPack.Identity.Tests/xunit.runner.json diff --git a/tests/NetDevPack.Identity.Tests/JwksIntegrationTests.cs b/tests/NetDevPack.Identity.Tests/JwksIntegrationTests.cs new file mode 100644 index 0000000..77ab60e --- /dev/null +++ b/tests/NetDevPack.Identity.Tests/JwksIntegrationTests.cs @@ -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; + +/// +/// 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. +/// +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(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>(); + _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 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().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() + .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() + .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().ValidateRefreshToken(refreshToken); + validation.IsValid.Should().BeTrue(validation.Reason); + } + } +} diff --git a/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj index 2e02fa2..e1f8bae 100644 --- a/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj +++ b/tests/NetDevPack.Identity.Tests/NetDevPack.Identity.Tests.csproj @@ -15,6 +15,12 @@ + + + + + diff --git a/tests/NetDevPack.Identity.Tests/xunit.runner.json b/tests/NetDevPack.Identity.Tests/xunit.runner.json new file mode 100644 index 0000000..08c512b --- /dev/null +++ b/tests/NetDevPack.Identity.Tests/xunit.runner.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "parallelizeTestCollections": false +}