Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
41 changes: 41 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,47 @@ Revoking refresh tokens does not immediately invalidate access JWTs already issu
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.


## EF Core integration

### Identity stores

`AddEfStores<TDbContext, TUser, TRole, TKey>()` registers the ASP.NET Core Identity EF stores. `TDbContext` can be any `DbContext`: it does not have to derive from `IdentityDbContext`, but its model must contain the default Identity entities for your user, role and key types (`TUser`, `TRole`, `IdentityUserClaim<TKey>`, `IdentityUserRole<TKey>`, `IdentityUserLogin<TKey>`, `IdentityUserToken<TKey>`, `IdentityRoleClaim<TKey>`). The application fails at startup with a message listing any missing entity. Custom claim, login, token or user-role entity types (the eight-argument `IdentityDbContext`) are not supported by the built-in stores; implement your own stores for that case (see the Custom Store sample).

### Model configuration

Add the entities of the features you use in `OnModelCreating`. Each method is independent; call only the ones you need:

```cs
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.AddRefreshTokenEntity<int>();
modelBuilder.AddVerificationRequestEntity<int>();
}
```

Table names or schemas can be changed with ordinary EF Core calls afterwards, for example `modelBuilder.Entity<RefreshToken<int>>().ToTable("RefreshTokens", "auth")`.

### Supported providers and limitations

- Refresh-token and verification stores require a **relational** provider. Rotation, resend and send limits use transactions and conditional updates; EF InMemory is not supported and throws `NotSupportedException`.
- The repository's tests run against SQLite. SQL Server and PostgreSQL are expected to work but are not covered by automated tests in this repository.
- Transactions run inside the DbContext execution strategy, so `EnableRetryOnFailure` (and equivalent provider settings) is supported.
- Verification create and resend use `Serializable` transactions. Under heavy concurrency, providers can abort a transaction (deadlock or serialization failure). Configure a retrying execution strategy if this matters for your workload.
- `VerificationRequest.CodeVerifier` uses an empty string as an "initial" marker. Providers that treat empty strings as `NULL` (for example Oracle) are not supported.
- Dates are stored with `DateTimeOffsetToBinaryConverter` (a `bigint`, millisecond precision) so that expiry comparisons work on every relational provider, including SQLite.
- `UserId` columns do not have a foreign key to your users table. Rows for deleted users remain until they expire, and the refresh endpoint rejects (and revokes) a refreshed session whose user no longer exists. To add a foreign key, configure it in your own `OnModelCreating` (for example `modelBuilder.Entity<RefreshToken<int>>().HasOne<IdentityUser<int>>().WithMany().HasForeignKey(token => token.UserId).OnDelete(DeleteBehavior.Cascade)`) and remove orphaned rows before applying the migration. Purging expired rows is the application's responsibility for now.

### Migration impact

Adding entities requires a migration for the tables you enable. When upgrading an existing database that already contains the verification tables, add two nullable columns to `AuthenticationVerificationSends`:

| Column | Type |
| --- | --- |
| `CustomPurpose` | `nvarchar(128)` / provider equivalent, nullable |
| `CustomChannel` | `nvarchar(128)` / provider equivalent, nullable |

`dotnet ef migrations add <Name>` generates this change. Existing rows keep `NULL` values, which match requests without a custom purpose or channel. Send limits and "supersede pending request" behavior are now scoped per custom purpose and custom channel, so two different custom purposes for the same destination no longer affect each other. No other column, index or table name changes were made.

## 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>`.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
using RuntimeApps.Authentication.DependencyInjection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using RuntimeApps.Authentication.EF.Identity;

