U3 password-reset (backend): wachtwoord vergeten en opnieuw instellen
POST auth/forgot-password antwoordt altijd hetzelfde (202) en handelt de mail na het antwoord af; POST auth/reset-password zet een nieuw wachtwoord met de link uit de mail. Alleen een voltooide reset trekt alle refresh tokens in (en beeindigt eerdere access tokens via de security stamp); het aanvragen raakt niets. Link eenmalig en tijdsbeperkt (standaard 60 minuten), cooldown van 5 minuten per adres in het geheugen, beide endpoints onder de login-limiter. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Core.SiteSettings;
|
||||
|
||||
namespace SlpModularCms.Core.Email;
|
||||
@@ -16,6 +17,7 @@ public interface IIdentityMailService
|
||||
bool IsEnabled { get; }
|
||||
|
||||
Task<MailSendResult> SendInvitationAsync(string email, string token, string? language, bool isNewLink, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendPasswordResetAsync(ApplicationUser user, string token, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendAccountReactivatedAsync(ApplicationUser user, CancellationToken ct = default);
|
||||
Task<MailSendResult> SendRoleChangedAsync(ApplicationUser user, string newRole, CancellationToken ct = default);
|
||||
@@ -29,6 +31,7 @@ public sealed class IdentityMailService(
|
||||
IOptions<EmailOptions> email,
|
||||
IOptions<AppMailOptions> app,
|
||||
IOptions<InvitationSettings> invitation,
|
||||
IOptions<PasswordResetSettings> resetSettings,
|
||||
ILogger<IdentityMailService> logger) : IIdentityMailService
|
||||
{
|
||||
public bool IsEnabled => !string.IsNullOrWhiteSpace(email.Value.Smtp.Host);
|
||||
@@ -44,6 +47,14 @@ public sealed class IdentityMailService(
|
||||
detail: null,
|
||||
ct);
|
||||
|
||||
/// <summary>The link carries the user id and the token (no e-mail address in a URL).</summary>
|
||||
public Task<MailSendResult> SendPasswordResetAsync(ApplicationUser user, string token, CancellationToken ct = default) =>
|
||||
SendAsync(
|
||||
MailKind.PasswordReset, user.Email, user.PreferredLanguage, user.DisplayName,
|
||||
actionPath: "/reset-password?uid=" + user.Id + "&token=" + Uri.EscapeDataString(token),
|
||||
validForMinutes: resetSettings.Value.TokenLifetimeMinutes,
|
||||
detail: null, ct);
|
||||
|
||||
public Task<MailSendResult> SendAccountDeactivatedAsync(ApplicationUser user, CancellationToken ct = default) =>
|
||||
SendAsync(MailKind.AccountDeactivated, user.Email, user.PreferredLanguage, user.DisplayName, null, null, null, ct);
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
@@ -52,7 +54,9 @@ public static class ServiceCollectionExtensions
|
||||
})
|
||||
.AddRoles<ApplicationRole>()
|
||||
.AddRoleManager<RoleManager<ApplicationRole>>()
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>();
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
// Needed for the password-reset token (stateless, single use through the security stamp).
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
// 3. Auth & Identity Services
|
||||
var jwtSettings = configuration.GetSection("JwtSettings").Get<JwtSettings>()
|
||||
@@ -67,6 +71,21 @@ public static class ServiceCollectionExtensions
|
||||
$"{InvitationSettings.SectionName}:ExpiryHours must be between 1 and {InvitationSettings.MaxExpiryHours}.")
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<PasswordResetSettings>()
|
||||
.Bind(configuration.GetSection(PasswordResetSettings.SectionName))
|
||||
.Validate(
|
||||
PasswordResetSettings.IsValid,
|
||||
$"{PasswordResetSettings.SectionName}: TokenLifetimeMinutes must be 5..1440 and CooldownMinutes 1..60.")
|
||||
.ValidateOnStart();
|
||||
// The reset link lifetime is the data-protection token lifetime.
|
||||
services.AddOptions<DataProtectionTokenProviderOptions>()
|
||||
.Configure<IOptions<PasswordResetSettings>>((o, reset) => o.TokenLifespan = TimeSpan.FromMinutes(reset.Value.TokenLifetimeMinutes));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton(sp =>
|
||||
new ResetCooldown(sp.GetRequiredService<TimeProvider>(), TimeSpan.FromMinutes(sp.GetRequiredService<IOptions<PasswordResetSettings>>().Value.CooldownMinutes)));
|
||||
services.AddScoped<IPasswordResetService, PasswordResetService>();
|
||||
services.AddSingleton<IPasswordResetDispatcher, BackgroundPasswordResetDispatcher>();
|
||||
|
||||
services.AddCmsEmail(configuration);
|
||||
|
||||
services.AddScoped<IAuthService, AuthService>();
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace SlpModularCms.Core.Identity.Models;
|
||||
[ExcludeFromCodeCoverage] public record InviteUserRequest(string Email, string Role, string? Language = null);
|
||||
[ExcludeFromCodeCoverage] public record CompleteSetupRequest(string Token, string Password, string? Name = null);
|
||||
[ExcludeFromCodeCoverage] public record ChangeRoleRequest(string NewRole);
|
||||
[ExcludeFromCodeCoverage] public record ForgotPasswordRequest(string Email);
|
||||
[ExcludeFromCodeCoverage] public record ResetPasswordRequest(Guid UserId, string Token, string NewPassword);
|
||||
[ExcludeFromCodeCoverage] public record UpdateProfileRequest(string Name, string Email, string? Language = null);
|
||||
[ExcludeFromCodeCoverage] public record ChangePasswordRequest(string CurrentPassword, string NewPassword);
|
||||
[ExcludeFromCodeCoverage] public record SetUserActiveRequest(bool IsActive);
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Email;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
|
||||
namespace SlpModularCms.Core.Identity.Services;
|
||||
|
||||
/// <summary>Settings for "forgot password" (section <c>Identity:PasswordReset</c>).</summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class PasswordResetSettings
|
||||
{
|
||||
public const string SectionName = "Identity:PasswordReset";
|
||||
public const int DefaultTokenLifetimeMinutes = 60;
|
||||
public const int DefaultCooldownMinutes = 5;
|
||||
|
||||
/// <summary>How long a reset link works (5 to 1440 minutes). The link is single-use besides.</summary>
|
||||
public int TokenLifetimeMinutes { get; set; } = DefaultTokenLifetimeMinutes;
|
||||
|
||||
/// <summary>At most one reset mail per address per this many minutes (1 to 60); extra requests are ignored silently.</summary>
|
||||
public int CooldownMinutes { get; set; } = DefaultCooldownMinutes;
|
||||
|
||||
public static bool IsValid(PasswordResetSettings s) =>
|
||||
s.TokenLifetimeMinutes is >= 5 and <= 1440 && s.CooldownMinutes is >= 1 and <= 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One reset mail per address per window, in memory. Anonymous requests could otherwise be used to flood
|
||||
/// somebody's inbox; the per-client rate limiter does not help against many client addresses. Memory is
|
||||
/// bounded: expired entries are purged and, if the table is still full, new addresses are refused (the
|
||||
/// caller treats that like the cooldown: silently, with the same response).
|
||||
/// </summary>
|
||||
public sealed class ResetCooldown(TimeProvider time, TimeSpan window, int capacity = 10_000)
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _last = new();
|
||||
|
||||
/// <summary>True when a mail may be sent for this address now (and it is recorded); false during the cooldown.</summary>
|
||||
public bool TryEnter(string normalizedAddress)
|
||||
{
|
||||
var now = time.GetUtcNow();
|
||||
|
||||
if (_last.Count >= capacity) Purge(now);
|
||||
if (_last.Count >= capacity && !_last.ContainsKey(normalizedAddress)) return false;
|
||||
|
||||
var allowed = false;
|
||||
_last.AddOrUpdate(
|
||||
normalizedAddress,
|
||||
_ => { allowed = true; return now; },
|
||||
(_, previous) =>
|
||||
{
|
||||
if (now - previous >= window) { allowed = true; return now; }
|
||||
return previous;
|
||||
});
|
||||
return allowed;
|
||||
}
|
||||
|
||||
public int Count => _last.Count;
|
||||
|
||||
private void Purge(DateTimeOffset now)
|
||||
{
|
||||
foreach (var (key, at) in _last)
|
||||
{
|
||||
if (now - at >= window) _last.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum PasswordResetStatus { Succeeded, InvalidLink, PasswordRejected }
|
||||
|
||||
public sealed record PasswordResetResult(PasswordResetStatus Status, IReadOnlyList<string> Problems)
|
||||
{
|
||||
public static PasswordResetResult Success { get; } = new(PasswordResetStatus.Succeeded, []);
|
||||
public static PasswordResetResult InvalidLink { get; } = new(PasswordResetStatus.InvalidLink, []);
|
||||
}
|
||||
|
||||
public interface IPasswordResetService
|
||||
{
|
||||
/// <summary>
|
||||
/// Sends a reset mail when the address belongs to an active account, mail is on and the cooldown allows
|
||||
/// it. Changes nothing else: not the password, the security stamp, nor any session. Never throws and
|
||||
/// reveals nothing about the address.
|
||||
/// </summary>
|
||||
Task RequestAsync(string email, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sets a new password with a valid token. Only a completed reset ends the account's sessions
|
||||
/// (its refresh tokens are revoked here, its earlier access tokens end through the changed security
|
||||
/// stamp). A bad, expired or already used token is one generic <see cref="PasswordResetStatus.InvalidLink"/>.
|
||||
/// </summary>
|
||||
Task<PasswordResetResult> ResetAsync(Guid userId, string token, string newPassword, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class PasswordResetService(
|
||||
UserManager<ApplicationUser> users,
|
||||
ApplicationDbContext db,
|
||||
IIdentityMailService mail,
|
||||
ResetCooldown cooldown,
|
||||
ILogger<PasswordResetService> logger) : IPasswordResetService
|
||||
{
|
||||
public async Task RequestAsync(string email, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!mail.IsEnabled || string.IsNullOrWhiteSpace(email)) return;
|
||||
|
||||
var address = email.Trim();
|
||||
// Unknown addresses enter the cooldown too, so the outcome does not depend on the account existing.
|
||||
if (!cooldown.TryEnter(address.ToLowerInvariant()))
|
||||
{
|
||||
logger.LogInformation("password_reset_request_ignored reason=cooldown");
|
||||
return;
|
||||
}
|
||||
|
||||
var user = await users.FindByEmailAsync(address);
|
||||
if (user is null || !user.IsActive) return;
|
||||
|
||||
var token = await users.GeneratePasswordResetTokenAsync(user);
|
||||
await mail.SendPasswordResetAsync(user, token, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning("password_reset_request_failed exception={ExceptionType}", ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PasswordResetResult> ResetAsync(Guid userId, string token, string newPassword, CancellationToken ct = default)
|
||||
{
|
||||
var user = await users.FindByIdAsync(userId.ToString());
|
||||
if (user is null || !user.IsActive) return PasswordResetResult.InvalidLink;
|
||||
|
||||
var result = await users.ResetPasswordAsync(user, token, newPassword);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
// The token is checked before the password, so a policy complaint only reaches a holder of a valid link.
|
||||
if (result.Errors.Any(e => e.Code == nameof(IdentityErrorDescriber.InvalidToken)))
|
||||
return PasswordResetResult.InvalidLink;
|
||||
return new PasswordResetResult(PasswordResetStatus.PasswordRejected, result.Errors.Select(e => e.Description).ToList());
|
||||
}
|
||||
|
||||
// Completed reset: end every session of this account. Not done on a mere request.
|
||||
var tokens = await db.RefreshTokens.Where(t => t.UserId == user.Id && !t.IsRevoked).ToListAsync(ct);
|
||||
foreach (var t in tokens) t.IsRevoked = true;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
logger.LogInformation("password_reset_completed");
|
||||
return PasswordResetResult.Success;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a reset request without making the caller wait for it. The anonymous endpoint answers first, so
|
||||
/// its response time does not tell whether the address exists (a mail takes longer than nothing).
|
||||
/// </summary>
|
||||
public interface IPasswordResetDispatcher
|
||||
{
|
||||
void Dispatch(string email);
|
||||
}
|
||||
|
||||
public sealed class BackgroundPasswordResetDispatcher(IServiceScopeFactory scopes, ILogger<BackgroundPasswordResetDispatcher> logger)
|
||||
: IPasswordResetDispatcher
|
||||
{
|
||||
public void Dispatch(string email) =>
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<IPasswordResetService>().RequestAsync(email);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning("password_reset_dispatch_failed exception={ExceptionType}", ex.GetType().Name);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user