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 90ad006..16a6dc5 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -202,3 +202,76 @@ 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 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: + +```cs +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. 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 + +| 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 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. + +Confirmed accounts are never modified or registered again; the API returns the same generic response to prevent account enumeration. + +### 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/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..97bc76d --- /dev/null +++ b/RuntimeApps.Authentication.EF/Model/VerificationSendConfiguration.cs @@ -0,0 +1,25 @@ +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 => send.SentAt); + 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..86ec957 --- /dev/null +++ b/RuntimeApps.Authentication.EF/Store/EfVerificationRequestStore.cs @@ -0,0 +1,237 @@ +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); + + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(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 _dbContext.Set>().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; + } + + await Sends.Where(item => item.SentAt < sendsSince).ExecuteDeleteAsync(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; + } + + 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.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/Controller/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Controller/AccountApiEndpointRouteBuilderExtensions.cs index c2afa33..e6eece3 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; @@ -45,18 +46,115 @@ 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) => { + 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) + return result.CreateValidationProblem(); + return TypedResults.Accepted((string)null, result); + }); + + routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( + [FromBody] VerifyRegistrationModel request, + 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) return result.CreateValidationProblem(); return TypedResults.Ok(MapResult(result, mapper)); }); + routeGroup.MapPost("register/resend", async Task>, ValidationProblem>> ( + [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) + return result.CreateValidationProblem(); + return TypedResults.Accepted((string)null, result); + }); + + 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(new AuthorizeAttribute { Roles = "Administrator" }); + 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; } 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/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/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/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..51fe2d9 --- /dev/null +++ b/RuntimeApps.Authentication/Interface/IVerificationWorkflowService.cs @@ -0,0 +1,27 @@ +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, + 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/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/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/Model/RegistrationVerificationResponse.cs b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs new file mode 100644 index 0000000..718a3d6 --- /dev/null +++ b/RuntimeApps.Authentication/Model/RegistrationVerificationResponse.cs @@ -0,0 +1,11 @@ +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 this email address can be registered, check your inbox for a verification message."; + 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/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/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/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/RuntimeApps.Authentication.csproj b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj index 5a21fd9..7209d46 100644 --- a/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj +++ b/RuntimeApps.Authentication/RuntimeApps.Authentication.csproj @@ -1,16 +1,17 @@ - + net10.0 enable - + + + - - + \ No newline at end of file diff --git a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs index 42ce184..3dec1a3 100644 --- a/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs +++ b/RuntimeApps.Authentication/RuntimeAppsAuthenticationBuilder.cs @@ -24,8 +24,10 @@ public RuntimeAppsAuthenticationBuilder(AuthenticationBuilder authenticationBuil public RuntimeAppsAuthenticationBuilder AddAuthenticationServices() { Services.TryAddScoped, UserAccountService>(); + Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); Services.AddHttpContextAccessor(); + Services.AddHttpClient(); // Identity services Services.TryAddScoped, UserValidator>(); Services.TryAddScoped, PasswordValidator>(); @@ -49,6 +51,32 @@ 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>(); + Services.TryAddScoped, RegistrationService>(); + 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..562ecee --- /dev/null +++ b/RuntimeApps.Authentication/Service/DataProtectionVerificationCodeVerifier.cs @@ -0,0 +1,78 @@ +using System.Globalization; +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, CultureInfo.InvariantCulture), + Convert.ToString(request.UserId, CultureInfo.InvariantCulture), + 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, CultureInfo.InvariantCulture) || + payload.UserId != Convert.ToString(request.UserId, CultureInfo.InvariantCulture) || + 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/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..e70efd8 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/FacebookExternalLoginProvider.cs @@ -1,43 +1,95 @@ -using Microsoft.AspNetCore.Identity; +using System.Globalization; +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; 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; + 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"; - public async Task<(TUser, UserLoginInfo)> ValidateAsync(string token) { + 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 = _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); + 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 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 exception) { + _logger.LogWarning("Facebook returned an invalid response: {Reason}", exception.Message); + return null; + } 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; + } } } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs index 8c5579f..c7ae4b6 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/GoogleExternalLoginProvider.cs @@ -1,37 +1,58 @@ -using Google.Apis.Auth; +using Google.Apis.Auth; using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Logging; 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> _options; private readonly ILogger> _logger; - private readonly IOptions> _option; - public GoogleExternalLoginProvider(ILogger> logger, IOptions> option) { - _logger = logger; - _option = option; + public GoogleExternalLoginProvider( + IOptions> options, + ILogger> logger) { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public string Provider => "GOOGLE"; - 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)) + 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 (user, userLogin); - } 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 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; } } } -} +} \ No newline at end of file diff --git a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs index ac5d315..d47b73a 100644 --- a/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Service/ExternalLoginProviders/MicrosoftExternalLoginProvider.cs @@ -1,41 +1,109 @@ -using System.IdentityModel.Tokens.Jwt; +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; 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; + 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"; - 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( - $"{option.IssuerEndpoint}{option.ConfigurationAddress}", 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(); + using var client = _httpClientFactory.CreateClient(nameof(MicrosoftExternalLoginProvider)); + var documentRetriever = new HttpDocumentRetriever(client) { RequireHttps = true }; + var configuration = await OpenIdConnectConfigurationRetriever.GetAsync( + metadataAddress, documentRetriever, 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 exception) { + _logger.LogWarning( + "Microsoft identity token validation failed. {ExceptionType}: {Reason}", + exception.GetType().FullName, + exception.Message); + return null; + } catch(HttpRequestException exception) { + _logger.LogWarning( + "Microsoft OpenID Connect metadata request failed. Status code: {StatusCode}.", + exception.StatusCode); + return null; + } 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; + } } } -} +} \ 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/RegistrationService.cs b/RuntimeApps.Authentication/Service/RegistrationService.cs new file mode 100644 index 0000000..f32ffcc --- /dev/null +++ b/RuntimeApps.Authentication/Service/RegistrationService.cs @@ -0,0 +1,109 @@ +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 IVerificationWorkflowService _verification; + private readonly IUserAccountService _accountService; + private readonly VerificationOptions _options; + private readonly TimeProvider _timeProvider; + + public RegistrationService( + IUserManager userManager, + IVerificationWorkflowService verification, + IUserAccountService accountService, + IOptions options, + TimeProvider timeProvider = null) { + _userManager = userManager; + _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); + // 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(); + + if(existingUser != null) { + // Reuse the existing pending account without changing any of its data or credentials. + 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); + + // Another request created this pending account first. Reuse it unchanged. + 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..1ff4fff 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,12 +123,32 @@ 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); } 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); @@ -103,15 +158,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; - - var createResult = await _userManager.CreateAsync(user, password); - if(!createResult.Succeeded) - return new Result(ResultCode.BadRequest, createResult.Errors); + 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."))); - return await GenerateTokenAsync(user); + return GenerateTokenAsync(user); } protected virtual Result GetIdentityError(SignInResult signInResult) { 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..17b2aa6 --- /dev/null +++ b/RuntimeApps.Authentication/Service/VerificationWorkflowService.cs @@ -0,0 +1,204 @@ +using System.Globalization; +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 = channel == VerificationChannel.Email + ? _normalizer.NormalizeEmail(destination.Trim()) + : destination.Trim(); + 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); + 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( + 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, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, + 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 || + request.Purpose != expectedPurpose || request.Channel != expectedChannel) + return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + 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); + + 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, + VerificationPurpose expectedPurpose, + VerificationChannel expectedChannel, + 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.Purpose != expectedPurpose || request.Channel != expectedChannel || + 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, CultureInfo.InvariantCulture)); + if(user == null) + return Failure("VerificationRequestUnavailable", "The verification request is unavailable."); + + 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) + return new Result(ResultCode.BadRequest, updateResult.Errors); + + return new Result(user); + } + + 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/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/Model/SmtpVerificationOptions.cs b/Samples/RuntimeApps.Authentication.Sample/Model/SmtpVerificationOptions.cs new file mode 100644 index 0000000..1193ec8 --- /dev/null +++ b/Samples/RuntimeApps.Authentication.Sample/Model/SmtpVerificationOptions.cs @@ -0,0 +1,32 @@ +using System.Net.Mail; +using MailKit.Security; + +namespace RuntimeApps.Authentication.Sample.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() { + 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/Samples/RuntimeApps.Authentication.Sample/Program.cs b/Samples/RuntimeApps.Authentication.Sample/Program.cs index 71c0129..bcf1946 100644 --- a/Samples/RuntimeApps.Authentication.Sample/Program.cs +++ b/Samples/RuntimeApps.Authentication.Sample/Program.cs @@ -3,20 +3,32 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using RuntimeApps.Authentication.Sample.Services; +using RuntimeApps.Authentication.Sample.Model; using Microsoft.IdentityModel.Tokens; using RuntimeApps.Authentication.Controller; using RuntimeApps.Authentication.EF.Extensions; using RuntimeApps.Authentication.Extensions; using RuntimeApps.Authentication.Model; using RuntimeApps.Authentication.Sample; +using RuntimeApps.Authentication.Interface; 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 +76,16 @@ option.Mapper = (data) => MicrosoftExternalLoginOption>.UserIdentityMapper, int>(data); }); +builder.Services.AddVerificationRequestStore(); +builder.Services.AddOptions() + .BindConfiguration(SmtpVerificationOptions.SectionName) + .Validate(options => options.IsValid(), "SMTP verification options are invalid.") + .ValidateOnStart(); +builder.Services.AddScoped, int>, + MailKitVerificationSender, int>>(); + +builder.Services.AddAuthorization(options => options.AddPolicy("Admin", policy => policy.RequireRole("Administrator"))); + builder.Services.AddControllers() .AddJsonOptions(option => { option.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; @@ -80,10 +102,12 @@ var services = scope.ServiceProvider; try { var context = services.GetRequiredService(); - context.Database.Migrate(); + // 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."); } } @@ -100,6 +124,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..523474f 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -99,3 +99,31 @@ 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 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: + +```cs +protected override void OnModelCreating(ModelBuilder modelBuilder) { + base.OnModelCreating(modelBuilder); + modelBuilder.AddVerificationRequestEntity(); +} +``` + +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: + +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 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. diff --git a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj index f04a13c..6cccb51 100644 --- a/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj +++ b/Samples/RuntimeApps.Authentication.Sample/RuntimeApps.Authentication.Sample.csproj @@ -6,7 +6,8 @@ - + + diff --git a/Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs b/Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs new file mode 100644 index 0000000..e6a209c --- /dev/null +++ b/Samples/RuntimeApps.Authentication.Sample/Services/MailKitVerificationSender.cs @@ -0,0 +1,45 @@ +using MailKit.Net.Smtp; +using Microsoft.Extensions.Options; +using MimeKit; +using RuntimeApps.Authentication.Interface; +using RuntimeApps.Authentication.Sample.Model; +using RuntimeApps.Authentication.Model; + +namespace RuntimeApps.Authentication.Sample.Services { + 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/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/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/RegistrationServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs new file mode 100644 index 0000000..abc1880 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs @@ -0,0 +1,84 @@ +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 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, 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_ReusesAccountWithoutUpdatingIt() { + var userManager = 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); + 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, workflow, account); + var result = await service.RegisterAsync(requested, "AttackerSuppliedPassword!"); + + Assert.True(result.Succeeded); + userManager.Verify(manager => manager.CreateAsync(It.IsAny(), It.IsAny()), Times.Never); + 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 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, 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> workflow, + Mock> account) => + new(userManager.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 aa6c095..7aa84a3 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); @@ -51,6 +53,7 @@ public async Task Login_Success() { var user = new IdentityUser() { Id = "userId", UserName = userName, + EmailConfirmed = true }; var token = new Model.Token() { AuthenticationToken = "", @@ -74,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 @@ -113,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); - } - - [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!" - })); - - //Act - var result = await _userAccountService.RegisterAsync(user, password); - - //Assert - result.Succeeded.Should().BeFalse(); - result.Data.Should().BeNull(); - result.Meta.Should().BeNull(); + result.Data.Should().Be(user); + result.Meta.Should().Be(token); } [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" - } - })); + 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(); + result.Code.Should().Be(RuntimeApps.Authentication.Model.ResultCode.Forbidden); + _jwtProviderMock.Verify(provider => provider.GenerateTokenAsync(It.IsAny()), Times.Never()); } [Fact] @@ -205,7 +172,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)) @@ -231,43 +200,95 @@ 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)) - .ReturnsAsync((user, loginInfo)); - _userManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) - .ReturnsAsync(nullUSer); - _userManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) - .ReturnsAsync(user); - _userManagerMock.Setup(u => u.AddLoginAsync(user, loginInfo)) - .ReturnsAsync(IdentityResult.Success); - _jwtProviderMock.Setup(t => t.GenerateTokenAsync(user)) - .ReturnsAsync(appToken); + _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 = existingUser.Email }, + LoginInfo = loginInfo, + Email = existingUser.Email, + EmailVerified = true + }); + _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] + 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); + + 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] @@ -287,7 +308,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)) diff --git a/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs new file mode 100644 index 0000000..3588fac --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/VerificationPrimitivesTest.cs @@ -0,0 +1,66 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; +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 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 }; + + Assert.Throws(() => options.Validate()); + } + } +} \ No newline at end of file