namespace RuntimeApps.Authentication.EF.DependencyInjection {
public static class RuntimeAppsAuthenticationBuilderExtension {
/// <summary>
/// Registers the ASP.NET Core Identity EF stores. The DbContext does not have to derive from
/// <see cref="IdentityDbContext{TUser, TRole, TKey}"/>, but its model must contain the default
/// Identity entities for <typeparamref name="TUser"/>, <typeparamref name="TRole"/> and
/// <typeparamref name="TKey"/>. This is verified at application start.
/// </summary>
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddEfStores<TDbContext, TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder)
where TDbContext : IdentityDbContext<TUser, TRole, TKey>
where TDbContext : DbContext
where TUser : IdentityUser<TKey>, new()
where TRole : IdentityRole<TKey>
where TKey : IEquatable<TKey> {
builder.AddStores<UserStore<TUser, TRole, TDbContext, TKey>,
ArgumentNullException.ThrowIfNull(builder);
builder.AddStores<UserStore<TUser, TRole, TDbContext, TKey>,
RoleStore<TRole, TDbContext, TKey>>();
builder.Services.TryAddEnumerable(
ServiceDescriptor.Singleton<IHostedService, EfIdentityModelStartupValidator<TDbContext, TUser, TRole, TKey>>());
return builder;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,28 +62,54 @@ public async Task<bool> TryRotateAsync(
if(!_dbContext.Database.IsRelational())
throw new NotSupportedException("Atomic refresh-token rotation requires a relational EF Core provider.");

await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
// Generated keys (Guid/string) are assigned once so every retry attempt reuses the same value.
// Database-generated integer keys stay at their default and are reset before each attempt.
PrepareGeneratedId(replacement);
await _dbContext.Set<RefreshToken<TKey>>().AddAsync(replacement, cancellationToken);
await _dbContext.SaveChangesAsync(cancellationToken);
var originalId = replacement.Id;

var affected = await _dbContext.Set<RefreshToken<TKey>>()
.Where(token => token.Id.Equals(tokenId) &&
token.TokenHash == expectedTokenHash &&
token.RevokedAt == null &&
token.ExpiresAt > now)
.ExecuteUpdateAsync(setters => setters
.SetProperty(token => token.RevokedAt, now)
.SetProperty(token => token.ReplacedByTokenId, replacement.Id)
.SetProperty(token => token.HasReplacement, true), cancellationToken);

if(affected != 1) {
await transaction.RollbackAsync(cancellationToken);
return false;
}
// User-initiated transactions must run inside the execution strategy so providers configured
// with retry-on-failure (for example EnableRetryOnFailure) retry the whole unit.
var strategy = _dbContext.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async () => {
ResetReplacement(replacement, originalId);
var committed = false;
try {
await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
await _dbContext.Set<RefreshToken<TKey>>().AddAsync(replacement, cancellationToken);
await _dbContext.SaveChangesAsync(cancellationToken);

var affected = await _dbContext.Set<RefreshToken<TKey>>()
.Where(token => token.Id.Equals(tokenId) &&
token.TokenHash == expectedTokenHash &&
token.RevokedAt == null &&
token.ExpiresAt > now)
.ExecuteUpdateAsync(setters => setters
.SetProperty(token => token.RevokedAt, now)
.SetProperty(token => token.ReplacedByTokenId, replacement.Id)
.SetProperty(token => token.HasReplacement, true), cancellationToken);

if(affected != 1) {
await transaction.RollbackAsync(cancellationToken);
return false;
}

await transaction.CommitAsync(cancellationToken);
committed = true;
return true;
} finally {
// A rolled-back or failed insert must not stay tracked as a persisted row in the
// shared scoped context (it is shared with the Identity stores).
if(!committed)
ResetReplacement(replacement, originalId);
}
});
}

await transaction.CommitAsync(cancellationToken);
return true;
private void ResetReplacement(RefreshToken<TKey> replacement, TKey originalId) {
var entry = _dbContext.Entry(replacement);
if(entry.State != EntityState.Detached)
entry.State = EntityState.Detached;
replacement.Id = originalId;
}

public async Task RevokeFamilyAsync(Guid familyId, DateTimeOffset revokedAt, CancellationToken cancellationToken = default) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ public void Configure(EntityTypeBuilder<VerificationSend> builder) {
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();
// Nullable and intentionally not part of the index: the index prefix still narrows the
// lookup, and wider keys would exceed index size limits on some providers.
builder.Property(send => send.CustomPurpose).HasMaxLength(128);
builder.Property(send => send.CustomChannel).HasMaxLength(128);
builder.Property(send => send.SentAt).HasConversion(new DateTimeOffsetToBinaryConverter());
builder.HasIndex(send => send.SentAt);
builder.HasIndex(send => new {
Expand Down
Loading
Loading