Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
73 changes: 73 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<TKey>` 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<TUser, TKey>`.

### Configure the workflow

Call `AddVerificationServices` when configuring RuntimeApps Authentication. Register a persistent implementation of `IVerificationRequestStore<TKey>` and a delivery implementation of `IVerificationSender<TUser, TKey>`. The EF integration provides a relational store:

```cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddRuntimeAppsAuthentication<IdentityUser<int>, IdentityRole<int>, 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<ApplicationDbContext, IdentityUser<int>, IdentityRole<int>, int>();

// In ApplicationDbContext.OnModelCreating:
modelBuilder.AddVerificationRequestEntity<int>();

builder.Services.AddVerificationRequestStore<ApplicationDbContext, int>();
```

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<TUser, TKey>` 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<SmtpVerificationOptions>(
configuration.GetSection(SmtpVerificationOptions.SectionName));
builder.Services.AddScoped<IVerificationSender<IdentityUser<int>, int>,
MailKitVerificationSender<IdentityUser<int>, 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<TUser, TUserDto, TKey>()` 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<TUser>`.

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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.EntityFrameworkCore;
using RuntimeApps.Authentication.EF.Model;

namespace RuntimeApps.Authentication.EF.Extensions {
public static class VerificationRequestModelBuilderExtensions {
/// <summary>Adds the verification request and delivery-rate-limit entities to the consumer DbContext.</summary>
public static ModelBuilder AddVerificationRequestEntity<TKey>(this ModelBuilder modelBuilder)
where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(modelBuilder);
modelBuilder.ApplyConfiguration(new VerificationRequestConfiguration<TKey>());
modelBuilder.ApplyConfiguration(new VerificationSendConfiguration());
return modelBuilder;
}
}
}
Original file line number Diff line number Diff line change
@@ -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 {
/// <summary>Registers the EF Core verification-request store.</summary>
public static IServiceCollection AddVerificationRequestStore<TDbContext, TKey>(this IServiceCollection services)
where TDbContext : DbContext
where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(services);
services.TryAddScoped<IVerificationRequestStore<TKey>, EfVerificationRequestStore<TDbContext, TKey>>();
return services;
}
}
}
Original file line number Diff line number Diff line change
@@ -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<TKey> : IEntityTypeConfiguration<VerificationRequest<TKey>>
where TKey : IEquatable<TKey> {
public void Configure(EntityTypeBuilder<VerificationRequest<TKey>> 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<string>().HasMaxLength(32).IsRequired();
builder.Property(request => request.Channel).HasConversion<string>().HasMaxLength(32).IsRequired();
builder.Property(request => request.Status).HasConversion<string>().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 });
}
}
}
Original file line number Diff line number Diff line change
@@ -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<VerificationSend> {
public void Configure(EntityTypeBuilder<VerificationSend> 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<string>().HasMaxLength(32).IsRequired();
builder.Property(send => send.Channel).HasConversion<string>().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
});
}
}
}
Loading
Loading