From 5c2f68e00a995d0f37a73ecc083a42acebd6db70 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Wed, 18 Nov 2026 23:29:27 +0100 Subject: [PATCH 01/18] Add generic verification infrastructure and EF persistence --- ...rificationRequestModelBuilderExtensions.cs | 15 ++ ...rificationRequestStoreBuilderExtensions.cs | 18 ++ .../Model/VerificationRequestConfiguration.cs | 38 +++ .../Model/VerificationSendConfiguration.cs | 24 ++ .../Store/EfVerificationRequestStore.cs | 234 ++++++++++++++++++ .../Interface/IVerificationCodeGenerator.cs | 10 + .../Interface/IVerificationCodeVerifier.cs | 8 + .../Interface/IVerificationRequestStore.cs | 57 +++++ .../Interface/IVerificationSender.cs | 11 + .../Interface/IVerificationWorkflowService.cs | 23 ++ .../Model/VerificationChannel.cs | 9 + .../Model/VerificationCodeContext.cs | 12 + .../Model/VerificationOperationResult.cs | 15 ++ .../Model/VerificationOptions.cs | 30 +++ .../Model/VerificationPurpose.cs | 11 + .../Model/VerificationRequest.cs | 26 ++ .../Model/VerificationRequestStatus.cs | 9 + .../Model/VerificationSend.cs | 10 + .../RuntimeApps.Authentication.csproj | 8 +- .../RuntimeAppsAuthenticationBuilder.cs | 25 ++ .../DataProtectionVerificationCodeVerifier.cs | 77 ++++++ .../RandomVerificationCodeGenerator.cs | 24 ++ .../Service/VerificationHandle.cs | 17 ++ .../Service/VerificationWorkflowService.cs | 185 ++++++++++++++ .../VerificationPrimitivesTest.cs | 41 +++ 25 files changed, 933 insertions(+), 4 deletions(-) create mode 100644 RuntimeApps.Authentication.EF/Extensions/VerificationRequestModelBuilderExtensions.cs create mode 100644 RuntimeApps.Authentication.EF/Extensions/VerificationRequestStoreBuilderExtensions.cs create mode 100644 RuntimeApps.Authentication.EF/Model/VerificationRequestConfiguration.cs create mode 100644 RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs create mode 100644 RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs create mode 100644 RuntimeApps.Authentication/Interface/IVerificationCodeGenerator.cs create mode 100644 RuntimeApps.Authentication/Interface/IVerificationCodeVerifier.cs create mode 100644 RuntimeApps.Authentication/Interface/IVerificationRequestStore.cs create mode 100644 RuntimeApps.Authentication/Interface/IVerificationSender.cs create mode 100644 RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationChannel.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationCodeContext.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationOperationResult.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationOptions.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationPurpose.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationRequest.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationRequestStatus.cs create mode 100644 RuntimeApps.Authentication/Model/VerificationSend.cs create mode 100644 RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs create mode 100644 RuntimeApps.Authentication/Service/RandomVerificationCodeGenerator.cs create mode 100644 RuntimeApps.Authentication/Service/VerificationHandle.cs create mode 100644 RuntimeApps.Authentication/Service/VerificationWorkflowService.cs create mode 100644 Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs diff --git a/RuntimeApps.Authentication.EF/Extensions/VerificationRequestModelBuilderExtensions.cs b/RuntimeApps.Authentication.EF/Extensions/VerificationRequestModelBuilderExtensions.cs new file mode 100644 index 0000000..b6fa175 --- /dev/null +++ b/RuntimeApps.Authentication.EF/Extensions/VerificationRequestModelBuilderExtensions.cs @@ -0,0 +1,15 @@ +using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.EF.Model; + +namespace RuntimeApps.Authentication.EF.Extensions { + public static class VerificationRequestModelBuilderExtensions { + /// Adds the verification request and delivery-rate-limit entities to the consumer DbContext. + public static ModelBuilder AddVerificationRequestEntity(this ModelBuilder modelBuilder) + where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(modelBuilder); + modelBuilder.ApplyConfiguration(new VerificationRequestConfiguration()); + modelBuilder.ApplyConfiguration(new VerificationSendConfiguration()); + return modelBuilder; + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.EF/Extensions/VerificationRequestStoreBuilderExtensions.cs b/RuntimeApps.Authentication.EF/Extensions/VerificationRequestStoreBuilderExtensions.cs new file mode 100644 index 0000000..2112e67 --- /dev/null +++ b/RuntimeApps.Authentication.EF/Extensions/VerificationRequestStoreBuilderExtensions.cs @@ -0,0 +1,18 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using RuntimeApps.Authentication.EF.Store; +using RuntimeApps.Authentication.Interface; + +namespace RuntimeApps.Authentication.EF.Extensions { + public static class VerificationRequestStoreBuilderExtensions { + /// Registers the EF Core verification-request store. + public static IServiceCollection AddVerificationRequestStore(this IServiceCollection services) + where TDbContext : DbContext + where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(services); + services.TryAddScoped, EfVerificationRequestStore>(); + return services; + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.EF/Model/VerificationRequestConfiguration.cs b/RuntimeApps.Authentication.EF/Model/VerificationRequestConfiguration.cs new file mode 100644 index 0000000..e73441a --- /dev/null +++ b/RuntimeApps.Authentication.EF/Model/VerificationRequestConfiguration.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.EF.Model { + public sealed class VerificationRequestConfiguration : IEntityTypeConfiguration> + where TKey : IEquatable { + public void Configure(EntityTypeBuilder> builder) { + builder.ToTable("AuthenticationVerificationRequests"); + builder.HasKey(request => request.Id); + builder.Property(request => request.Id).ValueGeneratedOnAdd(); + builder.Property(request => request.UserId).IsRequired(); + builder.Property(request => request.Purpose).HasConversion().HasMaxLength(32).IsRequired(); + builder.Property(request => request.Channel).HasConversion().HasMaxLength(32).IsRequired(); + builder.Property(request => request.Status).HasConversion().HasMaxLength(32).IsRequired(); + builder.Property(request => request.CustomPurpose).HasMaxLength(128); + builder.Property(request => request.CustomChannel).HasMaxLength(128); + builder.Property(request => request.Destination).HasMaxLength(512).IsRequired(); + builder.Property(request => request.NormalizedDestination).HasMaxLength(512).IsRequired(); + builder.Property(request => request.PublicHandleHash).HasMaxLength(64).IsRequired(); + builder.Property(request => request.CodeVerifier).IsRequired(); + builder.Property(request => request.CreatedAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.Property(request => request.LastSentAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.Property(request => request.ExpiresAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.Property(request => request.CompletedAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.HasIndex(request => request.PublicHandleHash).IsUnique(); + builder.HasIndex(request => new { + request.NormalizedDestination, + request.Purpose, + request.Channel, + request.CreatedAt + }); + builder.HasIndex(request => new { request.UserId, request.Purpose, request.Status }); + builder.HasIndex(request => new { request.Status, request.ExpiresAt }); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs b/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs new file mode 100644 index 0000000..80381fe --- /dev/null +++ b/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.EF.Model { + public sealed class VerificationSendConfiguration : IEntityTypeConfiguration { + public void Configure(EntityTypeBuilder builder) { + builder.ToTable("AuthenticationVerificationSends"); + builder.HasKey(send => send.Id); + builder.Property(send => send.Id).ValueGeneratedOnAdd(); + builder.Property(send => send.NormalizedDestination).HasMaxLength(512).IsRequired(); + builder.Property(send => send.Purpose).HasConversion().HasMaxLength(32).IsRequired(); + builder.Property(send => send.Channel).HasConversion().HasMaxLength(32).IsRequired(); + builder.Property(send => send.SentAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.HasIndex(send => new { + send.NormalizedDestination, + send.Purpose, + send.Channel, + send.SentAt + }); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs new file mode 100644 index 0000000..292a037 --- /dev/null +++ b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs @@ -0,0 +1,234 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.EF.Store { + /// + /// Relational EF Core implementation. Conditional updates and serializable transactions protect + /// request state transitions and destination-level send limits against concurrent requests. + /// + public sealed class EfVerificationRequestStore : IVerificationRequestStore + where TDbContext : DbContext + where TKey : IEquatable { + private readonly TDbContext _dbContext; + + public EfVerificationRequestStore(TDbContext dbContext) { + _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); + if(_dbContext.Model.FindEntityType(typeof(VerificationRequest)) == null || + _dbContext.Model.FindEntityType(typeof(VerificationSend)) == null) + throw new InvalidOperationException( + $"The DbContext model does not include the verification entities. " + + $"Call modelBuilder.AddVerificationRequestEntity<{typeof(TKey).Name}>() in OnModelCreating."); + } + + private static void PrepareGeneratedId(VerificationRequest request) { + if(!EqualityComparer.Default.Equals(request.Id, default!)) + return; + object generatedId = typeof(TKey) == typeof(Guid) + ? Guid.NewGuid() + : typeof(TKey) == typeof(string) ? Guid.NewGuid().ToString("N") : null; + if(generatedId != null) { + request.Id = (TKey)generatedId; + return; + } + var typeCode = Type.GetTypeCode(typeof(TKey)); + if(typeCode is not (TypeCode.Byte or TypeCode.Int16 or TypeCode.Int32 or TypeCode.Int64 or + TypeCode.SByte or TypeCode.UInt16 or TypeCode.UInt32 or TypeCode.UInt64)) + throw new NotSupportedException( + $"Verification request key type '{typeof(TKey).FullName}' requires a non-default Id before persistence."); + } + + private IQueryable> Requests => _dbContext.Set>(); + private IQueryable Sends => _dbContext.Set(); + + public async Task TryCreateAsync( + VerificationRequest request, + DateTimeOffset sendsSince, + int maximumSendsPerHour, + CancellationToken cancellationToken = default) { + EnsureRelational(); + await using var transaction = await _dbContext.Database.BeginTransactionAsync( + IsolationLevel.Serializable, cancellationToken); + + var sendCount = await Sends.CountAsync(item => + item.NormalizedDestination == request.NormalizedDestination && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.SentAt >= sendsSince, cancellationToken); + + if(sendCount >= maximumSendsPerHour) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + await Requests.Where(item => + object.Equals(item.UserId, request.UserId) && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.NormalizedDestination == request.NormalizedDestination && + item.Status == VerificationRequestStatus.Pending) + .ExecuteUpdateAsync(setters => setters.SetProperty( + item => item.Status, VerificationRequestStatus.Superseded), cancellationToken); + + PrepareGeneratedId(request); + await Requests.AddAsync(request, cancellationToken); + await _dbContext.Set().AddAsync(new VerificationSend { + NormalizedDestination = request.NormalizedDestination, + Purpose = request.Purpose, + Channel = request.Channel, + SentAt = request.CreatedAt + }, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + return true; + } + + public async Task TrySetInitialVerifierAsync( + TKey requestId, + string verifier, + DateTimeOffset sentAt, + DateTimeOffset expiresAt, + CancellationToken cancellationToken = default) { + EnsureRelational(); + var affected = await Requests.Where(item => + item.Id.Equals(requestId) && + item.Status == VerificationRequestStatus.Pending && + item.CodeVersion == 0 && + item.CodeVerifier == string.Empty) + .ExecuteUpdateAsync(setters => setters + .SetProperty(item => item.CodeVerifier, verifier) + .SetProperty(item => item.CodeVersion, 1) + .SetProperty(item => item.LastSentAt, sentAt) + .SetProperty(item => item.ExpiresAt, expiresAt), cancellationToken); + return affected == 1; + } + + public Task> FindByHandleHashAsync( + string handleHash, + CancellationToken cancellationToken = default) => + Requests.AsNoTracking().SingleOrDefaultAsync( + request => request.PublicHandleHash == handleHash, cancellationToken); + + public async Task TryResendAsync( + TKey requestId, + int expectedCodeVersion, + string newCodeVerifier, + DateTimeOffset now, + DateTimeOffset expiresAt, + TimeSpan resendCooldown, + DateTimeOffset sendsSince, + int maximumSendsPerHour, + CancellationToken cancellationToken = default) { + EnsureRelational(); + await using var transaction = await _dbContext.Database.BeginTransactionAsync( + IsolationLevel.Serializable, cancellationToken); + + var request = await Requests.SingleOrDefaultAsync(item => item.Id.Equals(requestId), cancellationToken); + if(request == null || request.Status != VerificationRequestStatus.Pending || + request.LastSentAt > now - resendCooldown) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + var sendCount = await Sends.CountAsync(item => + item.NormalizedDestination == request.NormalizedDestination && + item.Purpose == request.Purpose && + item.Channel == request.Channel && + item.SentAt >= sendsSince, cancellationToken); + if(sendCount >= maximumSendsPerHour) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + var affected = await Requests.Where(item => + item.Id.Equals(requestId) && + item.Status == VerificationRequestStatus.Pending && + item.CodeVersion == expectedCodeVersion && + item.LastSentAt <= now - resendCooldown) + .ExecuteUpdateAsync(setters => setters + .SetProperty(item => item.CodeVerifier, newCodeVerifier) + .SetProperty(item => item.CodeVersion, item => item.CodeVersion + 1) + .SetProperty(item => item.FailedAttempts, 0) + .SetProperty(item => item.SendCount, item => item.SendCount + 1) + .SetProperty(item => item.LastSentAt, now) + .SetProperty(item => item.ExpiresAt, expiresAt), cancellationToken); + + if(affected != 1) { + await transaction.RollbackAsync(cancellationToken); + return false; + } + + await _dbContext.Set().AddAsync(new VerificationSend { + NormalizedDestination = request.NormalizedDestination, + Purpose = request.Purpose, + Channel = request.Channel, + SentAt = now + }, cancellationToken); + await _dbContext.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + return true; + } + + public async Task TryIncrementFailedAttemptsAsync( + TKey requestId, + int expectedCodeVersion, + int maximumFailedAttempts, + DateTimeOffset now, + CancellationToken cancellationToken = default) { + EnsureRelational(); + var affected = await Requests.Where(item => + item.Id.Equals(requestId) && + item.Status == VerificationRequestStatus.Pending && + item.CodeVersion == expectedCodeVersion && + item.ExpiresAt > now && + item.FailedAttempts < maximumFailedAttempts) + .ExecuteUpdateAsync(setters => setters + .SetProperty(item => item.FailedAttempts, item => item.FailedAttempts + 1) + .SetProperty(item => item.Status, + item => item.FailedAttempts + 1 >= maximumFailedAttempts + ? VerificationRequestStatus.Locked + : VerificationRequestStatus.Pending), cancellationToken); + return affected == 1; + } + + public async Task TryConsumeAsync( + TKey requestId, + int expectedCodeVersion, + DateTimeOffset now, + CancellationToken cancellationToken = default) { + EnsureRelational(); + var affected = await Requests.Where(item => + item.Id.Equals(requestId) && + item.Status == VerificationRequestStatus.Pending && + item.CodeVersion == expectedCodeVersion && + item.ExpiresAt > now) + .ExecuteUpdateAsync(setters => setters + .SetProperty(item => item.Status, VerificationRequestStatus.Completed) + .SetProperty(item => item.CompletedAt, now), cancellationToken); + return affected == 1; + } + + public async Task SupersedePendingAsync( + TKey userId, + VerificationPurpose purpose, + VerificationChannel channel, + string normalizedDestination, + CancellationToken cancellationToken = default) { + EnsureRelational(); + await Requests.Where(item => + object.Equals(item.UserId, userId) && + item.Purpose == purpose && + item.Channel == channel && + item.NormalizedDestination == normalizedDestination && + item.Status == VerificationRequestStatus.Pending) + .ExecuteUpdateAsync(setters => setters.SetProperty( + item => item.Status, VerificationRequestStatus.Superseded), cancellationToken); + } + + private void EnsureRelational() { + if(!_dbContext.Database.IsRelational()) + throw new NotSupportedException("Atomic verification-request operations require a relational EF Core provider."); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationCodeGenerator.cs b/RuntimeApps.Authentication/Interface/IVerificationCodeGenerator.cs new file mode 100644 index 0000000..e4449d4 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationCodeGenerator.cs @@ -0,0 +1,10 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IVerificationCodeGenerator where TKey : IEquatable { + Task GenerateAsync( + VerificationCodeContext context, + VerificationOptions options, + CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationCodeVerifier.cs b/RuntimeApps.Authentication/Interface/IVerificationCodeVerifier.cs new file mode 100644 index 0000000..94db047 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationCodeVerifier.cs @@ -0,0 +1,8 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IVerificationCodeVerifier where TKey : IEquatable { + string CreateVerifier(string code, VerificationRequest request); + bool Verify(string code, VerificationRequest request); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationRequestStore.cs b/RuntimeApps.Authentication/Interface/IVerificationRequestStore.cs new file mode 100644 index 0000000..fd09f02 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationRequestStore.cs @@ -0,0 +1,57 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + /// + /// Persistence contract for verification requests. State-changing methods must be atomic; + /// implementations must use conditional updates or transactions to prevent replay and races. + /// + public interface IVerificationRequestStore where TKey : IEquatable { + Task TryCreateAsync( + VerificationRequest request, + DateTimeOffset sendsSince, + int maximumSendsPerHour, + CancellationToken cancellationToken = default); + + Task TrySetInitialVerifierAsync( + TKey requestId, + string verifier, + DateTimeOffset sentAt, + DateTimeOffset expiresAt, + CancellationToken cancellationToken = default); + + Task> FindByHandleHashAsync( + string handleHash, + CancellationToken cancellationToken = default); + + Task TryResendAsync( + TKey requestId, + int expectedCodeVersion, + string newCodeVerifier, + DateTimeOffset now, + DateTimeOffset expiresAt, + TimeSpan resendCooldown, + DateTimeOffset sendsSince, + int maximumSendsPerHour, + CancellationToken cancellationToken = default); + + Task TryIncrementFailedAttemptsAsync( + TKey requestId, + int expectedCodeVersion, + int maximumFailedAttempts, + DateTimeOffset now, + CancellationToken cancellationToken = default); + + Task TryConsumeAsync( + TKey requestId, + int expectedCodeVersion, + DateTimeOffset now, + CancellationToken cancellationToken = default); + + Task SupersedePendingAsync( + TKey userId, + VerificationPurpose purpose, + VerificationChannel channel, + string normalizedDestination, + CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationSender.cs b/RuntimeApps.Authentication/Interface/IVerificationSender.cs new file mode 100644 index 0000000..47ca209 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationSender.cs @@ -0,0 +1,11 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IVerificationSender where TKey : IEquatable { + Task SendAsync( + VerificationCodeContext context, + string code, + DateTimeOffset expiresAt, + CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs b/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs new file mode 100644 index 0000000..10b092f --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs @@ -0,0 +1,23 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IVerificationWorkflowService where TKey : IEquatable { + Task StartAsync( + TUser user, + VerificationPurpose purpose, + VerificationChannel channel, + string destination, + string customPurpose = null, + string customChannel = null, + CancellationToken cancellationToken = default); + + Task ResendAsync( + string verificationHandle, + CancellationToken cancellationToken = default); + + Task> VerifyAsync( + string verificationHandle, + string code, + CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationChannel.cs b/RuntimeApps.Authentication/Model/VerificationChannel.cs new file mode 100644 index 0000000..ec3ecb1 --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationChannel.cs @@ -0,0 +1,9 @@ +namespace RuntimeApps.Authentication.Model { + /// Identifies the channel used to deliver or complete a verification request. + public enum VerificationChannel { + Email, + Sms, + Authenticator, + Custom + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationCodeContext.cs b/RuntimeApps.Authentication/Model/VerificationCodeContext.cs new file mode 100644 index 0000000..fbcd850 --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationCodeContext.cs @@ -0,0 +1,12 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class VerificationCodeContext where TKey : IEquatable { + public TUser User { get; init; } + public TKey UserId { get; init; } + public TKey RequestId { get; init; } + public VerificationPurpose Purpose { get; init; } + public VerificationChannel Channel { get; init; } + public string CustomPurpose { get; init; } + public string CustomChannel { get; init; } + public string Destination { get; init; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationOperationResult.cs b/RuntimeApps.Authentication/Model/VerificationOperationResult.cs new file mode 100644 index 0000000..2281777 --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationOperationResult.cs @@ -0,0 +1,15 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class VerificationOperationResult { + public bool Succeeded { get; init; } + public string VerificationHandle { get; init; } + public DateTimeOffset? ExpiresAt { get; init; } + public string ErrorCode { get; init; } + public string ErrorDescription { get; init; } + + public static VerificationOperationResult Success(string handle, DateTimeOffset expiresAt) => + new() { Succeeded = true, VerificationHandle = handle, ExpiresAt = expiresAt }; + + public static VerificationOperationResult Failure(string code, string description) => + new() { Succeeded = false, ErrorCode = code, ErrorDescription = description }; + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationOptions.cs b/RuntimeApps.Authentication/Model/VerificationOptions.cs new file mode 100644 index 0000000..ec11201 --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationOptions.cs @@ -0,0 +1,30 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class VerificationOptions { + public const string SectionName = "Authentication:Verification"; + + public int CodeLength { get; set; } = 6; + public TimeSpan CodeLifetime { get; set; } = TimeSpan.FromMinutes(10); + public int MaximumFailedAttempts { get; set; } = 5; + public TimeSpan ResendCooldown { get; set; } = TimeSpan.FromSeconds(60); + public int MaximumSendsPerHour { get; set; } = 5; + + /// + /// When true, external identities must complete the configured email verification workflow + /// before the library issues an application authentication token. Defaults to false. + /// + public bool RequireEmailVerificationForExternalLogins { get; set; } + + public void Validate() { + if(CodeLength is < 4 or > 12) + throw new InvalidOperationException("Verification code length must be between 4 and 12."); + if(CodeLifetime <= TimeSpan.Zero) + throw new InvalidOperationException("Verification code lifetime must be positive."); + if(MaximumFailedAttempts < 1) + throw new InvalidOperationException("Maximum failed attempts must be at least one."); + if(ResendCooldown < TimeSpan.Zero) + throw new InvalidOperationException("Resend cooldown cannot be negative."); + if(MaximumSendsPerHour < 1) + throw new InvalidOperationException("Maximum sends per hour must be at least one."); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationPurpose.cs b/RuntimeApps.Authentication/Model/VerificationPurpose.cs new file mode 100644 index 0000000..ca087d4 --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationPurpose.cs @@ -0,0 +1,11 @@ +namespace RuntimeApps.Authentication.Model { + /// Identifies the operation for which a verification request was created. + public enum VerificationPurpose { + Registration, + PasswordReset, + TwoFactor, + EmailChange, + PhoneChange, + Custom + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationRequest.cs b/RuntimeApps.Authentication/Model/VerificationRequest.cs new file mode 100644 index 0000000..cdddb0b --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationRequest.cs @@ -0,0 +1,26 @@ +namespace RuntimeApps.Authentication.Model { + /// + /// Persisted state for a verification operation. The raw public handle and verification code + /// must never be stored in this entity. + /// + public class VerificationRequest where TKey : IEquatable { + public TKey Id { get; set; } + public TKey UserId { get; set; } + public VerificationPurpose Purpose { get; set; } + public VerificationChannel Channel { get; set; } + public string CustomPurpose { get; set; } + public string CustomChannel { get; set; } + public string Destination { get; set; } + public string NormalizedDestination { get; set; } + public string PublicHandleHash { get; set; } + public string CodeVerifier { get; set; } + public int CodeVersion { get; set; } + public int FailedAttempts { get; set; } + public int SendCount { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset LastSentAt { get; set; } + public DateTimeOffset ExpiresAt { get; set; } + public DateTimeOffset? CompletedAt { get; set; } + public VerificationRequestStatus Status { get; set; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationRequestStatus.cs b/RuntimeApps.Authentication/Model/VerificationRequestStatus.cs new file mode 100644 index 0000000..b23248d --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationRequestStatus.cs @@ -0,0 +1,9 @@ +namespace RuntimeApps.Authentication.Model { + public enum VerificationRequestStatus { + Pending, + Completed, + Locked, + Expired, + Superseded + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerificationSend.cs b/RuntimeApps.Authentication/Model/VerificationSend.cs new file mode 100644 index 0000000..fb41bac --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerificationSend.cs @@ -0,0 +1,10 @@ +namespace RuntimeApps.Authentication.Model { + /// Immutable audit/rate-limit record for one attempted verification delivery. + public sealed class VerificationSend { + public long Id { get; set; } + public string NormalizedDestination { get; set; } + public VerificationPurpose Purpose { get; set; } + public VerificationChannel Channel { get; set; } + public DateTimeOffset SentAt { get; set; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj index 5a21fd9..3a763b9 100644 --- a/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj +++ b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj @@ -1,16 +1,16 @@ - + net10.0 enable - + + - - + \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index 42ce184..b35473f 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -49,6 +49,31 @@ public RuntimeAppsAuthenticationBuilder AddAuthenticationSer return this; } + /// + /// Registers the default verification workflow, secure code generation, and protected verifier. + /// The application must also register a persistent IVerificationRequestStore and a delivery sender. + /// + public RuntimeAppsAuthenticationBuilder AddVerificationServices( + Action configureOptions = null) { + Services.AddDataProtection(); + Services.AddOptions() + .Configure(options => configureOptions?.Invoke(options)) + .Validate(options => options.CodeLength is >= 4 and <= 12 && + options.CodeLifetime > TimeSpan.Zero && + options.MaximumFailedAttempts > 0 && + options.ResendCooldown >= TimeSpan.Zero && + options.MaximumSendsPerHour > 0, + "Verification options contain invalid values.") + .ValidateOnStart(); + + Services.Configure(options => options.SignIn.RequireConfirmedEmail = true); + Services.TryAddSingleton(TimeProvider.System); + Services.TryAddScoped, RandomVerificationCodeGenerator>(); + Services.TryAddScoped, DataProtectionVerificationCodeVerifier>(); + Services.TryAddScoped, VerificationWorkflowService>(); + return this; + } + public RuntimeAppsAuthenticationBuilder UseJwt(string authenticationScheme, Action configureOptions) { Services.TryAddScoped, JwtProvider>(); Services.Configure(configureOptions); diff --git a/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs b/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs new file mode 100644 index 0000000..b7ee7ab --- /dev/null +++ b/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs @@ -0,0 +1,77 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Service { + /// + /// Protects verification codes with ASP.NET Core Data Protection and binds them to + /// the request, user, purpose, channel, and destination. + /// + public sealed class DataProtectionVerificationCodeVerifier : IVerificationCodeVerifier + where TKey : IEquatable { + private readonly IDataProtector _protector; + + public DataProtectionVerificationCodeVerifier(IDataProtectionProvider provider) { + ArgumentNullException.ThrowIfNull(provider); + _protector = provider.CreateProtector("RuntimeApps.Authentication.VerificationCode.v1"); + } + + public string CreateVerifier(string code, VerificationRequest request) { + ArgumentException.ThrowIfNullOrEmpty(code); + ArgumentNullException.ThrowIfNull(request); + + var payload = JsonSerializer.Serialize(new VerificationCodePayload( + Convert.ToString(request.Id), + Convert.ToString(request.UserId), + request.Purpose, + request.Channel, + request.CustomPurpose, + request.CustomChannel, + request.NormalizedDestination, + code)); + + return _protector.Protect(payload); + } + + public bool Verify(string code, VerificationRequest request) { + if(string.IsNullOrEmpty(code) || request?.CodeVerifier == null) + return false; + + try { + var payload = JsonSerializer.Deserialize( + _protector.Unprotect(request.CodeVerifier)); + if(payload == null || + payload.RequestId != Convert.ToString(request.Id) || + payload.UserId != Convert.ToString(request.UserId) || + payload.Purpose != request.Purpose || + payload.Channel != request.Channel || + payload.CustomPurpose != request.CustomPurpose || + payload.CustomChannel != request.CustomChannel || + payload.Destination != request.NormalizedDestination) + return false; + + var expected = Encoding.UTF8.GetBytes(payload.Code); + var supplied = Encoding.UTF8.GetBytes(code); + return expected.Length == supplied.Length && + CryptographicOperations.FixedTimeEquals(expected, supplied); + } catch(CryptographicException) { + return false; + } catch(JsonException) { + return false; + } + } + + private sealed record VerificationCodePayload( + string RequestId, + string UserId, + VerificationPurpose Purpose, + VerificationChannel Channel, + string CustomPurpose, + string CustomChannel, + string Destination, + string Code); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/RandomVerificationCodeGenerator.cs b/RuntimeApps.Authentication/Service/RandomVerificationCodeGenerator.cs new file mode 100644 index 0000000..a764a4a --- /dev/null +++ b/RuntimeApps.Authentication/Service/RandomVerificationCodeGenerator.cs @@ -0,0 +1,24 @@ +using System.Security.Cryptography; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Service { + public sealed class RandomVerificationCodeGenerator : IVerificationCodeGenerator + where TKey : IEquatable { + public Task GenerateAsync( + VerificationCodeContext context, + VerificationOptions options, + CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(options); + options.Validate(); + + cancellationToken.ThrowIfCancellationRequested(); + var characters = new char[options.CodeLength]; + for(var index = 0; index < characters.Length; index++) + characters[index] = (char)('0' + RandomNumberGenerator.GetInt32(0, 10)); + + return Task.FromResult(new string(characters)); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/VerificationHandle.cs b/RuntimeApps.Authentication/Service/VerificationHandle.cs new file mode 100644 index 0000000..967fe68 --- /dev/null +++ b/RuntimeApps.Authentication/Service/VerificationHandle.cs @@ -0,0 +1,17 @@ +using System.Security.Cryptography; +using System.Text; + +namespace RuntimeApps.Authentication.Service { + /// Creates opaque public verification handles and their persisted SHA-256 lookup hashes. + public static class VerificationHandle { + public static string Create() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); + + public static string ComputeHash(string handle) { + ArgumentException.ThrowIfNullOrWhiteSpace(handle); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(handle))); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs new file mode 100644 index 0000000..a425052 --- /dev/null +++ b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs @@ -0,0 +1,185 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Service { + public sealed class VerificationWorkflowService : IVerificationWorkflowService + where TUser : IdentityUser + where TKey : IEquatable { + private readonly IVerificationRequestStore _store; + private readonly IVerificationCodeGenerator _generator; + private readonly IVerificationCodeVerifier _verifier; + private readonly IVerificationSender _sender; + private readonly IUserManager _userManager; + private readonly ILookupNormalizer _normalizer; + private readonly VerificationOptions _options; + private readonly TimeProvider _timeProvider; + + public VerificationWorkflowService( + IVerificationRequestStore store, + IVerificationCodeGenerator generator, + IVerificationCodeVerifier verifier, + IVerificationSender sender, + IUserManager userManager, + ILookupNormalizer normalizer, + IOptions options, + TimeProvider timeProvider = null) { + _store = store ?? throw new ArgumentNullException(nameof(store)); + _generator = generator ?? throw new ArgumentNullException(nameof(generator)); + _verifier = verifier ?? throw new ArgumentNullException(nameof(verifier)); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); + _normalizer = normalizer ?? throw new ArgumentNullException(nameof(normalizer)); + _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + _options.Validate(); + _timeProvider = timeProvider ?? TimeProvider.System; + } + + public async Task StartAsync( + TUser user, + VerificationPurpose purpose, + VerificationChannel channel, + string destination, + string customPurpose = null, + string customChannel = null, + CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(user); + ArgumentException.ThrowIfNullOrWhiteSpace(destination); + _options.Validate(); + + var now = _timeProvider.GetUtcNow(); + var normalizedDestination = NormalizeDestination(destination, channel); + var handle = VerificationHandle.Create(); + var request = new VerificationRequest { + UserId = user.Id, + Purpose = purpose, + Channel = channel, + CustomPurpose = customPurpose, + CustomChannel = customChannel, + Destination = destination.Trim(), + NormalizedDestination = normalizedDestination, + PublicHandleHash = VerificationHandle.ComputeHash(handle), + CodeVerifier = string.Empty, + CodeVersion = 0, + FailedAttempts = 0, + SendCount = 1, + CreatedAt = now, + LastSentAt = now, + ExpiresAt = now.Add(_options.CodeLifetime), + Status = VerificationRequestStatus.Pending + }; + + if(!await _store.TryCreateAsync( + request, now.AddHours(-1), _options.MaximumSendsPerHour, cancellationToken)) + return VerificationOperationResult.Failure("VerificationRateLimited", "The verification send limit has been reached."); + + var context = CreateContext(user, request); + var code = await _generator.GenerateAsync(context, _options, cancellationToken); + var protectedVerifier = _verifier.CreateVerifier(code, request); + + if(!await _store.TrySetInitialVerifierAsync( + request.Id, protectedVerifier, now, request.ExpiresAt, cancellationToken)) + return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request could not be initialized."); + + await _sender.SendAsync(context, code, request.ExpiresAt, cancellationToken); + return VerificationOperationResult.Success(handle, request.ExpiresAt); + } + + public async Task ResendAsync( + string verificationHandle, + CancellationToken cancellationToken = default) { + if(string.IsNullOrWhiteSpace(verificationHandle)) + return VerificationOperationResult.Failure("InvalidVerificationHandle", "The verification request is invalid."); + + var request = await _store.FindByHandleHashAsync( + VerificationHandle.ComputeHash(verificationHandle), cancellationToken); + var now = _timeProvider.GetUtcNow(); + + if(request == null || request.Status != VerificationRequestStatus.Pending) + return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId)); + if(user == null) + return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + var context = CreateContext(user, request); + var code = await _generator.GenerateAsync(context, _options, cancellationToken); + var newVerifier = _verifier.CreateVerifier(code, request); + var expiresAt = now.Add(_options.CodeLifetime); + + if(!await _store.TryResendAsync( + request.Id, + request.CodeVersion, + newVerifier, + now, + expiresAt, + _options.ResendCooldown, + now.AddHours(-1), + _options.MaximumSendsPerHour, + cancellationToken)) + return VerificationOperationResult.Failure("VerificationResendUnavailable", "The verification request cannot be resent yet."); + + await _sender.SendAsync(context, code, expiresAt, cancellationToken); + return VerificationOperationResult.Success(verificationHandle, expiresAt); + } + + public async Task> VerifyAsync( + string verificationHandle, + string code, + CancellationToken cancellationToken = default) { + if(string.IsNullOrWhiteSpace(verificationHandle) || string.IsNullOrWhiteSpace(code)) + return Failure("InvalidVerificationCode", "The verification code is invalid."); + + var request = await _store.FindByHandleHashAsync( + VerificationHandle.ComputeHash(verificationHandle), cancellationToken); + var now = _timeProvider.GetUtcNow(); + + if(request == null || request.Status != VerificationRequestStatus.Pending || request.ExpiresAt <= now) + return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + if(!_verifier.Verify(code, request)) { + await _store.TryIncrementFailedAttemptsAsync( + request.Id, request.CodeVersion, _options.MaximumFailedAttempts, now, cancellationToken); + return Failure("InvalidVerificationCode", "The verification code is invalid."); + } + + if(!await _store.TryConsumeAsync(request.Id, request.CodeVersion, now, cancellationToken)) + return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId)); + if(user == null) + return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + if(request.Purpose == VerificationPurpose.Registration || + request.Purpose == VerificationPurpose.EmailChange) + user.EmailConfirmed = true; + + var updateResult = await _userManager.UpdateAsync(user); + if(!updateResult.Succeeded) + return new Result(ResultCode.BadRequest, updateResult.Errors); + + return new Result(user); + } + + private string NormalizeDestination(string destination, VerificationChannel channel) => + channel == VerificationChannel.Email + ? _normalizer.NormalizeEmail(destination.Trim()) + : destination.Trim(); + + private VerificationCodeContext CreateContext(TUser user, VerificationRequest request) => + new() { + User = user, + UserId = user.Id, + RequestId = request.Id, + Purpose = request.Purpose, + Channel = request.Channel, + CustomPurpose = request.CustomPurpose, + CustomChannel = request.CustomChannel, + Destination = request.Destination + }; + + private static Result Failure(string code, string description) => + new(ResultCode.BadRequest, Result.CreateErrors(code, description)); + } +} \ No newline at end of file diff --git a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs new file mode 100644 index 0000000..c4c1623 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs @@ -0,0 +1,41 @@ +using RuntimeApps.Authentication.Model; +using RuntimeApps.Authentication.Service; + +namespace RuntimeApps.Authentication.Test { + public class VerificationPrimitivesTest { + [Fact] + public void VerificationHandle_Create_ReturnsIndependentOpaqueValues() { + var first = VerificationHandle.Create(); + var second = VerificationHandle.Create(); + + Assert.NotEqual(first, second); + Assert.Equal(64, VerificationHandle.ComputeHash(first).Length); + Assert.NotEqual(VerificationHandle.ComputeHash(first), VerificationHandle.ComputeHash(second)); + } + + [Fact] + public async Task RandomVerificationCodeGenerator_GeneratesConfiguredNumericCode() { + var generator = new RandomVerificationCodeGenerator(); + var options = new VerificationOptions { CodeLength = 6 }; + var context = new VerificationCodeContext { + UserId = "user-1", + RequestId = "request-1", + Purpose = VerificationPurpose.Registration, + Channel = VerificationChannel.Email, + Destination = "person@example.com" + }; + + var code = await generator.GenerateAsync(context, options); + + Assert.Equal(6, code.Length); + Assert.All(code, character => Assert.InRange(character, '0', '9')); + } + + [Fact] + public void VerificationOptions_RejectsInvalidSecurityLimits() { + var options = new VerificationOptions { MaximumFailedAttempts = 0 }; + + Assert.Throws(() => options.Validate()); + } + } +} \ No newline at end of file From 500df9b7035d343065d7acec0931a98f2f8cee1c Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Wed, 18 Nov 2026 23:31:35 +0100 Subject: [PATCH 02/18] Require email verification for public registration --- ...ccountApiEndpointRouteBuilderExtensions.cs | 50 +++++++- .../Interface/IRegistrationService.cs | 14 +++ .../Interface/IUserAccountService.cs | 6 +- .../Interface/IUserRegistrationUpdater.cs | 6 + .../Interface/IVerificationWorkflowService.cs | 4 + .../Model/RegistrationVerificationResponse.cs | 7 ++ .../ResendRegistrationVerificationModel.cs | 5 + .../Model/VerifyRegistrationModel.cs | 6 + .../RuntimeAppsAuthenticationBuilder.cs | 2 + .../Service/DefaultUserRegistrationUpdater.cs | 30 +++++ .../Service/RegistrationService.cs | 116 ++++++++++++++++++ .../Service/UserAccountService.cs | 14 +-- .../Service/VerificationWorkflowService.cs | 20 +-- .../UserAccountServiceTest.cs | 73 ++--------- 14 files changed, 270 insertions(+), 83 deletions(-) create mode 100644 RuntimeApps.Authentication/Interface/IRegistrationService.cs create mode 100644 RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs create mode 100644 RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs create mode 100644 RuntimeApps.Authentication/Model/ResendRegistrationVerificationModel.cs create mode 100644 RuntimeApps.Authentication/Model/VerifyRegistrationModel.cs create mode 100644 RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs create mode 100644 RuntimeApps.Authentication/Service/RegistrationService.cs diff --git a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index c2afa33..b8d7e4f 100644 --- a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs @@ -45,18 +45,62 @@ public static IEndpointRouteBuilder MapLoginApi(this IEnd } public static IEndpointRouteBuilder MapRegisterApi(this IEndpointRouteBuilder endpoints) - where TUser : IdentityUser + where TUser : IdentityUser, new() where TUserDto : class where TKey : IEquatable { + var serviceAvailability = endpoints.ServiceProvider.GetRequiredService(); + var requiredServices = new[] { + typeof(IRegistrationService), + typeof(IVerificationWorkflowService), + typeof(IVerificationRequestStore), + typeof(IVerificationSender), + typeof(IUserAccountService), + typeof(IUserMapper) + }; + var missingServices = requiredServices.Where(type => !serviceAvailability.IsService(type)).ToArray(); + if(missingServices.Length > 0) + throw new InvalidOperationException( + "Registration endpoints require verification services, a persistent verification request store, " + + "a verification sender, an account service, and a user mapper. Missing: " + + string.Join(", ", missingServices.Select(type => type.Name))); + var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("register", async Task>, ValidationProblem>> ([FromBody] RegisterUserModel user, IUserAccountService userAccountService, [FromServices] IUserMapper mapper) => { - var result = await userAccountService.RegisterAsync(mapper.ToUser(user.UserInfo), user.Password); + routeGroup.MapPost("register", async Task>, ValidationProblem>> ( + [FromBody] RegisterUserModel user, + IRegistrationService registrationService, + [FromServices] IUserMapper mapper, + HttpContext httpContext) => { + var result = await registrationService.RegisterAsync( + mapper.ToUser(user.UserInfo), user.Password, httpContext.RequestAborted); + if(!result.Succeeded) + return result.CreateValidationProblem(); + return TypedResults.Accepted(value: result); + }); + + routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( + [FromBody] VerifyRegistrationModel request, + IRegistrationService registrationService, + [FromServices] IUserMapper mapper, + HttpContext httpContext) => { + var result = await registrationService.VerifyAsync( + request.VerificationHandle, request.Code, httpContext.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); return TypedResults.Ok(MapResult(result, mapper)); }); + routeGroup.MapPost("register/resend", async Task>, ValidationProblem>> ( + [FromBody] ResendRegistrationVerificationModel request, + IRegistrationService registrationService, + HttpContext httpContext) => { + var result = await registrationService.ResendAsync( + request.VerificationHandle, httpContext.RequestAborted); + if(!result.Succeeded) + return result.CreateValidationProblem(); + return TypedResults.Accepted(value: result); + }); + return endpoints; } diff --git a/RuntimeApps.Authentication/Interface/IRegistrationService.cs b/RuntimeApps.Authentication/Interface/IRegistrationService.cs new file mode 100644 index 0000000..7b121a1 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IRegistrationService.cs @@ -0,0 +1,14 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IRegistrationService where TKey : IEquatable { + Task> RegisterAsync( + TUser user, string password, CancellationToken cancellationToken = default); + + Task> VerifyAsync( + string verificationHandle, string code, CancellationToken cancellationToken = default); + + Task> ResendAsync( + string verificationHandle, CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IUserAccountService.cs b/RuntimeApps.Authentication/Interface/IUserAccountService.cs index ed68748..61d25c4 100644 --- a/RuntimeApps.Authentication/Interface/IUserAccountService.cs +++ b/RuntimeApps.Authentication/Interface/IUserAccountService.cs @@ -1,9 +1,9 @@ -using RuntimeApps.Authentication.Model; +using RuntimeApps.Authentication.Model; namespace RuntimeApps.Authentication.Interface { public interface IUserAccountService { - Task> RegisterAsync(TUser user, string password); + Task> CompleteRegistrationAsync(TUser user); Task> LoginAsync(string userName, string password); Task> ExternalLoginAsync(string provider, string token); } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs b/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs new file mode 100644 index 0000000..99177ee --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs @@ -0,0 +1,6 @@ +namespace RuntimeApps.Authentication.Interface { + /// Copies only explicitly permitted, non-credential fields to an existing pending account. + public interface IUserRegistrationUpdater { + Task UpdatePendingUserAsync(TUser existingUser, TUser requestedUser, CancellationToken cancellationToken = default); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs b/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs index 10b092f..51fe2d9 100644 --- a/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs @@ -13,11 +13,15 @@ Task StartAsync( Task ResendAsync( string verificationHandle, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, CancellationToken cancellationToken = default); Task> VerifyAsync( string verificationHandle, string code, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs new file mode 100644 index 0000000..c9e5341 --- /dev/null +++ b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs @@ -0,0 +1,7 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class RegistrationVerificationResponse { + public string Message { get; init; } = "If the account can be registered, a verification message will be sent."; + public string VerificationHandle { get; init; } + public DateTimeOffset ExpiresAt { get; init; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/ResendRegistrationVerificationModel.cs b/RuntimeApps.Authentication/Model/ResendRegistrationVerificationModel.cs new file mode 100644 index 0000000..d949482 --- /dev/null +++ b/RuntimeApps.Authentication/Model/ResendRegistrationVerificationModel.cs @@ -0,0 +1,5 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class ResendRegistrationVerificationModel { + public string VerificationHandle { get; set; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/VerifyRegistrationModel.cs b/RuntimeApps.Authentication/Model/VerifyRegistrationModel.cs new file mode 100644 index 0000000..d3f6abb --- /dev/null +++ b/RuntimeApps.Authentication/Model/VerifyRegistrationModel.cs @@ -0,0 +1,6 @@ +namespace RuntimeApps.Authentication.Model { + public sealed class VerifyRegistrationModel { + public string VerificationHandle { get; set; } + public string Code { get; set; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index b35473f..55c44af 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -71,6 +71,8 @@ public RuntimeAppsAuthenticationBuilder AddVerificationServi Services.TryAddScoped, RandomVerificationCodeGenerator>(); Services.TryAddScoped, DataProtectionVerificationCodeVerifier>(); Services.TryAddScoped, VerificationWorkflowService>(); + Services.TryAddScoped, DefaultUserRegistrationUpdater>(); + Services.TryAddScoped, RegistrationService>(); return this; } diff --git a/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs b/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs new file mode 100644 index 0000000..2ed7bfb --- /dev/null +++ b/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Identity; +using RuntimeApps.Authentication.Interface; + +namespace RuntimeApps.Authentication.Service { + /// + /// Updates only username and phone number on an existing pending Identity account. + /// Passwords, email ownership, roles, claims, security stamps, and external logins are not copied. + /// + public sealed class DefaultUserRegistrationUpdater : IUserRegistrationUpdater + where TUser : IdentityUser + where TKey : IEquatable { + public Task UpdatePendingUserAsync( + TUser existingUser, + TUser requestedUser, + CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(existingUser); + ArgumentNullException.ThrowIfNull(requestedUser); + + if(!string.IsNullOrWhiteSpace(requestedUser.UserName)) + existingUser.UserName = requestedUser.UserName; + + if(existingUser.PhoneNumber != requestedUser.PhoneNumber) { + existingUser.PhoneNumber = requestedUser.PhoneNumber; + existingUser.PhoneNumberConfirmed = false; + } + + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/RegistrationService.cs b/RuntimeApps.Authentication/Service/RegistrationService.cs new file mode 100644 index 0000000..ad2872b --- /dev/null +++ b/RuntimeApps.Authentication/Service/RegistrationService.cs @@ -0,0 +1,116 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Service { + public sealed class RegistrationService : IRegistrationService + where TUser : IdentityUser, new() + where TKey : IEquatable { + private readonly IUserManager _userManager; + private readonly IUserRegistrationUpdater _userUpdater; + private readonly IVerificationWorkflowService _verification; + private readonly IUserAccountService _accountService; + private readonly VerificationOptions _options; + private readonly TimeProvider _timeProvider; + + public RegistrationService( + IUserManager userManager, + IUserRegistrationUpdater userUpdater, + IVerificationWorkflowService verification, + IUserAccountService accountService, + IOptions options, + TimeProvider timeProvider = null) { + _userManager = userManager; + _userUpdater = userUpdater; + _verification = verification; + _accountService = accountService; + _options = options.Value; + _timeProvider = timeProvider ?? TimeProvider.System; + } + + public async Task> RegisterAsync( + TUser user, string password, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(user); + if(string.IsNullOrWhiteSpace(user.Email) || string.IsNullOrEmpty(password)) + return Failure("InvalidRegistration", "Email and password are required."); + + if(string.IsNullOrWhiteSpace(user.UserName)) + user.UserName = user.Email; + + var existingUser = await _userManager.FindByEmailAsync(user.Email); + if(existingUser?.EmailConfirmed == true) + return GenericResponse(); + + if(existingUser != null) { + await _userUpdater.UpdatePendingUserAsync(existingUser, user, cancellationToken); + var updateResult = await _userManager.UpdateAsync(existingUser); + if(!updateResult.Succeeded) + return new Result(ResultCode.BadRequest, updateResult.Errors); + user = existingUser; + } else { + user.EmailConfirmed = false; + var createResult = await _userManager.CreateAsync(user, password); + if(!createResult.Succeeded) { + // A concurrent registration may have created the account after our initial lookup. + var racedUser = await _userManager.FindByEmailAsync(user.Email); + if(racedUser?.EmailConfirmed == true) + return GenericResponse(); + if(racedUser == null) + return new Result(ResultCode.BadRequest, createResult.Errors); + + await _userUpdater.UpdatePendingUserAsync(racedUser, user, cancellationToken); + var updateResult = await _userManager.UpdateAsync(racedUser); + if(!updateResult.Succeeded) + return new Result(ResultCode.BadRequest, updateResult.Errors); + user = racedUser; + } + } + + user.EmailConfirmed = false; + var verificationResult = await _verification.StartAsync( + user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, + cancellationToken: cancellationToken); + + if(!verificationResult.Succeeded) + return Failure(verificationResult.ErrorCode, verificationResult.ErrorDescription); + + return new Result(new RegistrationVerificationResponse { + VerificationHandle = verificationResult.VerificationHandle, + ExpiresAt = verificationResult.ExpiresAt!.Value + }); + } + + public async Task> VerifyAsync( + string verificationHandle, string code, CancellationToken cancellationToken = default) { + var verificationResult = await _verification.VerifyAsync( + verificationHandle, code, VerificationPurpose.Registration, VerificationChannel.Email, cancellationToken); + if(!verificationResult.Succeeded) + return new Result(verificationResult.Code, verificationResult.Errors); + + return await _accountService.CompleteRegistrationAsync(verificationResult.Data); + } + + public async Task> ResendAsync( + string verificationHandle, CancellationToken cancellationToken = default) { + var result = await _verification.ResendAsync( + verificationHandle, VerificationPurpose.Registration, VerificationChannel.Email, cancellationToken); + if(!result.Succeeded) + return Failure(result.ErrorCode, result.ErrorDescription); + + return new Result(new RegistrationVerificationResponse { + VerificationHandle = result.VerificationHandle, + ExpiresAt = result.ExpiresAt!.Value + }); + } + + private Result GenericResponse() => + new(new RegistrationVerificationResponse { + VerificationHandle = VerificationHandle.Create(), + ExpiresAt = _timeProvider.GetUtcNow().Add(_options.CodeLifetime) + }); + + private static Result Failure(string code, string description) => + new(ResultCode.BadRequest, Result.CreateErrors(code, description)); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/UserAccountService.cs b/RuntimeApps.Authentication/Service/UserAccountService.cs index 000820a..37ee878 100644 --- a/RuntimeApps.Authentication/Service/UserAccountService.cs +++ b/RuntimeApps.Authentication/Service/UserAccountService.cs @@ -103,15 +103,13 @@ public virtual async Task> LoginAsync(string userName, stri return await GenerateTokenAsync(userInfo); } - public virtual async Task> RegisterAsync(TUser user, string password) { - if(string.IsNullOrEmpty(user.UserName)) - user.UserName = user.Email; + public virtual Task> CompleteRegistrationAsync(TUser user) { + if(user == null || !user.EmailConfirmed) + return Task.FromResult(new Result( + ResultCode.Forbidden, + Result.CreateErrors("EmailNotConfirmed", "The account must complete email verification before registration can be completed."))); - var createResult = await _userManager.CreateAsync(user, password); - if(!createResult.Succeeded) - return new Result(ResultCode.BadRequest, createResult.Errors); - - return await GenerateTokenAsync(user); + return GenerateTokenAsync(user); } protected virtual Result GetIdentityError(SignInResult signInResult) { diff --git a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs index a425052..d4bc744 100644 --- a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs @@ -49,7 +49,9 @@ public async Task StartAsync( _options.Validate(); var now = _timeProvider.GetUtcNow(); - var normalizedDestination = NormalizeDestination(destination, channel); + var normalizedDestination = channel == VerificationChannel.Email + ? _normalizer.NormalizeEmail(destination.Trim()) + : destination.Trim(); var handle = VerificationHandle.Create(); var request = new VerificationRequest { UserId = user.Id, @@ -88,6 +90,8 @@ public async Task StartAsync( public async Task ResendAsync( string verificationHandle, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, CancellationToken cancellationToken = default) { if(string.IsNullOrWhiteSpace(verificationHandle)) return VerificationOperationResult.Failure("InvalidVerificationHandle", "The verification request is invalid."); @@ -96,7 +100,8 @@ public async Task ResendAsync( VerificationHandle.ComputeHash(verificationHandle), cancellationToken); var now = _timeProvider.GetUtcNow(); - if(request == null || request.Status != VerificationRequestStatus.Pending) + if(request == null || request.Status != VerificationRequestStatus.Pending || + request.Purpose != expectedPurpose || request.Channel != expectedChannel) return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId)); @@ -127,6 +132,8 @@ public async Task ResendAsync( public async Task> VerifyAsync( string verificationHandle, string code, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, CancellationToken cancellationToken = default) { if(string.IsNullOrWhiteSpace(verificationHandle) || string.IsNullOrWhiteSpace(code)) return Failure("InvalidVerificationCode", "The verification code is invalid."); @@ -135,7 +142,9 @@ public async Task> VerifyAsync( VerificationHandle.ComputeHash(verificationHandle), cancellationToken); var now = _timeProvider.GetUtcNow(); - if(request == null || request.Status != VerificationRequestStatus.Pending || request.ExpiresAt <= now) + if(request == null || request.Status != VerificationRequestStatus.Pending || + request.Purpose != expectedPurpose || request.Channel != expectedChannel || + request.ExpiresAt <= now) return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); if(!_verifier.Verify(code, request)) { @@ -162,11 +171,6 @@ await _store.TryIncrementFailedAttemptsAsync( return new Result(user); } - private string NormalizeDestination(string destination, VerificationChannel channel) => - channel == VerificationChannel.Email - ? _normalizer.NormalizeEmail(destination.Trim()) - : destination.Trim(); - private VerificationCodeContext CreateContext(TUser user, VerificationRequest request) => new() { User = user, diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index aa6c095..50d700e 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -113,79 +113,30 @@ public async Task Login_WrongPassword() { } [Fact] - public async Task Register_Success() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - var token = new Model.Token() { + public async Task CompleteRegistration_Success_ConfirmedUser() { + var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = true }; + var token = new Model.Token { AuthenticationToken = "", ExpireDate = DateTimeOffset.Now.AddDays(30), }; - _userManagerMock.Setup(u => u.FindByNameAsync(user.Email)) - .ReturnsAsync(nullUSer); - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) - .ReturnsAsync(token); + _jwtProviderMock.Setup(provider => provider.GenerateTokenAsync(user)).ReturnsAsync(token); - //Act - var result = await _userAccountService.RegisterAsync(user, password); + var result = await _userAccountService.CompleteRegistrationAsync(user); - //Assert result.Succeeded.Should().BeTrue(); - result.Data.Should().NotBeNull() - .And.Be(user); - result.Data.UserName.Should().Be(result.Data.Email); - result.Meta.Should().NotBeNull() - .And.Be(token); + result.Data.Should().Be(user); + result.Meta.Should().Be(token); } [Fact] - public async Task Register_UserExist() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Failed(new IdentityError { - Code = "Failed", - Description = "User Exist!" - })); + public async Task CompleteRegistration_UnconfirmedUser_IsRejected() { + var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = false }; - //Act - var result = await _userAccountService.RegisterAsync(user, password); - - //Assert - result.Succeeded.Should().BeFalse(); - result.Data.Should().BeNull(); - result.Meta.Should().BeNull(); - } - - [Fact] - public async Task Register_ValidateError() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Failed(new IdentityError[] { - new IdentityError { - Code = "InvalidPassword", - Description = "Password must be more than 6 character" - } - })); + var result = await _userAccountService.CompleteRegistrationAsync(user); - //Act - var result = await _userAccountService.RegisterAsync(user, password); - - //Assert result.Succeeded.Should().BeFalse(); - result.Data.Should().BeNull(); - result.Meta.Should().BeNull(); + result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Forbidden); + _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); } [Fact] From 52edcbb0852efd7970b9325a2a33c24aec17e4a1 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Wed, 18 Nov 2026 23:34:27 +0100 Subject: [PATCH 03/18] Harden external login email trust and account linking --- .../IExternalLoginEmailTrustPolicy.cs | 7 ++ .../Interface/IExternalLoginProvider.cs | 9 +- .../Model/ExternalLoginProviderResult.cs | 11 +++ RuntimeApps.Authentication/Model/Token.cs | 7 ++ .../RuntimeAppsAuthenticationBuilder.cs | 1 + .../DefaultExternalLoginEmailTrustPolicy.cs | 29 ++++++ .../FacebookExternalLoginProvider.cs | 2 +- .../GoogleExternalLoginProvider.cs | 4 +- .../MicrosoftExternalLoginProvider.cs | 2 +- .../Service/UserAccountService.cs | 79 +++++++++++++--- .../ExternalLoginEmailTrustPolicyTest.cs | 47 ++++++++++ .../UserAccountServiceTest.cs | 93 +++++++++++++++---- 12 files changed, 254 insertions(+), 37 deletions(-) create mode 100644 RuntimeApps.Authentication/Interface/IExternalLoginEmailTrustPolicy.cs create mode 100644 RuntimeApps.Authentication/Model/ExternalLoginProviderResult.cs create mode 100644 RuntimeApps.Authentication/Service/DefaultExternalLoginEmailTrustPolicy.cs create mode 100644 Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs diff --git a/RuntimeApps.Authentication/Interface/IExternalLoginEmailTrustPolicy.cs b/RuntimeApps.Authentication/Interface/IExternalLoginEmailTrustPolicy.cs new file mode 100644 index 0000000..87b98e6 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IExternalLoginEmailTrustPolicy.cs @@ -0,0 +1,7 @@ +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Interface { + public interface IExternalLoginEmailTrustPolicy where TUser : class { + bool IsEmailTrusted(string provider, ExternalLoginProviderResult result); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Interface/IExternalLoginProvider.cs b/RuntimeApps.Authentication/Interface/IExternalLoginProvider.cs index a22e984..883f4ce 100644 --- a/RuntimeApps.Authentication/Interface/IExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Interface/IExternalLoginProvider.cs @@ -1,9 +1,8 @@ -using Microsoft.AspNetCore.Identity; +using RuntimeApps.Authentication.Model; namespace RuntimeApps.Authentication.Interface { - public interface IExternalLoginProvider - where TUser : class { + public interface IExternalLoginProvider where TUser : class { string Provider { get; } - Task<(TUser, UserLoginInfo)> ValidateAsync(string token); + Task> ValidateAsync(string token); } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/ExternalLoginProviderResult.cs b/RuntimeApps.Authentication/Model/ExternalLoginProviderResult.cs new file mode 100644 index 0000000..2e38384 --- /dev/null +++ b/RuntimeApps.Authentication/Model/ExternalLoginProviderResult.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Identity; + +namespace RuntimeApps.Authentication.Model { + public sealed class ExternalLoginProviderResult where TUser : class { + public TUser User { get; init; } + public UserLoginInfo LoginInfo { get; init; } + public string Email { get; init; } + public bool EmailVerified { get; init; } + public string HostedDomain { get; init; } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Model/Token.cs b/RuntimeApps.Authentication/Model/Token.cs index f74cf42..29a55b6 100644 --- a/RuntimeApps.Authentication/Model/Token.cs +++ b/RuntimeApps.Authentication/Model/Token.cs @@ -12,5 +12,12 @@ public class Token { /// Identifies the authenticated session, not a secret. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Guid? SessionId { get; set; } + /// True when external authentication succeeded but email verification is still required. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool VerificationRequired { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string VerificationHandle { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeOffset? VerificationExpiresAt { get; set; } } } \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index 55c44af..17ef441 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -24,6 +24,7 @@ public RuntimeAppsAuthenticationBuilder(AuthenticationBuilder authenticationBuil public RuntimeAppsAuthenticationBuilder AddAuthenticationServices() { Services.TryAddScoped, UserAccountService>(); + Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); Services.AddHttpContextAccessor(); // Identity services diff --git a/RuntimeApps.Authentication/Service/DefaultExternalLoginEmailTrustPolicy.cs b/RuntimeApps.Authentication/Service/DefaultExternalLoginEmailTrustPolicy.cs new file mode 100644 index 0000000..29110ae --- /dev/null +++ b/RuntimeApps.Authentication/Service/DefaultExternalLoginEmailTrustPolicy.cs @@ -0,0 +1,29 @@ +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Service { + /// + /// Trusts verified Google Gmail/Googlemail addresses and verified Google Workspace addresses + /// whose email domain matches the token's hosted-domain claim. Other providers require a custom policy. + /// + public sealed class DefaultExternalLoginEmailTrustPolicy : IExternalLoginEmailTrustPolicy + where TUser : class { + public bool IsEmailTrusted(string provider, ExternalLoginProviderResult result) { + if(result == null || !result.EmailVerified || string.IsNullOrWhiteSpace(result.Email) || + !string.Equals(provider, "GOOGLE", StringComparison.OrdinalIgnoreCase)) + return false; + + var at = result.Email.LastIndexOf('@'); + if(at <= 0 || at == result.Email.Length - 1) + return false; + + var emailDomain = result.Email[(at + 1)..]; + if(emailDomain.Equals("gmail.com", StringComparison.OrdinalIgnoreCase) || + emailDomain.Equals("googlemail.com", StringComparison.OrdinalIgnoreCase)) + return true; + + return !string.IsNullOrWhiteSpace(result.HostedDomain) && + emailDomain.Equals(result.HostedDomain, StringComparison.OrdinalIgnoreCase); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs index 669eec8..f7c0a33 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs @@ -16,7 +16,7 @@ public FacebookExternalLoginProvider(IOptions public string Provider => "FACEBOOK"; - public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { + public async Task> ValidateAsync(string token) { var option = _options.Value; using HttpClient httpClient = new HttpClient(); diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs index 8c5579f..5449b3d 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs @@ -18,7 +18,7 @@ public GoogleExternalLoginProvider(ILogger> l public string Provider => "GOOGLE"; - public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { + public async Task> ValidateAsync(string token) { try { var option = _option.Value; var settings = new GoogleJsonWebSignature.ValidationSettings() { @@ -27,7 +27,7 @@ public GoogleExternalLoginProvider(ILogger> l GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(token, settings); var user = option.Mapper(payload); var userLogin = new UserLoginInfo(Provider, payload.Subject, Provider); - return (user, userLogin); + return new ExternalLoginProviderResult {\n User = user,\n LoginInfo = userLogin,\n Email = payload.Email,\n EmailVerified = payload.EmailVerified,\n HostedDomain = payload.HostedDomain\n }; } catch(Exception ex) { _logger.LogError(ex, ex.Message); return (null, null); diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs index ac5d315..98ab13a 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs @@ -17,7 +17,7 @@ public MicrosoftExternalLoginProvider(IOptions "MICROSOFT"; - public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { + public async Task> ValidateAsync(string token) { var option = _options.Value; var openidConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync( diff --git a/RuntimeApps.Authentication/Service/UserAccountService.cs b/RuntimeApps.Authentication/Service/UserAccountService.cs index 37ee878..d3565a8 100644 --- a/RuntimeApps.Authentication/Service/UserAccountService.cs +++ b/RuntimeApps.Authentication/Service/UserAccountService.cs @@ -19,6 +19,9 @@ public class UserAccountService: IUserAccountService private readonly IEnumerable> _externalLoginProviders; private readonly IRefreshTokenService _refreshTokenService; private readonly RefreshTokenOptions _refreshTokenOptions; + private readonly IExternalLoginEmailTrustPolicy _externalLoginEmailTrustPolicy; + private readonly VerificationOptions _verificationOptions; + private readonly IVerificationWorkflowService _verificationWorkflow; // Preserve the original public constructor for existing compiled consumers. public UserAccountService(IUserManager userManager, @@ -31,7 +34,7 @@ public UserAccountService(IUserManager userManager, IJwtProvider jwtUtils = null) : this(userManager, signInManager, externalLoginProviders, authenticationHandlerProvider, contextAccessor, userClaimsPrincipalFactory, authenticationSchemeProvider, - jwtUtils, null, null) { + jwtUtils, null, null, null, null, null) { } public UserAccountService(IUserManager userManager, @@ -43,7 +46,10 @@ public UserAccountService(IUserManager userManager, IAuthenticationSchemeProvider authenticationSchemeProvider, IJwtProvider jwtUtils = null, IRefreshTokenService refreshTokenService = null, - IOptions refreshTokenOptions = null) { + IOptions refreshTokenOptions = null, + IExternalLoginEmailTrustPolicy externalLoginEmailTrustPolicy = null, + IOptions verificationOptions = null, + IVerificationWorkflowService verificationWorkflow = null) { _userManager = userManager; _signInManager = signInManager; _jwtUtils = jwtUtils; @@ -54,6 +60,9 @@ public UserAccountService(IUserManager userManager, _authenticationSchemeProvider = authenticationSchemeProvider; _refreshTokenService = refreshTokenService; _refreshTokenOptions = refreshTokenOptions?.Value ?? new RefreshTokenOptions(); + _externalLoginEmailTrustPolicy = externalLoginEmailTrustPolicy; + _verificationOptions = verificationOptions?.Value ?? new VerificationOptions(); + _verificationWorkflow = verificationWorkflow; } public virtual async Task> ExternalLoginAsync(string providerName, string token) { @@ -61,24 +70,50 @@ public virtual async Task> ExternalLoginAsync(string provid if(provider == null) return new Result(ResultCode.BadRequest, Result.CreateErrors("Unknown provider", "Provider is not added to system")); - (TUser userInfo, UserLoginInfo loginInfo) = await provider.ValidateAsync(token); - if(loginInfo == null) + var providerResult = await provider.ValidateAsync(token); + if(providerResult?.LoginInfo == null || providerResult.User == null) return new Result(ResultCode.BadRequest, Result.CreateErrors("Invalid token", "Invalid External Authentication.")); + var loginInfo = providerResult.LoginInfo; var user = await _userManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); if(user == null) { - user = await _userManager.FindByEmailAsync(userInfo.Email); - if(user == null) { - user = userInfo; - var createResult = await _userManager.CreateAsync(user); - if(!createResult.Succeeded) - return new Result(ResultCode.BadRequest, createResult.Errors); + var trustedEmail = _externalLoginEmailTrustPolicy?.IsEmailTrusted(provider.Provider, providerResult) == true; + var existingEmailUser = string.IsNullOrWhiteSpace(providerResult.Email) + ? null + : await _userManager.FindByEmailAsync(providerResult.Email); + + if(existingEmailUser != null) { + // Never link an external identity to an existing account based on an unverified email. + if(!trustedEmail) + return new Result( + ResultCode.Conflict, + Result.CreateErrors("ExternalAccountLinkRequired", "Sign in to the existing account before linking this external provider.")); + + user = existingEmailUser; + if(!user.EmailConfirmed) { + user.EmailConfirmed = true; + var updateResult = await _userManager.UpdateAsync(user); + if(!updateResult.Succeeded) + return new Result(ResultCode.BadRequest, updateResult.Errors); + } var addLoginResult = await _userManager.AddLoginAsync(user, loginInfo); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); - } - else { + } else { + user = providerResult.User; + if(string.IsNullOrWhiteSpace(user.Email)) + user.Email = providerResult.Email; + if(string.IsNullOrWhiteSpace(user.UserName)) + user.UserName = !string.IsNullOrWhiteSpace(providerResult.Email) + ? providerResult.Email + : $"{provider.Provider}_{loginInfo.ProviderKey}"; + user.EmailConfirmed = trustedEmail; + + var createResult = await _userManager.CreateAsync(user); + if(!createResult.Succeeded) + return new Result(ResultCode.BadRequest, createResult.Errors); + var addLoginResult = await _userManager.AddLoginAsync(user, loginInfo); if(!addLoginResult.Succeeded) return new Result(ResultCode.BadRequest, addLoginResult.Errors); @@ -88,6 +123,26 @@ public virtual async Task> ExternalLoginAsync(string provid if(user == null) return new Result(ResultCode.BadRequest, Result.CreateErrors("Add_Error", "User cannot added")); + if(_verificationOptions.RequireEmailVerificationForExternalLogins && !user.EmailConfirmed) { + if(string.IsNullOrWhiteSpace(user.Email) || _verificationWorkflow == null) + return new Result( + ResultCode.Forbidden, + Result.CreateErrors("EmailVerificationRequired", "Email verification is required but no verified email address or verification workflow is available.")); + + var verification = await _verificationWorkflow.StartAsync( + user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email); + if(!verification.Succeeded) + return new Result( + ResultCode.Forbidden, + Result.CreateErrors(verification.ErrorCode, verification.ErrorDescription)); + + return new Result(user, new Token { + VerificationRequired = true, + VerificationHandle = verification.VerificationHandle, + VerificationExpiresAt = verification.ExpiresAt + }); + } + return await GenerateTokenAsync(user); } diff --git a/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs b/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs new file mode 100644 index 0000000..ee0276c --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs @@ -0,0 +1,47 @@ +using RuntimeApps.Authentication.Model; +using RuntimeApps.Authentication.Service; + +namespace RuntimeApps.Authentication.Test { + public class ExternalLoginEmailTrustPolicyTest { + private readonly DefaultExternalLoginEmailTrustPolicy _policy = new(); + + [Theory] + [InlineData("person@gmail.com", null, true)] + [InlineData("person@company.com", "company.com", true)] + [InlineData("person@company.com", "other.com", false)] + [InlineData("person@example.com", null, false)] + public void GoogleEmailTrust_RequiresVerifiedEmailAndTrustedDomain( + string email, string hostedDomain, bool expected) { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = email, + EmailVerified = true, + HostedDomain = hostedDomain + }; + + Assert.Equal(expected, _policy.IsEmailTrusted("GOOGLE", result)); + } + + [Fact] + public void FacebookEmail_IsNeverTrustedByDefault() { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = "person@example.com", + EmailVerified = true + }; + + Assert.False(_policy.IsEmailTrusted("FACEBOOK", result)); + } + + [Fact] + public void UnverifiedGoogleEmail_IsNotTrusted() { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = "person@gmail.com", + EmailVerified = false + }; + + Assert.False(_policy.IsEmailTrusted("GOOGLE", result)); + } + } +} \ No newline at end of file diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index 50d700e..e1ee946 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -14,6 +14,7 @@ public class UserAccountServiceTest { private readonly Mock> _jwtProviderMock; private readonly Mock> _externalLoginProvider1; private readonly Mock> _externalLoginProvider2; + private readonly Mock> _externalLoginEmailTrustPolicyMock; private readonly Mock _authenticationHandlerProviderMock; private readonly Mock _httpContextAccessorMock; private readonly Mock> _userClaimsPrincipalFactoryMock; @@ -26,6 +27,7 @@ public UserAccountServiceTest() { _jwtProviderMock = new Mock>(); _externalLoginProvider1 = new Mock>(); _externalLoginProvider2 = new Mock>(); + _externalLoginEmailTrustPolicyMock = new Mock>(); _authenticationHandlerProviderMock= new Mock(); _httpContextAccessorMock= new Mock(); _userClaimsPrincipalFactoryMock = new Mock>(); @@ -38,7 +40,7 @@ public UserAccountServiceTest() { _httpContextAccessorMock.Object, _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, - _jwtProviderMock.Object); + _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object); _authenticationSchemeProviderMock.Setup(p => p.GetDefaultSignInSchemeAsync()) .ReturnsAsync((AuthenticationScheme)null); @@ -113,30 +115,79 @@ public async Task Login_WrongPassword() { } [Fact] - public async Task CompleteRegistration_Success_ConfirmedUser() { - var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = true }; - var token = new Model.Token { + public async Task Register_Success() { + //Arrange + string password = "password"; + var user = new IdentityUser() { + Email = "test@test.com" + }; + var token = new Model.Token() { AuthenticationToken = "", ExpireDate = DateTimeOffset.Now.AddDays(30), }; - _jwtProviderMock.Setup(provider => provider.GenerateTokenAsync(user)).ReturnsAsync(token); + _userManagerMock.Setup(u => u.FindByNameAsync(user.Email)) + .ReturnsAsync(nullUSer); + _userManagerMock.Setup(u => u.CreateAsync(user, password)) + .ReturnsAsync(IdentityResult.Success); + _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) + .ReturnsAsync(token); - var result = await _userAccountService.CompleteRegistrationAsync(user); + //Act + var result = await _userAccountService.RegisterAsync(user, password); + //Assert result.Succeeded.Should().BeTrue(); - result.Data.Should().Be(user); - result.Meta.Should().Be(token); + result.Data.Should().NotBeNull() + .And.Be(user); + result.Data.UserName.Should().Be(result.Data.Email); + result.Meta.Should().NotBeNull() + .And.Be(token); } [Fact] - public async Task CompleteRegistration_UnconfirmedUser_IsRejected() { - var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = false }; + public async Task Register_UserExist() { + //Arrange + string password = "password"; + var user = new IdentityUser() { + Email = "test@test.com" + }; + _userManagerMock.Setup(u => u.CreateAsync(user, password)) + .ReturnsAsync(IdentityResult.Failed(new IdentityError { + Code = "Failed", + Description = "User Exist!" + })); - var result = await _userAccountService.CompleteRegistrationAsync(user); + //Act + var result = await _userAccountService.RegisterAsync(user, password); + + //Assert + result.Succeeded.Should().BeFalse(); + result.Data.Should().BeNull(); + result.Meta.Should().BeNull(); + } + + [Fact] + public async Task Register_ValidateError() { + //Arrange + string password = "password"; + var user = new IdentityUser() { + Email = "test@test.com" + }; + _userManagerMock.Setup(u => u.CreateAsync(user, password)) + .ReturnsAsync(IdentityResult.Failed(new IdentityError[] { + new IdentityError { + Code = "InvalidPassword", + Description = "Password must be more than 6 character" + } + })); + //Act + var result = await _userAccountService.RegisterAsync(user, password); + + //Assert result.Succeeded.Should().BeFalse(); - result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Forbidden); - _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); + result.Data.Should().BeNull(); + result.Meta.Should().BeNull(); } [Fact] @@ -156,7 +207,9 @@ public async Task ExternalLogin_Success_CreateNewUser() { _externalLoginProvider2.SetupGet(e => e.Provider) .Returns(provider); _externalLoginProvider2.Setup(e => e.ValidateAsync(token)) - .ReturnsAsync((user, loginInfo)); + .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { + User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false + }); _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(nullUSer); _userManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) @@ -198,11 +251,17 @@ public async Task ExternalLogin_Success_ExistUser() { _externalLoginProvider2.SetupGet(e => e.Provider) .Returns(provider); _externalLoginProvider2.Setup(e => e.ValidateAsync(token)) - .ReturnsAsync((user, loginInfo)); + .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { + User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false + }); _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(nullUSer); _userManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) .ReturnsAsync(user); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted( + provider, It.IsAny>())) + .Returns(true); + _userManagerMock.Setup(u => u.UpdateAsync(user)).ReturnsAsync(IdentityResult.Success); _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) .ReturnsAsync(IdentityResult.Success); _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) @@ -238,7 +297,9 @@ public async Task ExternalLogin_Success_ExistsLogin() { _externalLoginProvider2.SetupGet(e => e.Provider) .Returns(provider); _externalLoginProvider2.Setup(e => e.ValidateAsync(token)) - .ReturnsAsync((user, loginInfo)); + .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { + User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false + }); _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(user); _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) From 82a38ecf0aa3d6ba6890922c2086c6ddef72ad98 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Wed, 18 Nov 2026 23:36:01 +0100 Subject: [PATCH 04/18] Add admin provisioning and optional MailKit email sender --- .../MailKitVerificationSenderExtensions.cs | 27 +++++++++++ .../Model/SmtpVerificationOptions.cs | 23 ++++++++++ .../RuntimeApps.Authentication.MailKit.csproj | 12 +++++ .../Service/MailKitVerificationSender.cs | 45 +++++++++++++++++++ RuntimeApps.Authentication.sln | 6 +++ ...ccountApiEndpointRouteBuilderExtensions.cs | 44 ++++++++++++++++++ .../MicrosoftExternalLoginProvider.cs | 4 +- .../Service/VerificationWorkflowService.cs | 8 +++- .../UserAccountServiceTest.cs | 25 +++++++++++ 9 files changed, 190 insertions(+), 4 deletions(-) create mode 100644 RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs create mode 100644 RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs create mode 100644 RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj create mode 100644 RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs diff --git a/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs b/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs new file mode 100644 index 0000000..d04d616 --- /dev/null +++ b/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs @@ -0,0 +1,27 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.MailKit.Model; +using RuntimeApps.Authentication.MailKit.Service; + +namespace RuntimeApps.Authentication.MailKit.Extensions { + public static class MailKitVerificationSenderExtensions { + public static IServiceCollection AddMailKitVerificationSender( + this IServiceCollection services, + Action configure) + where TKey : IEquatable { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configure); + + services.AddOptions() + .Configure(configure) + .Validate(options => options.IsValid(), "SMTP verification options are invalid.") + .ValidateOnStart(); + + services.Replace(ServiceDescriptor.Scoped< + IVerificationSender, + MailKitVerificationSender>()); + return services; + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs b/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs new file mode 100644 index 0000000..06dff7f --- /dev/null +++ b/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs @@ -0,0 +1,23 @@ +using MailKit.Security; + +namespace RuntimeApps.Authentication.MailKit.Model { + public sealed class SmtpVerificationOptions { + public const string SectionName = "Authentication:Verification:Smtp"; + + public string Host { get; set; } + public int Port { get; set; } = 587; + public SecureSocketOptions SocketOptions { get; set; } = SecureSocketOptions.StartTls; + public string UserName { get; set; } + public string Password { get; set; } + public string FromAddress { get; set; } + public string FromName { get; set; } = "Account verification"; + public string ApplicationName { get; set; } = "Application"; + + public bool IsValid() => + !string.IsNullOrWhiteSpace(Host) && + Port is > 0 and <= 65535 && + !string.IsNullOrWhiteSpace(FromAddress) && + ((!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrEmpty(Password)) || + (string.IsNullOrWhiteSpace(UserName) && string.IsNullOrEmpty(Password))); + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj b/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj new file mode 100644 index 0000000..7f8af4c --- /dev/null +++ b/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj @@ -0,0 +1,12 @@ + + + net10.0 + enable + + + + + + + + \ No newline at end of file diff --git a/RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs b/RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs new file mode 100644 index 0000000..cd18d34 --- /dev/null +++ b/RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs @@ -0,0 +1,45 @@ +using MailKit.Net.Smtp; +using Microsoft.Extensions.Options; +using MimeKit; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.MailKit.Model; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.MailKit.Service { + public sealed class MailKitVerificationSender : IVerificationSender + where TKey : IEquatable { + private readonly SmtpVerificationOptions _options; + + public MailKitVerificationSender(IOptions options) { + _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + if(!_options.IsValid()) + throw new InvalidOperationException("SMTP verification options are invalid."); + } + + public async Task SendAsync( + VerificationCodeContext context, + string code, + DateTimeOffset expiresAt, + CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(context); + ArgumentException.ThrowIfNullOrWhiteSpace(context.Destination); + ArgumentException.ThrowIfNullOrWhiteSpace(code); + + var message = new MimeMessage(); + message.From.Add(new MailboxAddress(_options.FromName, _options.FromAddress)); + message.To.Add(MailboxAddress.Parse(context.Destination)); + message.Subject = $"{_options.ApplicationName} verification code"; + message.Body = new TextPart("plain") { + Text = $"Your verification code is: {code}\n\n" + + $"This code expires at {expiresAt:O}. If you did not request this code, you can ignore this message." + }; + + using var client = new SmtpClient(); + await client.ConnectAsync(_options.Host, _options.Port, _options.SocketOptions, cancellationToken); + if(!string.IsNullOrWhiteSpace(_options.UserName)) + await client.AuthenticateAsync(_options.UserName, _options.Password, cancellationToken); + await client.SendAsync(message, cancellationToken); + await client.DisconnectAsync(true, cancellationToken); + } + } +} \ No newline at end of file diff --git a/RuntimeApps.Authentication.sln b/RuntimeApps.Authentication.sln index fdac239..7c63ccd 100644 --- a/RuntimeApps.Authentication.sln +++ b/RuntimeApps.Authentication.sln @@ -7,6 +7,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.EF", "RuntimeApps.Authentication.EF\RuntimeApps.Authentication.EF.csproj", "{366669C0-AF34-42D9-B54F-F884AAB5F9E2}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.MailKit", "RuntimeApps.Authentication.MailKit\RuntimeApps.Authentication.MailKit.csproj", "{2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{58197192-84A5-4423-8DD9-60DBA205E544}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.Sample", "Samples\RuntimeApps.Authentication.Sample\RuntimeApps.Authentication.Sample.csproj", "{1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}" @@ -43,6 +45,10 @@ Global {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Debug|Any CPU.Build.0 = Debug|Any CPU {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Release|Any CPU.ActiveCfg = Release|Any CPU {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Release|Any CPU.Build.0 = Release|Any CPU + {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Release|Any CPU.Build.0 = Release|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index b8d7e4f..48cef9c 100644 --- a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs @@ -104,6 +104,50 @@ public static IEndpointRouteBuilder MapRegisterApi(this I return endpoints; } + /// + /// Maps an administrator-only endpoint for creating users that are already email-confirmed. + /// No authentication token is issued by this endpoint. + /// + public static IEndpointRouteBuilder MapAdminUserApi( + this IEndpointRouteBuilder endpoints, + string authorizationPolicy = null) + where TUser : IdentityUser + where TUserDto : class + where TKey : IEquatable { + var serviceAvailability = endpoints.ServiceProvider.GetRequiredService(); + if(!serviceAvailability.IsService(typeof(IUserManager)) || + !serviceAvailability.IsService(typeof(IUserMapper))) + throw new InvalidOperationException("Admin user endpoints require IUserManager and the configured user mapper."); + + var routeGroup = endpoints.MapGroup("admin/users"); + if(string.IsNullOrWhiteSpace(authorizationPolicy)) + routeGroup.RequireAuthorization(); + else + routeGroup.RequireAuthorization(authorizationPolicy); + + routeGroup.MapPost("", async Task, ValidationProblem>> ( + [FromBody] RegisterUserModel request, + IUserManager userManager, + [FromServices] IUserMapper mapper) => { + if(request?.UserInfo == null || string.IsNullOrEmpty(request.Password)) + return ValidationProblemFactory.CreateValidationProblem( + "InvalidUser", "User information and password are required."); + + var user = mapper.ToUser(request.UserInfo); + if(string.IsNullOrWhiteSpace(user.UserName)) + user.UserName = user.Email; + user.EmailConfirmed = true; + + var result = await userManager.CreateAsync(user, request.Password); + if(!result.Succeeded) + return result.CreateValidationProblem(); + + return TypedResults.Ok(mapper.ToDto(user)); + }); + + return endpoints; + } + public static IEndpointRouteBuilder MapAccountApi(this IEndpointRouteBuilder endpoints) where TUser : IdentityUser where TUserDto : class diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs index 98ab13a..531b930 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs @@ -17,11 +17,11 @@ public MicrosoftExternalLoginProvider(IOptions "MICROSOFT"; - public async Task> ValidateAsync(string token) { + public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { var option = _options.Value; var openidConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync( - $"{option.IssuerEndpoint}{option.ConfigurationAddress}", CancellationToken.None); + new Uri(new Uri(option.IssuerEndpoint), option.ConfigurationAddress.TrimStart('/')).ToString(), CancellationToken.None); var tokenHandler = new JwtSecurityTokenHandler(); diff --git a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs index d4bc744..f729462 100644 --- a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs @@ -160,9 +160,13 @@ await _store.TryIncrementFailedAttemptsAsync( if(user == null) return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); - if(request.Purpose == VerificationPurpose.Registration || - request.Purpose == VerificationPurpose.EmailChange) + if(request.Channel == VerificationChannel.Email && + (request.Purpose == VerificationPurpose.Registration || request.Purpose == VerificationPurpose.EmailChange)) { + var currentEmail = _normalizer.NormalizeEmail(user.Email ?? string.Empty); + if(!string.Equals(currentEmail, request.NormalizedDestination, StringComparison.Ordinal)) + return Failure("VerificationDestinationChanged", "The email address associated with this request has changed."); user.EmailConfirmed = true; + } var updateResult = await _userManager.UpdateAsync(user); if(!updateResult.Succeeded) diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index e1ee946..687236a 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -280,6 +280,31 @@ public async Task ExternalLogin_Success_ExistUser() { _userManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Once()); } + [Fact] + public async Task ExternalLogin_UnverifiedEmail_DoesNotLinkExistingAccount() { + const string provider = "Google"; + const string token = "provider-token"; + var user = new IdentityUser { Email = "existing@example.com", EmailConfirmed = true }; + var loginInfo = new UserLoginInfo(provider, token, provider); + _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); + _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); + _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) + .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { + User = new IdentityUser { Email = user.Email }, + LoginInfo = loginInfo, + Email = user.Email, + EmailVerified = false + }); + _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _userManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + + var result = await _userAccountService.ExternalLoginAsync(provider, token); + + result.Succeeded.Should().BeFalse(); + result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Conflict); + _userManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); + } + [Fact] public async Task ExternalLogin_Success_ExistsLogin() { //Arrange From f0bd17aa94f7849f5d4d8994e6f495bc83bc1211 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:04:19 +0100 Subject: [PATCH 05/18] Complete secure email verification registration workflow --- .github/workflows/ci.yml | 22 +++++ ReadMe.md | 75 ++++++++++++++++ .../Model/VerificationSendConfiguration.cs | 1 + .../Store/EfVerificationRequestStore.cs | 4 + .../Model/SmtpVerificationOptions.cs | 21 +++-- ...ccountApiEndpointRouteBuilderExtensions.cs | 14 ++- ...hTokenApiEndpointRouteBuilderExtensions.cs | 19 ++-- .../Model/FacebookExternalLoginOption.cs | 11 +-- .../DataProtectionVerificationCodeVerifier.cs | 9 +- .../FacebookExternalLoginProvider.cs | 69 ++++++++++---- .../GoogleExternalLoginProvider.cs | 2 - .../Service/RegistrationService.cs | 4 + .../Service/UserAccountService.cs | 2 +- .../Service/VerificationWorkflowService.cs | 15 +++- .../ApplicationDbContext.cs | 5 ++ .../Program.cs | 31 ++++++- .../ReadMe.md | 26 ++++++ .../RuntimeApps.Authentication.Sample.csproj | 3 +- .../appsettings.json | 14 +++ .../EfVerificationRequestStoreTest.cs | 86 ++++++++++++++++++ .../RegistrationServiceTest.cs | 89 +++++++++++++++++++ .../UserAccountServiceTest.cs | 53 ++++------- .../VerificationPrimitivesTest.cs | 25 ++++++ 23 files changed, 515 insertions(+), 85 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 Tests/RuntimeApps.Authentication.Test/EfVerificationRequestStoreTest.cs create mode 100644 Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7429129 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: CI + +on: + pull_request: + branches: [ main ] + push: + branches: [ main, "feature/**" ] + +jobs: + build-and-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + - name: Restore + run: dotnet restore RuntimeApps.Authentication.sln + - name: Build + run: dotnet build RuntimeApps.Authentication.sln --configuration Release --no-restore + - name: Test + run: dotnet test Tests/RuntimeApps.Authentication.Test/RuntimeApps.Authentication.Test.csproj --configuration Release --no-build diff --git a/ReadMe.md b/ReadMe.md index 90ad006..17afab0 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -202,3 +202,78 @@ Revoking refresh tokens does not immediately invalidate access JWTs already issu ### Custom persistence Applications that do not use the EF integration can implement `IRefreshTokenStore` and register it before startup. Store implementations must make `TryRotateAsync` atomic: consuming the old token and persisting its replacement must succeed or fail as one operation. A non-atomic implementation is not safe for production use. + + +## Registration with email verification + +Public registration uses a verification workflow instead of issuing an access token immediately. This is a major-version API change: `IUserAccountService.RegisterAsync` has been replaced by `IRegistrationService`. + +### Configure the workflow + +Call `AddVerificationServices` when configuring RuntimeApps Authentication. Register a persistent implementation of `IVerificationRequestStore` and a delivery implementation of `IVerificationSender`. The EF integration provides a relational store: + +```cs +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddRuntimeAppsAuthentication, IdentityRole, int>() + .AddVerificationServices(options => { + options.CodeLength = 6; + options.CodeLifetime = TimeSpan.FromMinutes(10); + options.MaximumFailedAttempts = 5; + options.ResendCooldown = TimeSpan.FromSeconds(60); + options.MaximumSendsPerHour = 5; + options.RequireEmailVerificationForExternalLogins = false; + }) + .AddEfStores, IdentityRole, int>(); + +// In ApplicationDbContext.OnModelCreating: +modelBuilder.AddVerificationRequestEntity(); + +builder.Services.AddVerificationRequestStore(); +``` + +The DbContext must use a relational provider. Verification state changes and destination-level rate limits rely on atomic relational operations; EF InMemory is not supported. Add a migration after adding the verification entities. + +The optional `RuntimeApps.Authentication.MailKit` package provides an SMTP sender without adding MailKit to the core package: + +```cs +builder.Services.AddMailKitVerificationSender, int>(options => { + options.Host = configuration["Authentication:Verification:Smtp:Host"]; + options.Port = 587; + options.SocketOptions = MailKit.Security.SecureSocketOptions.StartTls; + options.UserName = configuration["Authentication:Verification:Smtp:UserName"]; + options.Password = configuration["Authentication:Verification:Smtp:Password"]; + options.FromAddress = configuration["Authentication:Verification:Smtp:FromAddress"]; +}); +``` + +Keep SMTP credentials in user secrets, environment variables, or a secret manager. Persist and share the ASP.NET Core Data Protection key ring across application instances. + +### Registration endpoints + +| Method | Endpoint | Purpose | +| --- | --- | --- | +| POST | `/register` | Create or recover a pending account and send a verification code | +| POST | `/register/verify` | Verify the code and receive an authentication token | +| POST | `/register/resend` | Send a replacement code; the previous code becomes invalid | + +The API returns an opaque, cryptographically random verification handle. Only its SHA-256 lookup hash is stored; the database request ID is never exposed. The code is protected using ASP.NET Core Data Protection and bound to the user, request, purpose, channel, and destination. + +Default limits are six numeric digits, ten-minute lifetime, five failed attempts, a 60-second resend cooldown, and five sends per destination/purpose/channel per hour. A successful verification is single-use. A resend rotates the code. The EF store uses relational transactions and conditional updates for concurrent operations. + +Repeating registration recovers a pending account if the client lost its handle. It does not replace the password on an existing pending account. The default updater changes only the username and phone number; implement `IUserRegistrationUpdater` to allow other safe profile fields. Do not copy passwords, roles, claims, security stamps, or external logins from an unauthenticated repeat request. + +### Administrator provisioning + +Map `MapAdminUserApi()` separately from public registration. By default, the endpoint requires the `Administrator` role. Alternatively, pass a named authorization policy. It creates an already-confirmed user, returns the user DTO, and does not issue an authentication token. + +### External login policy + +External provider login does not require a second email challenge by default. Set `RequireEmailVerificationForExternalLogins = true` to require email verification before issuing an application token when the provider email is not trusted. + +External authentication and email confirmation remain separate. The default trust policy accepts verified Google Gmail/Googlemail addresses and verified Google Workspace addresses when the signed hosted-domain claim matches the email domain. Facebook and Microsoft email claims are not trusted by default. Developers can replace `IExternalLoginEmailTrustPolicy`. + +External identities are not automatically linked to an existing local account based on a matching email address. Linking must be initiated from an authenticated account-management flow. + +### Migration note + +This is a breaking major-version change. Remove calls to the old immediate-token registration API and use the verification endpoints. Applications must add the verification entities to their relational DbContext and create a migration, configure a persistent request store and sender, and review administrator authorization policy. No production in-memory verification store is provided. diff --git a/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs b/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs index 80381fe..97bc76d 100644 --- a/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs +++ b/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs @@ -13,6 +13,7 @@ public void Configure(EntityTypeBuilder builder) { builder.Property(send => send.Purpose).HasConversion().HasMaxLength(32).IsRequired(); builder.Property(send => send.Channel).HasConversion().HasMaxLength(32).IsRequired(); builder.Property(send => send.SentAt).HasConversion(new DateTimeOffsetToBinaryConverter()); + builder.HasIndex(send => send.SentAt); builder.HasIndex(send => new { send.NormalizedDestination, send.Purpose, diff --git a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs index 292a037..71eca51 100644 --- a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs +++ b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs @@ -51,6 +51,8 @@ public async Task TryCreateAsync( await using var transaction = await _dbContext.Database.BeginTransactionAsync( IsolationLevel.Serializable, cancellationToken); + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); + var sendCount = await Sends.CountAsync(item => item.NormalizedDestination == request.NormalizedDestination && item.Purpose == request.Purpose && @@ -131,6 +133,8 @@ public async Task TryResendAsync( return false; } + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(cancellationToken); + var sendCount = await Sends.CountAsync(item => item.NormalizedDestination == request.NormalizedDestination && item.Purpose == request.Purpose && diff --git a/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs b/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs index 06dff7f..e45917a 100644 --- a/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs +++ b/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs @@ -1,3 +1,4 @@ +using System.Net.Mail; using MailKit.Security; namespace RuntimeApps.Authentication.MailKit.Model { @@ -13,11 +14,19 @@ public sealed class SmtpVerificationOptions { public string FromName { get; set; } = "Account verification"; public string ApplicationName { get; set; } = "Application"; - public bool IsValid() => - !string.IsNullOrWhiteSpace(Host) && - Port is > 0 and <= 65535 && - !string.IsNullOrWhiteSpace(FromAddress) && - ((!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrEmpty(Password)) || - (string.IsNullOrWhiteSpace(UserName) && string.IsNullOrEmpty(Password))); + public bool IsValid() { + if(string.IsNullOrWhiteSpace(Host) || Port is <= 0 or > 65535 || + string.IsNullOrWhiteSpace(FromAddress) || + !((!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrEmpty(Password)) || + (string.IsNullOrWhiteSpace(UserName) && string.IsNullOrEmpty(Password)))) + return false; + + try { + _ = new MailAddress(FromAddress); + return true; + } catch(FormatException) { + return false; + } + } } } \ No newline at end of file diff --git a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index 48cef9c..066db2e 100644 --- a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Identity; @@ -71,6 +72,9 @@ public static IEndpointRouteBuilder MapRegisterApi(this I IRegistrationService registrationService, [FromServices] IUserMapper mapper, HttpContext httpContext) => { + if(user?.UserInfo == null) + return ValidationProblemFactory.CreateValidationProblem("InvalidRegistration", "User information is required."); + var result = await registrationService.RegisterAsync( mapper.ToUser(user.UserInfo), user.Password, httpContext.RequestAborted); if(!result.Succeeded) @@ -83,6 +87,9 @@ public static IEndpointRouteBuilder MapRegisterApi(this I IRegistrationService registrationService, [FromServices] IUserMapper mapper, HttpContext httpContext) => { + if(request == null) + return ValidationProblemFactory.CreateValidationProblem("InvalidVerification", "Verification handle and code are required."); + var result = await registrationService.VerifyAsync( request.VerificationHandle, request.Code, httpContext.RequestAborted); if(!result.Succeeded) @@ -94,6 +101,9 @@ public static IEndpointRouteBuilder MapRegisterApi(this I [FromBody] ResendRegistrationVerificationModel request, IRegistrationService registrationService, HttpContext httpContext) => { + if(request == null) + return ValidationProblemFactory.CreateValidationProblem("InvalidVerification", "Verification handle is required."); + var result = await registrationService.ResendAsync( request.VerificationHandle, httpContext.RequestAborted); if(!result.Succeeded) @@ -121,7 +131,7 @@ public static IEndpointRouteBuilder MapAdminUserApi( var routeGroup = endpoints.MapGroup("admin/users"); if(string.IsNullOrWhiteSpace(authorizationPolicy)) - routeGroup.RequireAuthorization(); + routeGroup.RequireAuthorization(new AuthorizeAttribute { Roles = "Administrator" }); else routeGroup.RequireAuthorization(authorizationPolicy); diff --git a/RuntimeApps.Authentication/Controller/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/RefreshTokenApiEndpointRouteBuilderExtensions.cs index 7d3488f..798be74 100644 --- a/RuntimeApps.Authentication/Controller/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -29,7 +29,8 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi IServiceProvider services, IAuthenticationSchemeProvider schemeProvider, IAuthenticationHandlerProvider handlerProvider, - IOptions options) => { + IOptions options, + IOptions verificationOptions) => { if(!await requestLimiter.IsAllowedAsync(context, context.RequestAborted)) return Results.StatusCode(StatusCodes.Status429TooManyRequests); @@ -48,10 +49,18 @@ public static IEndpointRouteBuilder MapRefreshTokenApi(this IEndpoi if(session == null) return Results.Unauthorized(); - var user = await userManager.FindByIdAsync(Convert.ToString(session.UserId)); - if(user == null || - await userManager.IsLockedOutAsync(user) || - !await signInManager.CanSignInAsync(user)) { + var user = await userManager.FindByIdAsync(Convert.ToString(session.UserId, System.Globalization.CultureInfo.InvariantCulture)); + if(user == null) { + await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted); + return Results.Unauthorized(); + } + + var isLockedOut = await userManager.IsLockedOutAsync(user); + var hasExternalLogin = (await userManager.GetLoginsAsync(user)).Count > 0; + var emailPolicyAllowsSignIn = user.EmailConfirmed || + (hasExternalLogin && !verificationOptions.Value.RequireEmailVerificationForExternalLogins); + if(isLockedOut || !emailPolicyAllowsSignIn || + (user.EmailConfirmed && !await signInManager.CanSignInAsync(user))) { await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted); return Results.Unauthorized(); } diff --git a/RuntimeApps.Authentication/Model/FacebookExternalLoginOption.cs b/RuntimeApps.Authentication/Model/FacebookExternalLoginOption.cs index 2337560..a210095 100644 --- a/RuntimeApps.Authentication/Model/FacebookExternalLoginOption.cs +++ b/RuntimeApps.Authentication/Model/FacebookExternalLoginOption.cs @@ -1,20 +1,21 @@ -using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity; using RuntimeApps.Authentication.Model.Facebook; namespace RuntimeApps.Authentication.Model { - public class FacebookExternalLoginOption: BaseExternalLoginOption + public class FacebookExternalLoginOption : BaseExternalLoginOption where TUser : class, new() { public string AccessTokenUrl { get; set; } = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials"; public string DebugTokenUrl { get; set; } = "https://graph.facebook.com/debug_token?input_token={0}&access_token={1}"; - public Func Mapper { get; set; } = (data) => new TUser(); + public string GraphApiVersion { get; set; } = "v27.0"; + public Func Mapper { get; set; } = data => new TUser(); public static TIdentityUser UserIdentityMapper(FacebookUserData data) where TIdentityUser : IdentityUser, new() where TKey : IEquatable { - return new TIdentityUser() { + return new TIdentityUser { UserName = data.Email, Email = data.Email }; } } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs b/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs index b7ee7ab..562ecee 100644 --- a/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs +++ b/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -24,8 +25,8 @@ public string CreateVerifier(string code, VerificationRequest request) { ArgumentNullException.ThrowIfNull(request); var payload = JsonSerializer.Serialize(new VerificationCodePayload( - Convert.ToString(request.Id), - Convert.ToString(request.UserId), + Convert.ToString(request.Id, CultureInfo.InvariantCulture), + Convert.ToString(request.UserId, CultureInfo.InvariantCulture), request.Purpose, request.Channel, request.CustomPurpose, @@ -44,8 +45,8 @@ public bool Verify(string code, VerificationRequest request) { var payload = JsonSerializer.Deserialize( _protector.Unprotect(request.CodeVerifier)); if(payload == null || - payload.RequestId != Convert.ToString(request.Id) || - payload.UserId != Convert.ToString(request.UserId) || + payload.RequestId != Convert.ToString(request.Id, CultureInfo.InvariantCulture) || + payload.UserId != Convert.ToString(request.UserId, CultureInfo.InvariantCulture) || payload.Purpose != request.Purpose || payload.Channel != request.Channel || payload.CustomPurpose != request.CustomPurpose || diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs index f7c0a33..4781385 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs @@ -1,4 +1,6 @@ -using Microsoft.AspNetCore.Identity; +using System.Globalization; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Newtonsoft.Json; using RuntimeApps.Authentication.Interface; @@ -6,7 +8,7 @@ using RuntimeApps.Authentication.Model.Facebook; namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { - public class FacebookExternalLoginProvider: IExternalLoginProvider + public class FacebookExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { private readonly IOptions> _options; @@ -18,26 +20,57 @@ public FacebookExternalLoginProvider(IOptions public async Task> ValidateAsync(string token) { var option = _options.Value; - using HttpClient httpClient = new HttpClient(); + if(string.IsNullOrWhiteSpace(token) || + !long.TryParse(option.ClientId, NumberStyles.None, CultureInfo.InvariantCulture, out var configuredAppId)) + return null; - var appAccessTokenResponse = await httpClient.GetStringAsync(string.Format(option.AccessTokenUrl, option.ClientId, option.ClientSecret)); - var appAccessToken = JsonConvert.DeserializeObject(appAccessTokenResponse); + var graphApiVersion = string.IsNullOrWhiteSpace(option.GraphApiVersion) ? "v27.0" : option.GraphApiVersion; + if(!Regex.IsMatch(graphApiVersion, "^v[0-9]+\\.0$", RegexOptions.CultureInvariant)) + return null; - // 2. validate the user access token - var userAccessTokenValidationResponse = await httpClient.GetStringAsync(string.Format(option.DebugTokenUrl, token, appAccessToken.Access_token)); - var userAccessTokenValidation = JsonConvert.DeserializeObject(userAccessTokenValidationResponse); + try { + using var client = new HttpClient(); + var appTokenUrl = string.Format(CultureInfo.InvariantCulture, option.AccessTokenUrl, + Uri.EscapeDataString(option.ClientId), Uri.EscapeDataString(option.ClientSecret)); + var appTokenResponse = await client.GetStringAsync(appTokenUrl); + var appToken = JsonConvert.DeserializeObject(appTokenResponse); + if(string.IsNullOrWhiteSpace(appToken?.Access_token)) + return null; - if(!userAccessTokenValidation.Data.Is_valid) { - return (null, null); - } + var debugUrl = string.Format(CultureInfo.InvariantCulture, option.DebugTokenUrl, + Uri.EscapeDataString(token), Uri.EscapeDataString(appToken.Access_token)); + var debugResponse = await client.GetStringAsync(debugUrl); + var debugData = JsonConvert.DeserializeObject(debugResponse)?.Data; + if(debugData == null || !debugData.Is_valid || debugData.App_id != configuredAppId || + debugData.User_Id == null || + (debugData.Expires_at is > 0 && DateTimeOffset.FromUnixTimeSeconds(debugData.Expires_at.Value) <= DateTimeOffset.UtcNow)) + return null; + + var userUrl = $"https://graph.facebook.com/{graphApiVersion}/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={Uri.EscapeDataString(token)}"; + var userResponse = await client.GetStringAsync(userUrl); + var userInfo = JsonConvert.DeserializeObject(userResponse); + if(userInfo?.Id == null || userInfo.Id.Value != debugData.User_Id.Value) + return null; - // 3. we've got a valid token so we can request user data from fb - var userInfoResponse = await httpClient.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={token}"); - var userInfo = JsonConvert.DeserializeObject(userInfoResponse); + var user = option.Mapper(userInfo); + if(user == null) + return null; - var user = option.Mapper(userInfo); - var loginInfo = new UserLoginInfo(Provider, userInfo.Id.ToString(), Provider); - return (user, loginInfo); + return new ExternalLoginProviderResult { + User = user, + LoginInfo = new UserLoginInfo(Provider, + userInfo.Id.Value.ToString(CultureInfo.InvariantCulture), Provider), + Email = userInfo.Email, + // Facebook's current response model does not provide a trustworthy email-verified assertion. + EmailVerified = false + }; + } catch(HttpRequestException) { + return null; + } catch(JsonException) { + return null; + } catch(FormatException) { + return null; + } } } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs index 5449b3d..eb49580 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs @@ -1,6 +1,5 @@ using Google.Apis.Auth; using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Interface; using RuntimeApps.Authentication.Model; @@ -8,7 +7,6 @@ namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { public class GoogleExternalLoginProvider: IExternalLoginProvider where TUser : class, new() { - private readonly ILogger> _logger; private readonly IOptions> _option; public GoogleExternalLoginProvider(ILogger> logger, IOptions> option) { diff --git a/RuntimeApps.Authentication/Service/RegistrationService.cs b/RuntimeApps.Authentication/Service/RegistrationService.cs index ad2872b..5ca1b0e 100644 --- a/RuntimeApps.Authentication/Service/RegistrationService.cs +++ b/RuntimeApps.Authentication/Service/RegistrationService.cs @@ -43,7 +43,9 @@ public async Task> RegisterAsync( return GenericResponse(); if(existingUser != null) { + var existingEmail = existingUser.Email; await _userUpdater.UpdatePendingUserAsync(existingUser, user, cancellationToken); + existingUser.Email = existingEmail; var updateResult = await _userManager.UpdateAsync(existingUser); if(!updateResult.Succeeded) return new Result(ResultCode.BadRequest, updateResult.Errors); @@ -59,7 +61,9 @@ public async Task> RegisterAsync( if(racedUser == null) return new Result(ResultCode.BadRequest, createResult.Errors); + var racedEmail = racedUser.Email; await _userUpdater.UpdatePendingUserAsync(racedUser, user, cancellationToken); + racedUser.Email = racedEmail; var updateResult = await _userManager.UpdateAsync(racedUser); if(!updateResult.Succeeded) return new Result(ResultCode.BadRequest, updateResult.Errors); diff --git a/RuntimeApps.Authentication/Service/UserAccountService.cs b/RuntimeApps.Authentication/Service/UserAccountService.cs index d3565a8..1ff4fff 100644 --- a/RuntimeApps.Authentication/Service/UserAccountService.cs +++ b/RuntimeApps.Authentication/Service/UserAccountService.cs @@ -148,7 +148,7 @@ public virtual async Task> ExternalLoginAsync(string provid public virtual async Task> LoginAsync(string userName, string password) { var userInfo = await _userManager.FindByNameAsync(userName); - if(userInfo == null) + if(userInfo == null || !userInfo.EmailConfirmed) return GetIdentityError(SignInResult.Failed); var signInResult = await _signInManager.PasswordSignInAsync(userInfo, password, true, false); diff --git a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs index f729462..17b2aa6 100644 --- a/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Interface; @@ -78,6 +79,8 @@ public async Task StartAsync( var context = CreateContext(user, request); var code = await _generator.GenerateAsync(context, _options, cancellationToken); + if(string.IsNullOrWhiteSpace(code)) + return VerificationOperationResult.Failure("VerificationCodeGenerationFailed", "A verification code could not be generated."); var protectedVerifier = _verifier.CreateVerifier(code, request); if(!await _store.TrySetInitialVerifierAsync( @@ -104,12 +107,20 @@ public async Task ResendAsync( request.Purpose != expectedPurpose || request.Channel != expectedChannel) return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); - var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId)); + var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId, CultureInfo.InvariantCulture)); if(user == null) return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + if(request.Channel == VerificationChannel.Email && + (request.Purpose == VerificationPurpose.Registration || request.Purpose == VerificationPurpose.EmailChange) && + !string.Equals(_normalizer.NormalizeEmail(user.Email ?? string.Empty), + request.NormalizedDestination, StringComparison.Ordinal)) + return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + var context = CreateContext(user, request); var code = await _generator.GenerateAsync(context, _options, cancellationToken); + if(string.IsNullOrWhiteSpace(code)) + return VerificationOperationResult.Failure("VerificationCodeGenerationFailed", "A verification code could not be generated."); var newVerifier = _verifier.CreateVerifier(code, request); var expiresAt = now.Add(_options.CodeLifetime); @@ -156,7 +167,7 @@ await _store.TryIncrementFailedAttemptsAsync( if(!await _store.TryConsumeAsync(request.Id, request.CodeVersion, now, cancellationToken)) return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); - var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId)); + var user = await _userManager.FindByIdAsync(Convert.ToString(request.UserId, CultureInfo.InvariantCulture)); if(user == null) return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); diff --git a/Samples/RuntimeApps.Authentication.Sample/ApplicationDbContext.cs b/Samples/RuntimeApps.Authentication.Sample/ApplicationDbContext.cs index 1addd3f..b61df1f 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ApplicationDbContext.cs +++ b/Samples/RuntimeApps.Authentication.Sample/ApplicationDbContext.cs @@ -1,11 +1,16 @@ using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.EF.Extensions; namespace RuntimeApps.Authentication.Sample { public class ApplicationDbContext: IdentityDbContext, IdentityRole, int> { public ApplicationDbContext(DbContextOptions options) : base(options) { } + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddVerificationRequestEntity(); + } } } diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index 71c0129..a0e1f1e 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -3,6 +3,8 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using MailKit.Security; +using RuntimeApps.Authentication.MailKit.Extensions; using Microsoft.IdentityModel.Tokens; using RuntimeApps.Authentication.Controller; using RuntimeApps.Authentication.EF.Extensions; @@ -12,11 +14,20 @@ var builder = WebApplication.CreateBuilder(args); -builder.Services.AddDbContext(options => options.UseInMemoryDatabase("TestDatabase")); +builder.Services.AddDbContext(options => + options.UseSqlite(builder.Configuration.GetConnectionString("Authentication") ?? "Data Source=authentication.db")); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //Add default services of RuntimeApps application .AddRuntimeAppsAuthentication, IdentityRole, int>() + .AddVerificationServices(options => { + options.CodeLength = 6; + options.CodeLifetime = TimeSpan.FromMinutes(10); + options.MaximumFailedAttempts = 5; + options.ResendCooldown = TimeSpan.FromSeconds(60); + options.MaximumSendsPerHour = 5; + options.RequireEmailVerificationForExternalLogins = false; + }) //Add implemetation of entity framework core user stores. .AddEfStores, IdentityRole, int>() // Add default mapper between IdentityUser and IdentityUserDto @@ -64,6 +75,18 @@ option.Mapper = (data) => MicrosoftExternalLoginOption>.UserIdentityMapper, int>(data); }); +builder.Services.AddVerificationRequestStore(); +builder.Services.AddMailKitVerificationSender, int>(options => { + options.Host = builder.Configuration["Authentication:Verification:Smtp:Host"] ?? "localhost"; + options.Port = builder.Configuration.GetValue("Authentication:Verification:Smtp:Port", 1025); + options.SocketOptions = builder.Configuration.GetValue("Authentication:Verification:Smtp:SocketOptions", SecureSocketOptions.None); + options.FromAddress = builder.Configuration["Authentication:Verification:Smtp:FromAddress"] ?? "noreply@example.com"; + options.FromName = "RuntimeApps Authentication Sample"; + options.ApplicationName = "RuntimeApps Authentication Sample"; +}); + +builder.Services.AddAuthorization(options => options.AddPolicy("Admin", policy => policy.RequireRole("Administrator"))); + builder.Services.AddControllers() .AddJsonOptions(option => { option.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; @@ -80,7 +103,7 @@ var services = scope.ServiceProvider; try { var context = services.GetRequiredService(); - context.Database.Migrate(); + context.Database.EnsureCreated(); } catch(Exception ex) { var logger = services.GetRequiredService>(); logger.LogError(ex, "An error occurred while seeding the database."); @@ -100,6 +123,10 @@ .MapLoginApi, IdentityUserDto, int>() .MapRegisterApi, IdentityUserDto, int>(); +app.MapGroup("api") + .WithTags("Administrator APIs") + .MapAdminUserApi, IdentityUserDto, int>("Admin"); + app.MapGroup("api/account") .WithTags("Account APIs") .MapAccountApi, IdentityUserDto, int>(); diff --git a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md index 77c0d07..e9c21ab 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -99,3 +99,29 @@ app.MapGroup("api").MapLoginApi() .MapRegisterApi(); app.MapGroup("api/account").MapAccountApi(); ``` + + +## Email verification + +The basic sample uses SQLite (a relational provider is required by the atomic verification store) and MailKit SMTP delivery. It defaults to a local SMTP development server at `localhost:1025` without TLS. Run Mailpit or configure SMTP through environment variables/user secrets before testing registration. + +The sample's DbContext includes the verification entities: + +```cs +protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddVerificationRequestEntity(); +} +``` + +The service setup calls `AddVerificationServices()`, registers `AddVerificationRequestStore()`, and adds the optional `AddMailKitVerificationSender, int>()`. + +The registration flow is: + +1. `POST /api/register` creates a pending account and sends a code. +2. `POST /api/register/verify` accepts the opaque verification handle and code, confirms the email, and issues the application token. +3. `POST /api/register/resend` rotates the code while keeping the same handle. + +The sample also maps `POST /api/admin/users` under the named `Admin` policy. The policy requires the `Administrator` role. The endpoint creates an already-confirmed account and returns the user DTO without issuing a token. + +Do not use the sample SMTP defaults in production. Configure TLS, secrets, persistent Data Protection keys, database migrations, and operational cleanup for expired verification records and send-history rows. diff --git a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj index f04a13c..64fc0e8 100644 --- a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj +++ b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj @@ -6,13 +6,14 @@ - + + diff --git a/Samples/RuntimeApps.Authentication.Sample/appsettings.json b/Samples/RuntimeApps.Authentication.Sample/appsettings.json index d80e44d..970a9a9 100644 --- a/Samples/RuntimeApps.Authentication.Sample/appsettings.json +++ b/Samples/RuntimeApps.Authentication.Sample/appsettings.json @@ -11,5 +11,19 @@ "Audience": "Runtime Apps Authentication Sample 1", "Issuer": "Runtime Apps Authentication Sample 1", "ExpireInMinute": 1000 + }, + "ConnectionStrings": { + "Authentication": "Data Source=authentication.db" + }, + "Authentication": { + "Verification": { + "Smtp": { + "Host": "localhost", + "Port": 1025, + "SocketOptions": "None", + "FromAddress": "noreply@example.com", + "FromName": "RuntimeApps Authentication Sample" + } + } } } diff --git a/Tests/RuntimeApps.Authentication.Test/EfVerificationRequestStoreTest.cs b/Tests/RuntimeApps.Authentication.Test/EfVerificationRequestStoreTest.cs new file mode 100644 index 0000000..4212e2a --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/EfVerificationRequestStoreTest.cs @@ -0,0 +1,86 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.EF.Extensions; +using RuntimeApps.Authentication.EF.Store; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Test { + public class EfVerificationRequestStoreTest { + [Fact] + public async Task RequestCanBeCreatedResentAndConsumedOnlyOnce() { + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var options = new DbContextOptionsBuilder().UseSqlite(connection).Options; + await using var db = new TestDbContext(options); + await db.Database.EnsureCreatedAsync(); + var store = new EfVerificationRequestStore(db); + var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + var request = CreateRequest(10, "handle-hash", now); + + Assert.True(await store.TryCreateAsync(request, now.AddHours(-1), 5)); + Assert.True(request.Id > 0); + Assert.True(await store.TrySetInitialVerifierAsync(request.Id, "protected-v1", now, now.AddMinutes(10))); + + var persisted = await store.FindByHandleHashAsync("handle-hash"); + Assert.NotNull(persisted); + Assert.Equal(1, persisted.CodeVersion); + + Assert.True(await store.TryIncrementFailedAttemptsAsync(request.Id, 1, 5, now.AddSeconds(10))); + + var resentAt = now.AddMinutes(2); + Assert.True(await store.TryResendAsync( + request.Id, 1, "protected-v2", resentAt, resentAt.AddMinutes(10), + TimeSpan.FromSeconds(60), now.AddHours(-1), 5)); + Assert.False(await store.TryConsumeAsync(request.Id, 1, resentAt.AddSeconds(1))); + Assert.True(await store.TryConsumeAsync(request.Id, 2, resentAt.AddSeconds(1))); + Assert.False(await store.TryConsumeAsync(request.Id, 2, resentAt.AddSeconds(2))); + + var completed = await db.Set>().AsNoTracking().SingleAsync(); + Assert.Equal(VerificationRequestStatus.Completed, completed.Status); + Assert.Equal(2, completed.CodeVersion); + Assert.Equal(1, completed.FailedAttempts); + } + + [Fact] + public async Task SendRateLimitIsSharedAcrossRequestsForSameDestination() { + await using var connection = new SqliteConnection("Data Source=:memory:"); + await connection.OpenAsync(); + var options = new DbContextOptionsBuilder().UseSqlite(connection).Options; + await using var db = new TestDbContext(options); + await db.Database.EnsureCreatedAsync(); + var store = new EfVerificationRequestStore(db); + var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + Assert.True(await store.TryCreateAsync(CreateRequest(10, "first", now), now.AddHours(-1), 1)); + Assert.False(await store.TryCreateAsync(CreateRequest(20, "second", now.AddSeconds(1)), now.AddHours(-1), 1)); + } + + private static VerificationRequest CreateRequest(int userId, string handleHash, DateTimeOffset now) => new() { + UserId = userId, + Purpose = VerificationPurpose.Registration, + Channel = VerificationChannel.Email, + Destination = "person@example.com", + NormalizedDestination = "PERSON@EXAMPLE.COM", + PublicHandleHash = handleHash, + CodeVerifier = string.Empty, + CodeVersion = 0, + FailedAttempts = 0, + SendCount = 1, + CreatedAt = now, + LastSentAt = now, + ExpiresAt = now.AddMinutes(10), + Status = VerificationRequestStatus.Pending + }; + + private sealed class TestDbContext : IdentityDbContext, IdentityRole, int> { + public TestDbContext(DbContextOptions options) : base(options) { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddVerificationRequestEntity(); + } + } + } +} \ No newline at end of file diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs new file mode 100644 index 0000000..7c6e64e --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs @@ -0,0 +1,89 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using Moq; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Model; +using RuntimeApps.Authentication.Service; + +namespace RuntimeApps.Authentication.Test { + public class RegistrationServiceTest { + [Fact] + public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() { + var userManager = new Mock>(); + var updater = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; + var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); + + userManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + userManager.Setup(manager => manager.CreateAsync(user, "StrongPassword!1")).ReturnsAsync(IdentityResult.Success); + workflow.Setup(service => service.StartAsync( + user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, + null, null, It.IsAny())) + .ReturnsAsync(VerificationOperationResult.Success("opaque-handle", expiresAt)); + + var service = CreateService(userManager, updater, workflow, account); + var result = await service.RegisterAsync(user, "StrongPassword!1"); + + Assert.True(result.Succeeded); + Assert.Equal("opaque-handle", result.Data.VerificationHandle); + Assert.False(user.EmailConfirmed); + userManager.Verify(manager => manager.CreateAsync(user, "StrongPassword!1"), Times.Once); + account.Verify(manager => manager.CompleteRegistrationAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Register_ExistingPendingUser_DoesNotReplacePassword() { + var userManager = new Mock>(); + var updater = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var existing = new IdentityUser { Email = "pending@example.com", UserName = "old-name" }; + var requested = new IdentityUser { Email = existing.Email, UserName = "new-name" }; + var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); + + userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); + userManager.Setup(manager => manager.UpdateAsync(existing)).ReturnsAsync(IdentityResult.Success); + workflow.Setup(service => service.StartAsync( + existing, VerificationPurpose.Registration, VerificationChannel.Email, existing.Email, + null, null, It.IsAny())) + .ReturnsAsync(VerificationOperationResult.Success("new-handle", expiresAt)); + + var service = CreateService(userManager, updater, workflow, account); + var result = await service.RegisterAsync(requested, "AttackerSuppliedPassword!"); + + Assert.True(result.Succeeded); + userManager.Verify(manager => manager.CreateAsync(It.IsAny(), It.IsAny()), Times.Never); + userManager.Verify(manager => manager.UpdateAsync(existing), Times.Once); + updater.Verify(item => item.UpdatePendingUserAsync(existing, requested, It.IsAny()), Times.Once); + } + + [Fact] + public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSending() { + var userManager = new Mock>(); + var updater = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var existing = new IdentityUser { Email = "confirmed@example.com", EmailConfirmed = true }; + userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); + + var service = CreateService(userManager, updater, workflow, account); + var result = await service.RegisterAsync(new IdentityUser { Email = existing.Email }, "Password!"); + + Assert.True(result.Succeeded); + Assert.False(string.IsNullOrWhiteSpace(result.Data.VerificationHandle)); + workflow.Verify(item => item.StartAsync( + It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + private static RegistrationService CreateService( + Mock> userManager, + Mock> updater, + Mock> workflow, + Mock> account) => + new(userManager.Object, updater.Object, workflow.Object, account.Object, + Options.Create(new VerificationOptions())); + } +} \ No newline at end of file diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index 687236a..04e8ee4 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -235,49 +235,28 @@ public async Task ExternalLogin_Success_CreateNewUser() { } [Fact] - public async Task ExternalLogin_Success_ExistUser() { - //Arrange - string provider = "Google", token = "token"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - var appToken = new Model.Token() { - AuthenticationToken = "", - ExpireDate = DateTimeOffset.Now.AddDays(30), - }; + public async Task ExternalLogin_ExistingEmail_DoesNotAutomaticallyLink() { + const string provider = "Google"; + const string token = "provider-token"; + var existingUser = new IdentityUser { Email = "existing@example.com", EmailConfirmed = true }; var loginInfo = new UserLoginInfo(provider, token, provider); - _externalLoginProvider1.SetupGet(e => e.Provider) - .Returns("Not Selected Provided"); - _externalLoginProvider2.SetupGet(e => e.Provider) - .Returns(provider); - _externalLoginProvider2.Setup(e => e.ValidateAsync(token)) + _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); + _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); + _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { - User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false + User = new IdentityUser { Email = existingUser.Email }, + LoginInfo = loginInfo, + Email = existingUser.Email, + EmailVerified = true }); - _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) - .ReturnsAsync(nullUSer); - _userManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) - .ReturnsAsync(user); - _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted( - provider, It.IsAny>())) - .Returns(true); - _userManagerMock.Setup(u => u.UpdateAsync(user)).ReturnsAsync(IdentityResult.Success); - _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) - .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) - .ReturnsAsync(appToken); + _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _userManagerMock.Setup(manager => manager.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); - //Act var result = await _userAccountService.ExternalLoginAsync(provider, token); - //Assert - result.Succeeded.Should().BeTrue(); - result.Data.Should().NotBeNull() - .And.Be(user); - result.Meta.Should().NotBeNull() - .And.Be(appToken); - _userManagerMock.Verify(u => u.CreateAsync(It.IsAny()), Times.Never()); - _userManagerMock.Verify(u => u.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Once()); + Assert.False(result.Succeeded); + Assert.Equal(RuntimeApps.Authentication.Model.ResultCode.Conflict, result.Code); + _userManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } [Fact] diff --git a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs index c4c1623..3588fac 100644 --- a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs @@ -1,3 +1,5 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; using RuntimeApps.Authentication.Model; using RuntimeApps.Authentication.Service; @@ -31,6 +33,29 @@ public async Task RandomVerificationCodeGenerator_GeneratesConfiguredNumericCode Assert.All(code, character => Assert.InRange(character, '0', '9')); } + [Fact] + public void DataProtectionVerifier_BindsCodeToRequestAndDestination() { + var services = new ServiceCollection(); + services.AddDataProtection(); + using var provider = services.BuildServiceProvider(); + var verifier = new DataProtectionVerificationCodeVerifier( + provider.GetRequiredService()); + var request = new VerificationRequest { + Id = "request-1", + UserId = "user-1", + Purpose = VerificationPurpose.Registration, + Channel = VerificationChannel.Email, + NormalizedDestination = "PERSON@EXAMPLE.COM" + }; + request.CodeVerifier = verifier.CreateVerifier("123456", request); + + Assert.True(verifier.Verify("123456", request)); + Assert.False(verifier.Verify("123457", request)); + + request.NormalizedDestination = "OTHER@EXAMPLE.COM"; + Assert.False(verifier.Verify("123456", request)); + } + [Fact] public void VerificationOptions_RejectsInvalidSecurityLimits() { var options = new VerificationOptions { MaximumFailedAttempts = 0 }; From 5f0db96f9e74e697470b3d511cbe7f8c2d4931bf Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:05:09 +0100 Subject: [PATCH 06/18] Fix Google provider result initializer syntax --- .../GoogleExternalLoginProvider.cs | 48 ++++++++++++------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs index eb49580..7c7d1fd 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs @@ -1,35 +1,49 @@ -using Google.Apis.Auth; +using Google.Apis.Auth; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Interface; using RuntimeApps.Authentication.Model; namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { - public class GoogleExternalLoginProvider: IExternalLoginProvider + public class GoogleExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { - private readonly IOptions> _option; + private readonly IOptions> _options; - public GoogleExternalLoginProvider(ILogger> logger, IOptions> option) { - _logger = logger; - _option = option; + public GoogleExternalLoginProvider(IOptions> options) { + _options = options; } public string Provider => "GOOGLE"; public async Task> ValidateAsync(string token) { + var option = _options.Value; + if(string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(option.ClientId)) + return null; + try { - var option = _option.Value; - var settings = new GoogleJsonWebSignature.ValidationSettings() { - Audience = new List() { option.ClientId } - }; - GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(token, settings); + var payload = await GoogleJsonWebSignature.ValidateAsync(token, + new GoogleJsonWebSignature.ValidationSettings { + Audience = new[] { option.ClientId } + }); + + if(string.IsNullOrWhiteSpace(payload.Subject)) + return null; + var user = option.Mapper(payload); - var userLogin = new UserLoginInfo(Provider, payload.Subject, Provider); - return new ExternalLoginProviderResult {\n User = user,\n LoginInfo = userLogin,\n Email = payload.Email,\n EmailVerified = payload.EmailVerified,\n HostedDomain = payload.HostedDomain\n }; - } catch(Exception ex) { - _logger.LogError(ex, ex.Message); - return (null, null); + if(user == null) + return null; + + return new ExternalLoginProviderResult { + User = user, + LoginInfo = new UserLoginInfo(Provider, payload.Subject, Provider), + Email = payload.Email, + EmailVerified = payload.EmailVerified, + HostedDomain = payload.HostedDomain + }; + } catch(Exception) { + // Provider validation exceptions may contain token-related details; never log them. + return null; } } } -} +} \ No newline at end of file From f345718cd569eea17a3c1589c75f4c55ca3c0a40 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:05:42 +0100 Subject: [PATCH 07/18] Upgrade MailKit to patched 4.18.2 release --- .../RuntimeApps.Authentication.MailKit.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj b/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj index 7f8af4c..ab0a31a 100644 --- a/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj +++ b/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj @@ -4,7 +4,7 @@ enable - + From ba5eb5712aa284abe58a5b5cd1f41fc050c0fed4 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:06:11 +0100 Subject: [PATCH 08/18] Validate Microsoft external identity tokens correctly --- .../MicrosoftExternalLoginProvider.cs | 78 +++++++++++++++---- 1 file changed, 61 insertions(+), 17 deletions(-) diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs index 531b930..42bb2b6 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs @@ -1,4 +1,4 @@ -using System.IdentityModel.Tokens.Jwt; +using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; @@ -7,7 +7,7 @@ using RuntimeApps.Authentication.Model; namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { - public class MicrosoftExternalLoginProvider: IExternalLoginProvider + public class MicrosoftExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { private readonly IOptions> _options; @@ -17,25 +17,69 @@ public MicrosoftExternalLoginProvider(IOptions "MICROSOFT"; - public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { + public async Task> ValidateAsync(string token) { var option = _options.Value; + if(string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(option.ClientId) || + string.IsNullOrWhiteSpace(option.IssuerEndpoint) || string.IsNullOrWhiteSpace(option.ConfigurationAddress)) + return null; - var openidConfiguration = await OpenIdConnectConfigurationRetriever.GetAsync( - new Uri(new Uri(option.IssuerEndpoint), option.ConfigurationAddress.TrimStart('/')).ToString(), CancellationToken.None); + try { + var issuerEndpoint = option.IssuerEndpoint.EndsWith("/", StringComparison.Ordinal) + ? option.IssuerEndpoint + : option.IssuerEndpoint + "/"; + var metadataAddress = new Uri( + new Uri(issuerEndpoint), option.ConfigurationAddress.TrimStart('/')).ToString(); + var configuration = await OpenIdConnectConfigurationRetriever.GetAsync( + metadataAddress, CancellationToken.None); + var handler = new JwtSecurityTokenHandler(); + handler.ValidateToken(token, new TokenValidationParameters { + IssuerSigningKeys = configuration.SigningKeys, + ValidateIssuerSigningKey = true, + ValidateIssuer = true, + ValidateAudience = true, + ValidAudience = option.ClientId, + ValidateLifetime = true, + RequireExpirationTime = true, + ClockSkew = TimeSpan.FromMinutes(2), + IssuerValidator = (issuer, securityToken, parameters) => { + var jwt = securityToken as JwtSecurityToken; + var tenantId = jwt?.Claims.FirstOrDefault(claim => claim.Type == "tid")?.Value; + if(!Guid.TryParse(tenantId, out var parsedTenantId)) + throw new SecurityTokenInvalidIssuerException("The Microsoft identity token has no valid tenant identifier."); - var tokenHandler = new JwtSecurityTokenHandler(); - tokenHandler.ValidateToken(token, new TokenValidationParameters { - IssuerSigningKeys = openidConfiguration.SigningKeys, - ValidateIssuer = false, - ValidateAudience = false, - ValidateLifetime = false - }, out SecurityToken validatedToken); + var expectedIssuer = configuration.Issuer.Replace( + "{tenantid}", parsedTenantId.ToString(), StringComparison.OrdinalIgnoreCase); + if(!string.Equals(issuer, expectedIssuer, StringComparison.OrdinalIgnoreCase)) + throw new SecurityTokenInvalidIssuerException("The Microsoft identity token issuer is invalid."); + return issuer; + } + }, out var validatedToken); - var jwtToken = (JwtSecurityToken)validatedToken; - var user = option.Mapper(jwtToken); - var loginInfo = new UserLoginInfo(Provider, jwtToken.Claims.FirstOrDefault(x => x.Type == "oid")?.Value, Provider); - return (user, loginInfo); + var jwtToken = validatedToken as JwtSecurityToken; + var objectId = jwtToken?.Claims.FirstOrDefault(claim => claim.Type == "oid")?.Value; + var tenantIdClaim = jwtToken?.Claims.FirstOrDefault(claim => claim.Type == "tid")?.Value; + if(string.IsNullOrWhiteSpace(objectId) || string.IsNullOrWhiteSpace(tenantIdClaim)) + return null; + + var user = option.Mapper(jwtToken); + if(user == null) + return null; + + return new ExternalLoginProviderResult { + User = user, + LoginInfo = new UserLoginInfo(Provider, $"{tenantIdClaim}:{objectId}", Provider), + Email = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "email")?.Value, + // Microsoft email claims are mutable and do not prove mailbox ownership. + EmailVerified = false + }; + } catch(SecurityTokenException) { + return null; + } catch(HttpRequestException) { + return null; + } catch(InvalidOperationException) { + return null; + } } } -} +} \ No newline at end of file From 6b2da9f21d86f509132535809e6b76ca216993c5 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:06:57 +0100 Subject: [PATCH 09/18] Fix accepted registration endpoint result construction --- .../Controller/AccountApiEndpointRouteBuilderExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index 066db2e..f24a839 100644 --- a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs @@ -79,7 +79,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I mapper.ToUser(user.UserInfo), user.Password, httpContext.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); - return TypedResults.Accepted(value: result); + return TypedResults.Accepted(uri: null, value: result); }); routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( @@ -108,7 +108,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I request.VerificationHandle, httpContext.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); - return TypedResults.Accepted(value: result); + return TypedResults.Accepted(uri: null, value: result); }); return endpoints; From a19ffe1f696200dd03bcf5f646a3816d4e00815c Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:07:47 +0100 Subject: [PATCH 10/18] Disambiguate accepted typed result overload --- .../Controller/AccountApiEndpointRouteBuilderExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index f24a839..e6eece3 100644 --- a/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs @@ -79,7 +79,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I mapper.ToUser(user.UserInfo), user.Password, httpContext.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); - return TypedResults.Accepted(uri: null, value: result); + return TypedResults.Accepted((string)null, result); }); routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( @@ -108,7 +108,7 @@ public static IEndpointRouteBuilder MapRegisterApi(this I request.VerificationHandle, httpContext.RequestAborted); if(!result.Succeeded) return result.CreateValidationProblem(); - return TypedResults.Accepted(uri: null, value: result); + return TypedResults.Accepted((string)null, result); }); return endpoints; From 89ae8807194cfc58724e1dc70cce2943cae404bd Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:08:41 +0100 Subject: [PATCH 11/18] Fix EF verification request set insertion --- .../Store/EfVerificationRequestStore.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs index 71eca51..80d0b0d 100644 --- a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs +++ b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs @@ -74,7 +74,7 @@ await Requests.Where(item => item => item.Status, VerificationRequestStatus.Superseded), cancellationToken); PrepareGeneratedId(request); - await Requests.AddAsync(request, cancellationToken); + await _dbContext.Set>().AddAsync(request, cancellationToken); await _dbContext.Set().AddAsync(new VerificationSend { NormalizedDestination = request.NormalizedDestination, Purpose = request.Purpose, From ebcb961c49416fce627bd4aac178684df0ea1a9d Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:09:44 +0100 Subject: [PATCH 12/18] Update account service tests for verification registration --- .../UserAccountServiceTest.cs | 141 +++++++++--------- 1 file changed, 74 insertions(+), 67 deletions(-) diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index 04e8ee4..7aa84a3 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -53,6 +53,7 @@ public async Task Login_Success() { var user = new IdentityUser() { Id = "userId", UserName = userName, + EmailConfirmed = true }; var token = new Model.Token() { AuthenticationToken = "", @@ -76,6 +77,19 @@ public async Task Login_Success() { .And.Be(token); } + [Fact] + public async Task Login_UnconfirmedEmail_IsRejectedBeforePasswordCheck() { + const string userName = "pending-user"; + var user = new IdentityUser { UserName = userName, Email = "pending@example.com", EmailConfirmed = false }; + _userManagerMock.Setup(manager => manager.FindByNameAsync(userName)).ReturnsAsync(user); + + var result = await _userAccountService.LoginAsync(userName, "password"); + + Assert.False(result.Succeeded); + _signInManagerMock.Verify(manager => manager.PasswordSignInAsync( + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + } + [Fact] public async Task Login_WrongUserName() { //Arrange @@ -115,79 +129,30 @@ public async Task Login_WrongPassword() { } [Fact] - public async Task Register_Success() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - var token = new Model.Token() { + public async Task CompleteRegistration_Success_ConfirmedUser() { + var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = true }; + var token = new Model.Token { AuthenticationToken = "", ExpireDate = DateTimeOffset.Now.AddDays(30), }; - _userManagerMock.Setup(u => u.FindByNameAsync(user.Email)) - .ReturnsAsync(nullUSer); - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) - .ReturnsAsync(token); + _jwtProviderMock.Setup(provider => provider.GenerateTokenAsync(user)).ReturnsAsync(token); - //Act - var result = await _userAccountService.RegisterAsync(user, password); + var result = await _userAccountService.CompleteRegistrationAsync(user); - //Assert result.Succeeded.Should().BeTrue(); - result.Data.Should().NotBeNull() - .And.Be(user); - result.Data.UserName.Should().Be(result.Data.Email); - result.Meta.Should().NotBeNull() - .And.Be(token); + result.Data.Should().Be(user); + result.Meta.Should().Be(token); } [Fact] - public async Task Register_UserExist() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Failed(new IdentityError { - Code = "Failed", - Description = "User Exist!" - })); + public async Task CompleteRegistration_UnconfirmedUser_IsRejected() { + var user = new IdentityUser { Email = "test@test.com", EmailConfirmed = false }; - //Act - var result = await _userAccountService.RegisterAsync(user, password); + var result = await _userAccountService.CompleteRegistrationAsync(user); - //Assert result.Succeeded.Should().BeFalse(); - result.Data.Should().BeNull(); - result.Meta.Should().BeNull(); - } - - [Fact] - public async Task Register_ValidateError() { - //Arrange - string password = "password"; - var user = new IdentityUser() { - Email = "test@test.com" - }; - _userManagerMock.Setup(u => u.CreateAsync(user, password)) - .ReturnsAsync(IdentityResult.Failed(new IdentityError[] { - new IdentityError { - Code = "InvalidPassword", - Description = "Password must be more than 6 character" - } - })); - - //Act - var result = await _userAccountService.RegisterAsync(user, password); - - //Assert - result.Succeeded.Should().BeFalse(); - result.Data.Should().BeNull(); - result.Meta.Should().BeNull(); + result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Forbidden); + _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); } [Fact] @@ -269,21 +234,63 @@ public async Task ExternalLogin_UnverifiedEmail_DoesNotLinkExistingAccount() { _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { - User = new IdentityUser { Email = user.Email }, - LoginInfo = loginInfo, - Email = user.Email, - EmailVerified = false + User = new IdentityUser { Email = user.Email }, LoginInfo = loginInfo, + Email = user.Email, EmailVerified = false }); _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); _userManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); var result = await _userAccountService.ExternalLoginAsync(provider, token); - result.Succeeded.Should().BeFalse(); - result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Conflict); + Assert.False(result.Succeeded); + Assert.Equal(RuntimeApps.Authentication.Model.ResultCode.Conflict, result.Code); _userManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); } + [Fact] + public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() { + const string provider = "Google"; + const string token = "provider-token"; + var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; + var loginInfo = new UserLoginInfo(provider, token, provider); + var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); + var workflow = new Mock>(); + + _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); + _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); + _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) + .ReturnsAsync(new RuntimeApps.Authentication.Model.ExternalLoginProviderResult { + User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false + }); + _userManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _userManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + _userManagerMock.Setup(manager => manager.CreateAsync(user)).ReturnsAsync(IdentityResult.Success); + _userManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); + workflow.Setup(service => service.StartAsync( + user, RuntimeApps.Authentication.Model.VerificationPurpose.Registration, + RuntimeApps.Authentication.Model.VerificationChannel.Email, user.Email, + null, null, It.IsAny())) + .ReturnsAsync(RuntimeApps.Authentication.Model.VerificationOperationResult.Success("external-handle", expiresAt)); + + var service = new UserAccountService( + _userManagerMock.Object, _signInManagerMock.Object, + new IExternalLoginProvider[] { _externalLoginProvider1.Object, _externalLoginProvider2.Object }, + _authenticationHandlerProviderMock.Object, _httpContextAccessorMock.Object, + _userClaimsPrincipalFactoryMock.Object, _authenticationSchemeProviderMock.Object, + _jwtProviderMock.Object, null, null, _externalLoginEmailTrustPolicyMock.Object, + Microsoft.Extensions.Options.Options.Create(new RuntimeApps.Authentication.Model.VerificationOptions { + RequireEmailVerificationForExternalLogins = true + }), workflow.Object); + + var result = await service.ExternalLoginAsync(provider, token); + + Assert.True(result.Succeeded); + Assert.True(result.Meta.VerificationRequired); + Assert.Equal("external-handle", result.Meta.VerificationHandle); + Assert.Null(result.Meta.AuthenticationToken); + _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); + } + [Fact] public async Task ExternalLogin_Success_ExistsLogin() { //Arrange From 3ece2daa20af3fe6bff718bccda34dc7b0265bac Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 00:10:53 +0100 Subject: [PATCH 13/18] Preserve failed-attempt count when rotating verification codes --- .../Store/EfVerificationRequestStore.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs index 80d0b0d..86ec957 100644 --- a/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs +++ b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs @@ -153,7 +153,6 @@ public async Task TryResendAsync( .ExecuteUpdateAsync(setters => setters .SetProperty(item => item.CodeVerifier, newCodeVerifier) .SetProperty(item => item.CodeVersion, item => item.CodeVersion + 1) - .SetProperty(item => item.FailedAttempts, 0) .SetProperty(item => item.SendCount, item => item.SendCount + 1) .SetProperty(item => item.LastSentAt, now) .SetProperty(item => item.ExpiresAt, expiresAt), cancellationToken); From cef8ecf7a7a630152a0f40931bf514752da12447 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 20:48:52 +0100 Subject: [PATCH 14/18] Remove MailKit integration and consolidate CI workflow --- .github/workflows/ci.yml | 22 --------------- .github/workflows/publish.yml | 2 +- ReadMe.md | 14 ++++------ .../MailKitVerificationSenderExtensions.cs | 27 ------------------- .../RuntimeApps.Authentication.MailKit.csproj | 12 --------- RuntimeApps.Authentication.sln | 6 ----- .../Model/RegistrationVerificationResponse.cs | 4 +++ .../Model/SmtpVerificationOptions.cs | 2 +- .../Program.cs | 16 +++++------ .../ReadMe.md | 4 +-- .../RuntimeApps.Authentication.Sample.csproj | 2 +- .../Services}/MailKitVerificationSender.cs | 4 +-- 12 files changed, 22 insertions(+), 93 deletions(-) delete mode 100644 .github/workflows/ci.yml delete mode 100644 RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs delete mode 100644 RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj rename {RuntimeApps.Authentication.MailKit => Samples/RuntimeApps.Authentication.Sample}/Model/SmtpVerificationOptions.cs (95%) rename {RuntimeApps.Authentication.MailKit/Service => Samples/RuntimeApps.Authentication.Sample/Services}/MailKitVerificationSender.cs (95%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 7429129..0000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: CI - -on: - pull_request: - branches: [ main ] - push: - branches: [ main, "feature/**" ] - -jobs: - build-and-test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: 10.0.x - - name: Restore - run: dotnet restore RuntimeApps.Authentication.sln - - name: Build - run: dotnet build RuntimeApps.Authentication.sln --configuration Release --no-restore - - name: Test - run: dotnet test Tests/RuntimeApps.Authentication.Test/RuntimeApps.Authentication.Test.csproj --configuration Release --no-build diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index fad940c..51a720f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -10,7 +10,7 @@ on: - '*' pull_request: branches: - - '*' # Run the workflow for all pull requests + - 'main' # Run the workflow only for pull requests targeting main env: DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 diff --git a/ReadMe.md b/ReadMe.md index 17afab0..07d7e3f 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -233,17 +233,13 @@ builder.Services.AddVerificationRequestStore(); The DbContext must use a relational provider. Verification state changes and destination-level rate limits rely on atomic relational operations; EF InMemory is not supported. Add a migration after adding the verification entities. -The optional `RuntimeApps.Authentication.MailKit` package provides an SMTP sender without adding MailKit to the core package: +The library deliberately does not include an email/SMS delivery implementation. Each application must implement `IVerificationSender` and register it in DI. The basic sample contains a MailKit SMTP implementation that you can use as a starting point: ```cs -builder.Services.AddMailKitVerificationSender, int>(options => { - options.Host = configuration["Authentication:Verification:Smtp:Host"]; - options.Port = 587; - options.SocketOptions = MailKit.Security.SecureSocketOptions.StartTls; - options.UserName = configuration["Authentication:Verification:Smtp:UserName"]; - options.Password = configuration["Authentication:Verification:Smtp:Password"]; - options.FromAddress = configuration["Authentication:Verification:Smtp:FromAddress"]; -}); +builder.Services.Configure( + configuration.GetSection(SmtpVerificationOptions.SectionName)); +builder.Services.AddScoped, int>, + MailKitVerificationSender, int>>(); ``` Keep SMTP credentials in user secrets, environment variables, or a secret manager. Persist and share the ASP.NET Core Data Protection key ring across application instances. diff --git a/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs b/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs deleted file mode 100644 index d04d616..0000000 --- a/RuntimeApps.Authentication.MailKit/Extensions/MailKitVerificationSenderExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using RuntimeApps.Authentication.Interface; -using RuntimeApps.Authentication.MailKit.Model; -using RuntimeApps.Authentication.MailKit.Service; - -namespace RuntimeApps.Authentication.MailKit.Extensions { - public static class MailKitVerificationSenderExtensions { - public static IServiceCollection AddMailKitVerificationSender( - this IServiceCollection services, - Action configure) - where TKey : IEquatable { - ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(configure); - - services.AddOptions() - .Configure(configure) - .Validate(options => options.IsValid(), "SMTP verification options are invalid.") - .ValidateOnStart(); - - services.Replace(ServiceDescriptor.Scoped< - IVerificationSender, - MailKitVerificationSender>()); - return services; - } - } -} \ No newline at end of file diff --git a/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj b/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj deleted file mode 100644 index ab0a31a..0000000 --- a/RuntimeApps.Authentication.MailKit/RuntimeApps.Authentication.MailKit.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - net10.0 - enable - - - - - - - - \ No newline at end of file diff --git a/RuntimeApps.Authentication.sln b/RuntimeApps.Authentication.sln index 7c63ccd..fdac239 100644 --- a/RuntimeApps.Authentication.sln +++ b/RuntimeApps.Authentication.sln @@ -7,8 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.EF", "RuntimeApps.Authentication.EF\RuntimeApps.Authentication.EF.csproj", "{366669C0-AF34-42D9-B54F-F884AAB5F9E2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.MailKit", "RuntimeApps.Authentication.MailKit\RuntimeApps.Authentication.MailKit.csproj", "{2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{58197192-84A5-4423-8DD9-60DBA205E544}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RuntimeApps.Authentication.Sample", "Samples\RuntimeApps.Authentication.Sample\RuntimeApps.Authentication.Sample.csproj", "{1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}" @@ -45,10 +43,6 @@ Global {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Debug|Any CPU.Build.0 = Debug|Any CPU {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Release|Any CPU.ActiveCfg = Release|Any CPU {366669C0-AF34-42D9-B54F-F884AAB5F9E2}.Release|Any CPU.Build.0 = Release|Any CPU - {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2D5F4F98-3C73-4B75-A6C7-0F8C31F2A2B1}.Release|Any CPU.Build.0 = Release|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E1CB894-D6FE-4CB1-8B7F-AB802927BFF7}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs index c9e5341..7dd48af 100644 --- a/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs +++ b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs @@ -1,5 +1,9 @@ namespace RuntimeApps.Authentication.Model { public sealed class RegistrationVerificationResponse { + /// + /// A generic client-facing message returned for registration and resend requests. + /// It deliberately does not disclose whether an account exists or whether a message was sent. + /// public string Message { get; init; } = "If the account can be registered, a verification message will be sent."; public string VerificationHandle { get; init; } public DateTimeOffset ExpiresAt { get; init; } diff --git a/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs b/Samples/RuntimeApps.Authentication.Sample/Model/SmtpVerificationOptions.cs similarity index 95% rename from RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs rename to Samples/RuntimeApps.Authentication.Sample/Model/SmtpVerificationOptions.cs index e45917a..1193ec8 100644 --- a/RuntimeApps.Authentication.MailKit/Model/SmtpVerificationOptions.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Model/SmtpVerificationOptions.cs @@ -1,7 +1,7 @@ using System.Net.Mail; using MailKit.Security; -namespace RuntimeApps.Authentication.MailKit.Model { +namespace RuntimeApps.Authentication.Sample.Model { public sealed class SmtpVerificationOptions { public const string SectionName = "Authentication:Verification:Smtp"; diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index a0e1f1e..726fbe7 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -3,8 +3,8 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; -using MailKit.Security; -using RuntimeApps.Authentication.MailKit.Extensions; +using RuntimeApps.Authentication.Sample.Services; +using RuntimeApps.Authentication.Sample.Model; using Microsoft.IdentityModel.Tokens; using RuntimeApps.Authentication.Controller; using RuntimeApps.Authentication.EF.Extensions; @@ -76,14 +76,10 @@ }); builder.Services.AddVerificationRequestStore(); -builder.Services.AddMailKitVerificationSender, int>(options => { - options.Host = builder.Configuration["Authentication:Verification:Smtp:Host"] ?? "localhost"; - options.Port = builder.Configuration.GetValue("Authentication:Verification:Smtp:Port", 1025); - options.SocketOptions = builder.Configuration.GetValue("Authentication:Verification:Smtp:SocketOptions", SecureSocketOptions.None); - options.FromAddress = builder.Configuration["Authentication:Verification:Smtp:FromAddress"] ?? "noreply@example.com"; - options.FromName = "RuntimeApps Authentication Sample"; - options.ApplicationName = "RuntimeApps Authentication Sample"; -}); +builder.Services.Configure( + builder.Configuration.GetSection(SmtpVerificationOptions.SectionName)); +builder.Services.AddScoped, int>, + MailKitVerificationSender, int>>(); builder.Services.AddAuthorization(options => options.AddPolicy("Admin", policy => policy.RequireRole("Administrator"))); diff --git a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md index e9c21ab..9eef15f 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -103,7 +103,7 @@ app.MapGroup("api/account").MapAccountApi ## Email verification -The basic sample uses SQLite (a relational provider is required by the atomic verification store) and MailKit SMTP delivery. It defaults to a local SMTP development server at `localhost:1025` without TLS. Run Mailpit or configure SMTP through environment variables/user secrets before testing registration. +The basic sample uses SQLite (a relational provider is required by the atomic verification store) and demonstrates an SMTP sender implemented with MailKit. MailKit is referenced only by this sample; the authentication library itself does not provide or require an email-delivery implementation. The sample defaults to a local SMTP development server at `localhost:1025` without TLS. Run Mailpit or configure SMTP through environment variables/user secrets before testing registration. The sample's DbContext includes the verification entities: @@ -114,7 +114,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { } ``` -The service setup calls `AddVerificationServices()`, registers `AddVerificationRequestStore()`, and adds the optional `AddMailKitVerificationSender, int>()`. +The service setup calls `AddVerificationServices()`, registers `AddVerificationRequestStore()`, and registers the sample's `IVerificationSender, int>` implementation. In your own application, implement `IVerificationSender` for your delivery provider (SMTP, email API, SMS, etc.) and register it in dependency injection. The MailKit implementation in this sample is an example, not a library integration. The registration flow is: diff --git a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj index 64fc0e8..6cccb51 100644 --- a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj +++ b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj @@ -7,13 +7,13 @@ + - diff --git a/RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs b/Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs similarity index 95% rename from RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs rename to Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs index cd18d34..e6a209c 100644 --- a/RuntimeApps.Authentication.MailKit/Service/MailKitVerificationSender.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs @@ -2,10 +2,10 @@ using Microsoft.Extensions.Options; using MimeKit; using RuntimeApps.Authentication.Interface; -using RuntimeApps.Authentication.MailKit.Model; +using RuntimeApps.Authentication.Sample.Model; using RuntimeApps.Authentication.Model; -namespace RuntimeApps.Authentication.MailKit.Service { +namespace RuntimeApps.Authentication.Sample.Services { public sealed class MailKitVerificationSender : IVerificationSender where TKey : IEquatable { private readonly SmtpVerificationOptions _options; From c1869f47fd2dcd94dc7efdc13f1e3e7b9b62511c Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 20:49:30 +0100 Subject: [PATCH 15/18] Validate sample SMTP configuration on startup --- Samples/RuntimeApps.Authentication.Sample/Program.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index 726fbe7..f93f386 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -76,8 +76,10 @@ }); builder.Services.AddVerificationRequestStore(); -builder.Services.Configure( - builder.Configuration.GetSection(SmtpVerificationOptions.SectionName)); +builder.Services.AddOptions() + .BindConfiguration(SmtpVerificationOptions.SectionName) + .Validate(options => options.IsValid(), "SMTP verification options are invalid.") + .ValidateOnStart(); builder.Services.AddScoped, int>, MailKitVerificationSender, int>>(); From d2672dbf7266800512440ec7626d61f8610b25b7 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 22:59:46 +0100 Subject: [PATCH 16/18] Improve external provider diagnostics and clarify registration behavior --- ReadMe.md | 32 +++++++++++++++-- .../Model/RegistrationVerificationResponse.cs | 2 +- .../RuntimeApps.Authentication.csproj | 1 + .../RuntimeAppsAuthenticationBuilder.cs | 1 + .../FacebookExternalLoginProvider.cs | 31 ++++++++++++---- .../GoogleExternalLoginProvider.cs | 17 ++++++--- .../MicrosoftExternalLoginProvider.cs | 36 +++++++++++++++---- .../Service/RegistrationService.cs | 2 ++ .../Program.cs | 4 ++- .../ReadMe.md | 2 ++ 10 files changed, 107 insertions(+), 21 deletions(-) diff --git a/ReadMe.md b/ReadMe.md index 07d7e3f..e9057e1 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -231,7 +231,7 @@ modelBuilder.AddVerificationRequestEntity(); builder.Services.AddVerificationRequestStore(); ``` -The DbContext must use a relational provider. Verification state changes and destination-level rate limits rely on atomic relational operations; EF InMemory is not supported. Add a migration after adding the verification entities. +The DbContext must use a relational provider. Verification state changes and destination-level rate limits rely on atomic relational operations; EF InMemory is not supported. Add a migration after adding the verification entities. The basic sample uses SQLite because it is relational and supports the required transactions and conditional updates. The library deliberately does not include an email/SMS delivery implementation. Each application must implement `IVerificationSender` and register it in DI. The basic sample contains a MailKit SMTP implementation that you can use as a starting point: @@ -242,7 +242,7 @@ builder.Services.AddScoped, int>, MailKitVerificationSender, int>>(); ``` -Keep SMTP credentials in user secrets, environment variables, or a secret manager. Persist and share the ASP.NET Core Data Protection key ring across application instances. +Keep SMTP credentials in user secrets, environment variables, or a secret manager. Persist and share the ASP.NET Core Data Protection key ring across application instances. The sample uses `EnsureCreated` only to create its local development database without checked-in migration files; `EnsureCreated` does not apply or update migrations. Production applications should create and apply EF Core migrations as part of deployment. ### Registration endpoints @@ -256,7 +256,33 @@ The API returns an opaque, cryptographically random verification handle. Only it Default limits are six numeric digits, ten-minute lifetime, five failed attempts, a 60-second resend cooldown, and five sends per destination/purpose/channel per hour. A successful verification is single-use. A resend rotates the code. The EF store uses relational transactions and conditional updates for concurrent operations. -Repeating registration recovers a pending account if the client lost its handle. It does not replace the password on an existing pending account. The default updater changes only the username and phone number; implement `IUserRegistrationUpdater` to allow other safe profile fields. Do not copy passwords, roles, claims, security stamps, or external logins from an unauthenticated repeat request. +Repeating registration recovers a pending account if the client lost its handle. It does not replace the password on an existing pending account. The default updater changes only the username and phone number; implement `IUserRegistrationUpdater` to allow other explicitly approved profile fields. Do not copy passwords, roles, claims, security stamps, lockout state, two-factor settings, or external logins from an unauthenticated repeat request. + +For a custom user model, explicitly allowlist the profile fields that may be updated when an unconfirmed account registers again. The default updater changes only `UserName` and `PhoneNumber`; it intentionally does not copy arbitrary properties. For example: + +```cs +public sealed class AppUser : IdentityUser { + public string DisplayName { get; set; } +} + +public sealed class AppUserRegistrationUpdater : IUserRegistrationUpdater { + public Task UpdatePendingUserAsync( + AppUser existingUser, + AppUser requestedUser, + CancellationToken cancellationToken = default) { + existingUser.UserName = requestedUser.UserName; + existingUser.PhoneNumber = requestedUser.PhoneNumber; + existingUser.PhoneNumberConfirmed = false; + existingUser.DisplayName = requestedUser.DisplayName; + return Task.CompletedTask; + } +} + +// Register after AddVerificationServices so this replaces the default updater. +builder.Services.AddScoped, AppUserRegistrationUpdater>(); +``` + +Do not copy passwords, roles, claims, security stamps, lockout state, two-factor settings, or external login associations from an unauthenticated repeat-registration request. Confirmed accounts are never modified or registered again; the API deliberately returns the same generic response to prevent account enumeration. ### Administrator provisioning diff --git a/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs index 7dd48af..718a3d6 100644 --- a/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs +++ b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs @@ -4,7 +4,7 @@ public sealed class RegistrationVerificationResponse { /// A generic client-facing message returned for registration and resend requests. /// It deliberately does not disclose whether an account exists or whether a message was sent. /// - public string Message { get; init; } = "If the account can be registered, a verification message will be sent."; + public string Message { get; init; } = "If this email address can be registered, check your inbox for a verification message."; public string VerificationHandle { get; init; } public DateTimeOffset ExpiresAt { get; init; } } diff --git a/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj index 3a763b9..7209d46 100644 --- a/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj +++ b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj @@ -11,6 +11,7 @@ + \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index 17ef441..287b4b8 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -27,6 +27,7 @@ public RuntimeAppsAuthenticationBuilder AddAuthenticationSer Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); Services.AddHttpContextAccessor(); + Services.AddHttpClient(); // Identity services Services.TryAddScoped, UserValidator>(); Services.TryAddScoped, PasswordValidator>(); diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs index 4781385..e70efd8 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs @@ -2,6 +2,7 @@ using System.Text.RegularExpressions; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; using RuntimeApps.Authentication.Interface; using RuntimeApps.Authentication.Model; @@ -11,9 +12,16 @@ namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { public class FacebookExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { private readonly IOptions> _options; + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger> _logger; - public FacebookExternalLoginProvider(IOptions> options) { - _options = options; + public FacebookExternalLoginProvider( + IOptions> options, + IHttpClientFactory httpClientFactory, + ILogger> logger) { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Provider => "FACEBOOK"; @@ -29,7 +37,7 @@ public async Task> ValidateAsync(string token return null; try { - using var client = new HttpClient(); + using var client = _httpClientFactory.CreateClient(nameof(FacebookExternalLoginProvider)); var appTokenUrl = string.Format(CultureInfo.InvariantCulture, option.AccessTokenUrl, Uri.EscapeDataString(option.ClientId), Uri.EscapeDataString(option.ClientSecret)); var appTokenResponse = await client.GetStringAsync(appTokenUrl); @@ -64,11 +72,22 @@ public async Task> ValidateAsync(string token // Facebook's current response model does not provide a trustworthy email-verified assertion. EmailVerified = false }; - } catch(HttpRequestException) { + } catch(HttpRequestException exception) { + // Do not log request URLs: Facebook access tokens are sent in query parameters. + _logger.LogWarning( + "Facebook token validation request failed. Status code: {StatusCode}.", + exception.StatusCode); return null; - } catch(JsonException) { + } catch(JsonException exception) { + _logger.LogWarning("Facebook returned an invalid response: {Reason}", exception.Message); return null; - } catch(FormatException) { + } catch(FormatException exception) { + _logger.LogWarning("Facebook token validation response contained an invalid value: {Reason}", exception.Message); + return null; + } catch(Exception exception) { + _logger.LogError( + "Unexpected Facebook external login validation failure. Exception type: {ExceptionType}.", + exception.GetType().FullName); return null; } } diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs index 7c7d1fd..c7ae4b6 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs @@ -1,6 +1,7 @@ using Google.Apis.Auth; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging; using RuntimeApps.Authentication.Interface; using RuntimeApps.Authentication.Model; @@ -8,9 +9,13 @@ namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { public class GoogleExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { private readonly IOptions> _options; + private readonly ILogger> _logger; - public GoogleExternalLoginProvider(IOptions> options) { - _options = options; + public GoogleExternalLoginProvider( + IOptions> options, + ILogger> logger) { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Provider => "GOOGLE"; @@ -40,8 +45,12 @@ public async Task> ValidateAsync(string token EmailVerified = payload.EmailVerified, HostedDomain = payload.HostedDomain }; - } catch(Exception) { - // Provider validation exceptions may contain token-related details; never log them. + } catch(Exception exception) { + // Log the validation reason, but never log the supplied identity token. + _logger.LogWarning( + "Google external token validation failed. {ExceptionType}: {Reason}", + exception.GetType().FullName, + exception.Message); return null; } } diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs index 42bb2b6..d47b73a 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs @@ -1,6 +1,8 @@ using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using RuntimeApps.Authentication.Interface; @@ -10,9 +12,16 @@ namespace RuntimeApps.Authentication.Service.ExternalLoginProviders { public class MicrosoftExternalLoginProvider : IExternalLoginProvider where TUser : class, new() { private readonly IOptions> _options; + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger> _logger; - public MicrosoftExternalLoginProvider(IOptions> options) { - _options = options; + public MicrosoftExternalLoginProvider( + IOptions> options, + IHttpClientFactory httpClientFactory, + ILogger> logger) { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Provider => "MICROSOFT"; @@ -29,8 +38,10 @@ public async Task> ValidateAsync(string token : option.IssuerEndpoint + "/"; var metadataAddress = new Uri( new Uri(issuerEndpoint), option.ConfigurationAddress.TrimStart('/')).ToString(); + using var client = _httpClientFactory.CreateClient(nameof(MicrosoftExternalLoginProvider)); + var documentRetriever = new HttpDocumentRetriever(client) { RequireHttps = true }; var configuration = await OpenIdConnectConfigurationRetriever.GetAsync( - metadataAddress, CancellationToken.None); + metadataAddress, documentRetriever, CancellationToken.None); var handler = new JwtSecurityTokenHandler(); handler.ValidateToken(token, new TokenValidationParameters { @@ -73,11 +84,24 @@ public async Task> ValidateAsync(string token // Microsoft email claims are mutable and do not prove mailbox ownership. EmailVerified = false }; - } catch(SecurityTokenException) { + } catch(SecurityTokenException exception) { + _logger.LogWarning( + "Microsoft identity token validation failed. {ExceptionType}: {Reason}", + exception.GetType().FullName, + exception.Message); return null; - } catch(HttpRequestException) { + } catch(HttpRequestException exception) { + _logger.LogWarning( + "Microsoft OpenID Connect metadata request failed. Status code: {StatusCode}.", + exception.StatusCode); return null; - } catch(InvalidOperationException) { + } catch(InvalidOperationException exception) { + _logger.LogWarning("Microsoft external login configuration is invalid: {Reason}", exception.Message); + return null; + } catch(Exception exception) { + _logger.LogError( + "Unexpected Microsoft external login validation failure. Exception type: {ExceptionType}.", + exception.GetType().FullName); return null; } } diff --git a/RuntimeApps.Authentication/Service/RegistrationService.cs b/RuntimeApps.Authentication/Service/RegistrationService.cs index 5ca1b0e..c5df4fe 100644 --- a/RuntimeApps.Authentication/Service/RegistrationService.cs +++ b/RuntimeApps.Authentication/Service/RegistrationService.cs @@ -39,6 +39,8 @@ public async Task> RegisterAsync( user.UserName = user.Email; var existingUser = await _userManager.FindByEmailAsync(user.Email); + // Do not create or modify confirmed accounts. Keep the response indistinguishable + // from a pending registration to avoid exposing whether an email is registered. if(existingUser?.EmailConfirmed == true) return GenericResponse(); diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index f93f386..320db18 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -101,10 +101,12 @@ var services = scope.ServiceProvider; try { var context = services.GetRequiredService(); + // The sample has no checked-in migrations. EnsureCreated creates its demo schema + // directly from the EF model; real applications should use EF Core migrations. context.Database.EnsureCreated(); } catch(Exception ex) { var logger = services.GetRequiredService>(); - logger.LogError(ex, "An error occurred while seeding the database."); + logger.LogError(ex, "An error occurred while initializing the sample database."); } } diff --git a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md index 9eef15f..523474f 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -122,6 +122,8 @@ The registration flow is: 2. `POST /api/register/verify` accepts the opaque verification handle and code, confirms the email, and issues the application token. 3. `POST /api/register/resend` rotates the code while keeping the same handle. +The sample uses SQLite because the verification store requires a relational provider; EF Core's InMemory provider does not support the transactional/atomic operations used by the verification store. In Development, `EnsureCreated` initializes the sample database directly from the model because this sample does not include migration files. `EnsureCreated` does not apply later schema changes; production applications should use EF Core migrations. + The sample also maps `POST /api/admin/users` under the named `Admin` policy. The policy requires the `Administrator` role. The endpoint creates an already-confirmed account and returns the user DTO without issuing a token. Do not use the sample SMTP defaults in production. Configure TLS, secrets, persistent Data Protection keys, database migrations, and operational cleanup for expired verification records and send-history rows. From dfda3d5531658ce6c59cea939c231a9077097a04 Mon Sep 17 00:00:00 2001 From: Amin Mirzaee Date: Thu, 19 Nov 2026 23:13:45 +0100 Subject: [PATCH 17/18] Remove pending user registration updater --- ReadMe.md | 28 ++--------------- .../Interface/IUserRegistrationUpdater.cs | 6 ---- .../RuntimeAppsAuthenticationBuilder.cs | 1 - .../Service/DefaultUserRegistrationUpdater.cs | 30 ------------------- .../Service/RegistrationService.cs | 17 ++--------- .../RegistrationServiceTest.cs | 19 +++++------- 6 files changed, 11 insertions(+), 90 deletions(-) delete mode 100644 RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs delete mode 100644 RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs diff --git a/ReadMe.md b/ReadMe.md index e9057e1..16a6dc5 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -256,33 +256,9 @@ The API returns an opaque, cryptographically random verification handle. Only it Default limits are six numeric digits, ten-minute lifetime, five failed attempts, a 60-second resend cooldown, and five sends per destination/purpose/channel per hour. A successful verification is single-use. A resend rotates the code. The EF store uses relational transactions and conditional updates for concurrent operations. -Repeating registration recovers a pending account if the client lost its handle. It does not replace the password on an existing pending account. The default updater changes only the username and phone number; implement `IUserRegistrationUpdater` to allow other explicitly approved profile fields. Do not copy passwords, roles, claims, security stamps, lockout state, two-factor settings, or external logins from an unauthenticated repeat request. +Repeating registration recovers an existing pending account if the client lost its handle. The existing account is reused unchanged: registration does not update its username, phone number, email, password, or any custom properties. If the user needs to change account information, provide a separate authenticated account-management flow or a dedicated recovery process. -For a custom user model, explicitly allowlist the profile fields that may be updated when an unconfirmed account registers again. The default updater changes only `UserName` and `PhoneNumber`; it intentionally does not copy arbitrary properties. For example: - -```cs -public sealed class AppUser : IdentityUser { - public string DisplayName { get; set; } -} - -public sealed class AppUserRegistrationUpdater : IUserRegistrationUpdater { - public Task UpdatePendingUserAsync( - AppUser existingUser, - AppUser requestedUser, - CancellationToken cancellationToken = default) { - existingUser.UserName = requestedUser.UserName; - existingUser.PhoneNumber = requestedUser.PhoneNumber; - existingUser.PhoneNumberConfirmed = false; - existingUser.DisplayName = requestedUser.DisplayName; - return Task.CompletedTask; - } -} - -// Register after AddVerificationServices so this replaces the default updater. -builder.Services.AddScoped, AppUserRegistrationUpdater>(); -``` - -Do not copy passwords, roles, claims, security stamps, lockout state, two-factor settings, or external login associations from an unauthenticated repeat-registration request. Confirmed accounts are never modified or registered again; the API deliberately returns the same generic response to prevent account enumeration. +Confirmed accounts are never modified or registered again; the API returns the same generic response to prevent account enumeration. ### Administrator provisioning diff --git a/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs b/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs deleted file mode 100644 index 99177ee..0000000 --- a/RuntimeApps.Authentication/Interface/IUserRegistrationUpdater.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace RuntimeApps.Authentication.Interface { - /// Copies only explicitly permitted, non-credential fields to an existing pending account. - public interface IUserRegistrationUpdater { - Task UpdatePendingUserAsync(TUser existingUser, TUser requestedUser, CancellationToken cancellationToken = default); - } -} \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index 287b4b8..3dec1a3 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -73,7 +73,6 @@ public RuntimeAppsAuthenticationBuilder AddVerificationServi Services.TryAddScoped, RandomVerificationCodeGenerator>(); Services.TryAddScoped, DataProtectionVerificationCodeVerifier>(); Services.TryAddScoped, VerificationWorkflowService>(); - Services.TryAddScoped, DefaultUserRegistrationUpdater>(); Services.TryAddScoped, RegistrationService>(); return this; } diff --git a/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs b/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs deleted file mode 100644 index 2ed7bfb..0000000 --- a/RuntimeApps.Authentication/Service/DefaultUserRegistrationUpdater.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using RuntimeApps.Authentication.Interface; - -namespace RuntimeApps.Authentication.Service { - /// - /// Updates only username and phone number on an existing pending Identity account. - /// Passwords, email ownership, roles, claims, security stamps, and external logins are not copied. - /// - public sealed class DefaultUserRegistrationUpdater : IUserRegistrationUpdater - where TUser : IdentityUser - where TKey : IEquatable { - public Task UpdatePendingUserAsync( - TUser existingUser, - TUser requestedUser, - CancellationToken cancellationToken = default) { - ArgumentNullException.ThrowIfNull(existingUser); - ArgumentNullException.ThrowIfNull(requestedUser); - - if(!string.IsNullOrWhiteSpace(requestedUser.UserName)) - existingUser.UserName = requestedUser.UserName; - - if(existingUser.PhoneNumber != requestedUser.PhoneNumber) { - existingUser.PhoneNumber = requestedUser.PhoneNumber; - existingUser.PhoneNumberConfirmed = false; - } - - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/RegistrationService.cs b/RuntimeApps.Authentication/Service/RegistrationService.cs index c5df4fe..f32ffcc 100644 --- a/RuntimeApps.Authentication/Service/RegistrationService.cs +++ b/RuntimeApps.Authentication/Service/RegistrationService.cs @@ -8,7 +8,6 @@ public sealed class RegistrationService : IRegistrationService, new() where TKey : IEquatable { private readonly IUserManager _userManager; - private readonly IUserRegistrationUpdater _userUpdater; private readonly IVerificationWorkflowService _verification; private readonly IUserAccountService _accountService; private readonly VerificationOptions _options; @@ -16,13 +15,11 @@ public sealed class RegistrationService : IRegistrationService userManager, - IUserRegistrationUpdater userUpdater, IVerificationWorkflowService verification, IUserAccountService accountService, IOptions options, TimeProvider timeProvider = null) { _userManager = userManager; - _userUpdater = userUpdater; _verification = verification; _accountService = accountService; _options = options.Value; @@ -45,12 +42,7 @@ public async Task> RegisterAsync( return GenericResponse(); if(existingUser != null) { - var existingEmail = existingUser.Email; - await _userUpdater.UpdatePendingUserAsync(existingUser, user, cancellationToken); - existingUser.Email = existingEmail; - var updateResult = await _userManager.UpdateAsync(existingUser); - if(!updateResult.Succeeded) - return new Result(ResultCode.BadRequest, updateResult.Errors); + // Reuse the existing pending account without changing any of its data or credentials. user = existingUser; } else { user.EmailConfirmed = false; @@ -63,12 +55,7 @@ public async Task> RegisterAsync( if(racedUser == null) return new Result(ResultCode.BadRequest, createResult.Errors); - var racedEmail = racedUser.Email; - await _userUpdater.UpdatePendingUserAsync(racedUser, user, cancellationToken); - racedUser.Email = racedEmail; - var updateResult = await _userManager.UpdateAsync(racedUser); - if(!updateResult.Succeeded) - return new Result(ResultCode.BadRequest, updateResult.Errors); + // Another request created this pending account first. Reuse it unchanged. user = racedUser; } } diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs index 7c6e64e..abc1880 100644 --- a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs @@ -10,7 +10,6 @@ public class RegistrationServiceTest { [Fact] public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() { var userManager = new Mock>(); - var updater = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; @@ -23,7 +22,7 @@ public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("opaque-handle", expiresAt)); - var service = CreateService(userManager, updater, workflow, account); + var service = CreateService(userManager, workflow, account); var result = await service.RegisterAsync(user, "StrongPassword!1"); Assert.True(result.Succeeded); @@ -34,9 +33,8 @@ public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() } [Fact] - public async Task Register_ExistingPendingUser_DoesNotReplacePassword() { + public async Task Register_ExistingPendingUser_ReusesAccountWithoutUpdatingIt() { var userManager = new Mock>(); - var updater = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var existing = new IdentityUser { Email = "pending@example.com", UserName = "old-name" }; @@ -44,31 +42,29 @@ public async Task Register_ExistingPendingUser_DoesNotReplacePassword() { var expiresAt = DateTimeOffset.UtcNow.AddMinutes(10); userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); - userManager.Setup(manager => manager.UpdateAsync(existing)).ReturnsAsync(IdentityResult.Success); workflow.Setup(service => service.StartAsync( existing, VerificationPurpose.Registration, VerificationChannel.Email, existing.Email, null, null, It.IsAny())) .ReturnsAsync(VerificationOperationResult.Success("new-handle", expiresAt)); - var service = CreateService(userManager, updater, workflow, account); + var service = CreateService(userManager, workflow, account); var result = await service.RegisterAsync(requested, "AttackerSuppliedPassword!"); Assert.True(result.Succeeded); userManager.Verify(manager => manager.CreateAsync(It.IsAny(), It.IsAny()), Times.Never); - userManager.Verify(manager => manager.UpdateAsync(existing), Times.Once); - updater.Verify(item => item.UpdatePendingUserAsync(existing, requested, It.IsAny()), Times.Once); + Assert.Equal("old-name", existing.UserName); + userManager.Verify(manager => manager.UpdateAsync(It.IsAny()), Times.Never); } [Fact] public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSending() { var userManager = new Mock>(); - var updater = new Mock>(); var workflow = new Mock>(); var account = new Mock>(); var existing = new IdentityUser { Email = "confirmed@example.com", EmailConfirmed = true }; userManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); - var service = CreateService(userManager, updater, workflow, account); + var service = CreateService(userManager, workflow, account); var result = await service.RegisterAsync(new IdentityUser { Email = existing.Email }, "Password!"); Assert.True(result.Succeeded); @@ -80,10 +76,9 @@ public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSe private static RegistrationService CreateService( Mock> userManager, - Mock> updater, Mock> workflow, Mock> account) => - new(userManager.Object, updater.Object, workflow.Object, account.Object, + new(userManager.Object, workflow.Object, account.Object, Options.Create(new VerificationOptions())); } } \ No newline at end of file From 2441280b1775cfdeb2c706440f2734e2cc9ec445 Mon Sep 17 00:00:00 2001 From: Amin Date: Thu, 19 Nov 2026 23:35:36 +0100 Subject: [PATCH 18/18] Fix the bug --- Samples/RuntimeApps.Authentication.Sample/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index 320db18..bcf1946 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -11,6 +11,7 @@ using RuntimeApps.Authentication.Extensions; using RuntimeApps.Authentication.Model; using RuntimeApps.Authentication.Sample; +using RuntimeApps.Authentication.Interface; var builder = WebApplication.CreateBuilder(args);