Beveiliging: gedeactiveerde of verwijderde gebruiker wordt direct geweigerd

Het JWT werd alleen op handtekening en looptijd gecontroleerd, dus een gedeactiveerde
gebruiker kon tot het verlopen van het token lezen en schrijven. Nu controleert de
bearer-validatie per request of het account bestaat en actief is, en weigert de refresh
een inactieve gebruiker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 14:36:09 +01:00
co-authored by Claude Sonnet 5.5
parent 6c33a7ce36
commit 33a7500648
5 changed files with 274 additions and 2 deletions
@@ -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<UnauthorizedException>();
}
[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<UnauthorizedException>();
(await _context.RefreshTokens.SingleAsync()).IsRevoked.Should().BeTrue();
}
[Fact]
public async Task RefreshTokenAsync_ShouldRevokeAllTokensAndThrow_WhenTokenAlreadyUsed()
{
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<ApplicationDbContext>(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<ApplicationUser> AddUserAsync(bool isActive = true)
{
using var scope = _host.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
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<ApplicationDbContext>();
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<ApplicationDbContext>();
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<HttpStatusCode> 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);
}
}