diff --git a/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs b/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs index 7501779..b1e658d 100644 --- a/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs +++ b/src/SlpModularCms.Core.Tests/Identity/AuthServiceTests.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Abstractions; using FluentAssertions; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -129,6 +129,25 @@ public class AuthServiceTests await act.Should().ThrowAsync(); } + [Fact] + public async Task RefreshTokenAsync_ShouldThrow_AndRevoke_WhenUserWasDeactivated() + { + var user = new ApplicationUser { Id = Guid.NewGuid(), Email = "user@example.com", IsActive = false }; + _context.Users.Add(user); + _context.RefreshTokens.Add(new RefreshToken + { + Token = "still-valid-token", + UserId = user.Id, + ExpiryDate = DateTimeOffset.UtcNow.AddDays(1) + }); + await _context.SaveChangesAsync(); + + var act = () => _service.RefreshTokenAsync("still-valid-token"); + + await act.Should().ThrowAsync(); + (await _context.RefreshTokens.SingleAsync()).IsRevoked.Should().BeTrue(); + } + [Fact] public async Task RefreshTokenAsync_ShouldRevokeAllTokensAndThrow_WhenTokenAlreadyUsed() { diff --git a/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs b/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs new file mode 100644 index 0000000..5af01d2 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Identity/DeactivatedUserAccessTests.cs @@ -0,0 +1,184 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.IdentityModel.Tokens; +using SlpModularCms.Core.Data; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Identity.Authorization; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Models; + +namespace SlpModularCms.Core.Tests.Identity; + +/// +/// The scenario that was broken: a user is logged in with a still-valid access token and is then +/// deactivated or deleted. Every following request with that token must be refused, reads and +/// writes alike, until the token would have expired on its own. +/// +public class DeactivatedUserAccessTests : IAsyncLifetime +{ + private static readonly JwtSettings Jwt = new() + { + Secret = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789", + Issuer = "test-issuer", + Audience = "test-audience" + }; + + private readonly string _dbName = Guid.NewGuid().ToString(); + private IHost _host = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + var builder = new HostBuilder().ConfigureWebHost(web => + { + web.UseTestServer(); + web.ConfigureServices(services => + { + services.AddRouting(); + services.AddDbContext(o => o.UseInMemoryDatabase(_dbName)); + services.AddAuthentication(JwtBearerDefaultsScheme) + .AddJwtBearer(o => o.UseCmsTokenValidation(JwtTokenValidation.Create(Jwt))); + services.AddAuthorization(); + }); + web.Configure(app => + { + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(e => + { + e.MapGet("/data", () => Results.Ok("secret")).RequireAuthorization(); + e.MapPost("/act", () => Results.Ok("done")).RequireAuthorization(); + }); + }); + }); + + _host = await builder.StartAsync(); + _client = _host.GetTestClient(); + } + + private const string JwtBearerDefaultsScheme = "Bearer"; + + public async Task DisposeAsync() + { + _client.Dispose(); + await _host.StopAsync(); + _host.Dispose(); + } + + private async Task AddUserAsync(bool isActive = true) + { + using var scope = _host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive }; + db.Users.Add(user); + await db.SaveChangesAsync(); + return user; + } + + private async Task SetActiveAsync(Guid id, bool active) + { + using var scope = _host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = await db.Users.SingleAsync(u => u.Id == id); + user.IsActive = active; + await db.SaveChangesAsync(); + } + + private async Task DeleteAsync(Guid id) + { + using var scope = _host.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Users.Remove(await db.Users.SingleAsync(u => u.Id == id)); + await db.SaveChangesAsync(); + } + + private static string TokenFor(Guid userId) + { + var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Jwt.Secret)); + var token = new JwtSecurityToken( + Jwt.Issuer, + Jwt.Audience, + [ + new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()), + new Claim(ClaimTypes.Role, "Owner") + ], + expires: DateTime.UtcNow.AddMinutes(30), + signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); + return new JwtSecurityTokenHandler().WriteToken(token); + } + + private async Task CallAsync(HttpMethod method, string path, string token) + { + using var request = new HttpRequestMessage(method, path); + request.Headers.Authorization = new("Bearer", token); + using var response = await _client.SendAsync(request); + return response.StatusCode; + } + + [Fact] + public async Task ActiveUser_CanReadAndWrite() + { + var user = await AddUserAsync(); + var token = TokenFor(user.Id); + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK); + (await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task UserDeactivatedAfterLogin_IsRefusedOnTheNextGetAndPost_WithTheSameValidToken() + { + var user = await AddUserAsync(); + var token = TokenFor(user.Id); + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK); + + await SetActiveAsync(user.Id, false); + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); + (await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task ReactivatedUser_IsServedAgain() + { + var user = await AddUserAsync(); + var token = TokenFor(user.Id); + await SetActiveAsync(user.Id, false); + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); + + await SetActiveAsync(user.Id, true); + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task UserDeletedAfterLogin_IsRefusedOnTheNextGetAndPost() + { + var user = await AddUserAsync(); + var token = TokenFor(user.Id); + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK); + + await DeleteAsync(user.Id); + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); + (await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task ValidlySignedTokenForUnknownUser_IsRefused() + { + var token = TokenFor(Guid.NewGuid()); + + (await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized); + } +} diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index db4c8ff..8d47456 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -82,7 +82,7 @@ public static class ServiceCollectionExtensions }) .AddJwtBearer(options => { - options.TokenValidationParameters = tokenValidationParameters; + options.UseCmsTokenValidation(tokenValidationParameters); }); // 5. Authorization diff --git a/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs b/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs new file mode 100644 index 0000000..6fb900b --- /dev/null +++ b/src/SlpModularCms.Core/Identity/Authorization/ActiveUserTokenValidation.cs @@ -0,0 +1,61 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.JsonWebTokens; +using SlpModularCms.Core.Data; + +namespace SlpModularCms.Core.Identity.Authorization; + +/// +/// Rejects a structurally valid access token when its account is no longer allowed to act: +/// the user was deactivated or deleted after the token was issued. +/// +/// +/// A signed JWT stays valid until it expires, so without this check a deactivated or deleted user +/// could keep reading and writing for up to JwtSettings:ExpiryMinutes. The check runs for +/// every authenticated request (reads and writes alike) and deliberately has no cache: a cache +/// would bring back a window in which a deactivated user is still served. +/// +public static class ActiveUserTokenValidation +{ + /// + /// The one place the bearer scheme is configured: signature/lifetime parameters plus the + /// active-account check. Hosts and tests both go through this, so the check cannot be dropped + /// from one without the other noticing. + /// + public static JwtBearerOptions UseCmsTokenValidation( + this JwtBearerOptions options, + Microsoft.IdentityModel.Tokens.TokenValidationParameters parameters) + { + options.TokenValidationParameters = parameters; + options.Events = new JwtBearerEvents { OnTokenValidated = ValidateAsync }; + return options; + } + + public static async Task ValidateAsync(TokenValidatedContext context) + { + var principal = context.Principal; + var rawId = principal?.FindFirstValue(ClaimTypes.NameIdentifier) + ?? principal?.FindFirstValue(JwtRegisteredClaimNames.Sub); + + if (!Guid.TryParse(rawId, out var userId)) + { + context.Fail("Token has no valid subject."); + return; + } + + var db = context.HttpContext.RequestServices.GetRequiredService(); + var isActive = await db.Users + .AsNoTracking() + .Where(u => u.Id == userId) + .Select(u => (bool?)u.IsActive) + .FirstOrDefaultAsync(context.HttpContext.RequestAborted); + + if (isActive != true) + { + // Same 401 whether the user is gone or deactivated: which one is not the caller's business. + context.Fail("Account is not active."); + } + } +} diff --git a/src/SlpModularCms.Core/Identity/Services/AuthService.cs b/src/SlpModularCms.Core/Identity/Services/AuthService.cs index 78a9599..93f8782 100644 --- a/src/SlpModularCms.Core/Identity/Services/AuthService.cs +++ b/src/SlpModularCms.Core/Identity/Services/AuthService.cs @@ -71,6 +71,14 @@ public class AuthService : IAuthService throw new UnauthorizedException("Mogelijk token misbruik gedetecteerd. Alle sessies zijn beëindigd."); } + if (!savedRefreshToken.User.IsActive) + { + // A deactivated account must not get a new access token from a still-valid refresh token. + savedRefreshToken.IsRevoked = true; + await _context.SaveChangesAsync(); + throw new UnauthorizedException("Ongeldig refresh token."); + } + savedRefreshToken.IsUsed = true; await _context.SaveChangesAsync();