U2 identity-mail-flows (backend): taal per gebruiker, uitnodigingsmail, opnieuw versturen, meldingen, stamp-controle
Kolommen Users.PreferredLanguage en Invitations.Language (additieve migratie). IdentityMailService verstuurt uitnodiging, nieuwe link en meldingen bij deactiveren, heractiveren en rolwijziging; een mailfout laat nooit een actie falen, het resultaat gaat mee in de respons naast de kopieerbare link. Nieuwe actie resend-invite. De security stamp zit in het access token en wordt vergeleken in de actief-controle: een wachtwoordwijziging beeindigt eerder uitgegeven access tokens, de refresh geeft stil een nieuw token. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -79,7 +79,7 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
|
||||
{
|
||||
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 };
|
||||
var user = new ApplicationUser { Id = Guid.NewGuid(), UserName = "a@b.nl", Email = "a@b.nl", IsActive = isActive, SecurityStamp = "stamp-1" };
|
||||
db.Users.Add(user);
|
||||
await db.SaveChangesAsync();
|
||||
return user;
|
||||
@@ -102,16 +102,17 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static string TokenFor(Guid userId)
|
||||
private static string TokenFor(Guid userId, string? stamp = "stamp-1")
|
||||
{
|
||||
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Jwt.Secret));
|
||||
var token = new JwtSecurityToken(
|
||||
Jwt.Issuer,
|
||||
Jwt.Audience,
|
||||
[
|
||||
new[]
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
|
||||
new Claim(ClaimTypes.Role, "Owner")
|
||||
],
|
||||
}.Concat(stamp is null ? [] : [new Claim(ActiveUserTokenValidation.StampClaim, stamp)]),
|
||||
expires: DateTime.UtcNow.AddMinutes(30),
|
||||
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
@@ -181,4 +182,44 @@ public class DeactivatedUserAccessTests : IAsyncLifetime
|
||||
|
||||
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
private async Task SetStampAsync(Guid id, string stamp)
|
||||
{
|
||||
using var scope = _host.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var user = await db.Users.SingleAsync(u => u.Id == id);
|
||||
user.SecurityStamp = stamp;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APasswordChange_EndsTheAccessTokensIssuedBefore_ForGetAndPost()
|
||||
{
|
||||
var user = await AddUserAsync();
|
||||
var token = TokenFor(user.Id, "stamp-1");
|
||||
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.OK);
|
||||
|
||||
await SetStampAsync(user.Id, "stamp-2"); // what a password change or reset does
|
||||
|
||||
(await CallAsync(HttpMethod.Get, "/data", token)).Should().Be(HttpStatusCode.Unauthorized);
|
||||
(await CallAsync(HttpMethod.Post, "/act", token)).Should().Be(HttpStatusCode.Unauthorized);
|
||||
// A token issued after the change carries the new stamp and works.
|
||||
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "stamp-2"))).Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATokenWithoutAStamp_IssuedBeforeThisCheckExisted_IsRefused()
|
||||
{
|
||||
var user = await AddUserAsync();
|
||||
|
||||
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, stamp: null))).Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATokenWithAWrongStamp_IsRefused()
|
||||
{
|
||||
var user = await AddUserAsync();
|
||||
|
||||
(await CallAsync(HttpMethod.Get, "/data", TokenFor(user.Id, "someone-elses-stamp"))).Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,4 +394,32 @@ public class InvitationServiceTests
|
||||
|
||||
(await _service.RegenerateInvitationAsync(inv.Id)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_StoresTheNormalisedLanguage()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("lang@example.com", "User", "EN-gb");
|
||||
|
||||
(await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().Be("en");
|
||||
(await _service.GetAllPendingInvitationsAsync()).Single().Language.Should().Be("en");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitationAsync_IgnoresAnUnsupportedLanguage()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("lang2@example.com", "User", "de");
|
||||
|
||||
(await _context.Invitations.SingleAsync(i => i.Token == token)).Language.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteInvitationAsync_CopiesTheInvitationLanguageToTheNewAccount()
|
||||
{
|
||||
var token = await _service.CreateInvitationAsync("lang3@example.com", "User", "en");
|
||||
_userManager.CreateAsync(Arg.Any<ApplicationUser>(), Arg.Any<string>()).Returns(IdentityResult.Success);
|
||||
|
||||
await _service.CompleteInvitationAsync(token, "SafePassword123!", "Naam");
|
||||
|
||||
await _userManager.Received(1).CreateAsync(Arg.Is<ApplicationUser>(u => u.PreferredLanguage == "en"), "SafePassword123!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Net;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Hosting;
|
||||
using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
|
||||
namespace SlpModularCms.Core.Tests.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// The real chain end to end (real Identity password handling, real tokens from <see cref="AuthService"/>,
|
||||
/// the real bearer check): a password change ends the access tokens issued before it, and the refresh
|
||||
/// token then silently gives a new one that works.
|
||||
/// </summary>
|
||||
public class SessionEndsOnPasswordChangeTests : 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",
|
||||
ExpiryMinutes = 30
|
||||
};
|
||||
|
||||
private readonly string _dbName = Guid.NewGuid().ToString();
|
||||
private IHost _host = null!;
|
||||
private HttpClient _client = null!;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_host = await new HostBuilder().ConfigureWebHost(web =>
|
||||
{
|
||||
web.UseTestServer();
|
||||
web.ConfigureServices(services =>
|
||||
{
|
||||
services.AddLogging();
|
||||
services.AddRouting();
|
||||
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(_dbName));
|
||||
services.AddIdentityCore<ApplicationUser>().AddRoles<ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>();
|
||||
services.Configure<JwtSettings>(o =>
|
||||
{
|
||||
o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes;
|
||||
});
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
services.AddAuthentication("Bearer").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());
|
||||
});
|
||||
}).StartAsync();
|
||||
_client = _host.GetTestClient();
|
||||
|
||||
using var scope = _host.Services.CreateScope();
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
var result = await users.CreateAsync(
|
||||
new ApplicationUser { UserName = "owner@test.nl", Email = "owner@test.nl", IsActive = true, PreferredLanguage = "en" }, "Password1!");
|
||||
result.Succeeded.Should().BeTrue(string.Join(",", result.Errors.Select(e => e.Code)));
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
_client.Dispose();
|
||||
await _host.StopAsync();
|
||||
_host.Dispose();
|
||||
}
|
||||
|
||||
private async Task<HttpStatusCode> GetAsync(string token)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/data");
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
return (await _client.SendAsync(request)).StatusCode;
|
||||
}
|
||||
|
||||
private async Task<T> InScope<T>(Func<IAuthService, Task<T>> action)
|
||||
{
|
||||
using var scope = _host.Services.CreateScope();
|
||||
return await action(scope.ServiceProvider.GetRequiredService<IAuthService>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARealLoginToken_Works_AndCarriesTheUsersLanguage()
|
||||
{
|
||||
var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!"));
|
||||
|
||||
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK);
|
||||
login.User.Language.Should().Be("en");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APasswordChange_EndsTheEarlierAccessToken_AndTheRefreshTokenGivesAWorkingNewOne()
|
||||
{
|
||||
var login = await InScope(a => a.AuthenticateAsync("owner@test.nl", "Password1!"));
|
||||
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.OK);
|
||||
|
||||
await InScope(async a =>
|
||||
{
|
||||
await a.ChangePasswordAsync(login.User.Id, "Password1!", "Another-Pass2!");
|
||||
return 0;
|
||||
});
|
||||
|
||||
(await GetAsync(login.AccessToken)).Should().Be(HttpStatusCode.Unauthorized);
|
||||
|
||||
var refreshed = await InScope(a => a.RefreshTokenAsync(login.RefreshToken));
|
||||
(await GetAsync(refreshed.AccessToken)).Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user