App passwords
Let calendar apps and calendar subscriptions authenticate without a browser sign-in — per-user, named, revocable app passwords and feed tokens, stored as a hash, checked by an ASP.NET Core scheme whose every step the application can replace.
Calendar apps (iOS, macOS, Thunderbird, DAVx5) cannot run an OIDC or cookie sign-in: they send a user name and a password over HTTP Basic on every request. Outlook and Google Calendar subscribe to a URL and send nothing at all. An app password is the credential for both: a person creates one in the application ("iPhone"), types it into the calendar app once, and revokes it when the phone is gone. A feed token is an app password bound to one published calendar and carried in the path of its feed URL (ADR-0111).
| Package | Role |
|---|---|
Elarion.AppPasswords | IAppPasswords (create, list, revoke, verify), AppPasswordScope, AppPasswordOptions, the IAppPasswordStore seam and an in-memory store for tests. NativeAOT-safe. |
Elarion.AppPasswords.EntityFrameworkCore | The elarion_app_passwords table on the application's DbContext ([GenerateElarionAppPasswords]). |
Elarion.AppPasswords.AspNetCore | The authentication scheme: HTTP Basic and feed tokens, its events, and AddElarionIdentityAppPasswordPrincipals<TUser>(). |
Management is the application's: it writes the own-account handlers that create, list and revoke, and the page that shows a new secret once. Elarion stores, checks and signs in.
Wiring
// The DbContext maps the table:
[GenerateDbSets]
[GenerateElarionAppPasswords]
public partial class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options) {
protected override void OnModelCreating(ModelBuilder modelBuilder) => ConfigureEntities(modelBuilder);
}
builder.Services.AddElarionAppPasswordsEntityFrameworkCore<AppDbContext>(
builder.Configuration.GetSection(AppPasswordOptions.SectionName));
builder.Services.AddElarionIdentityAppPasswordPrincipals<AppUser>(); // or set Events.OnCreatePrincipal
builder.Services.AddAuthentication() // the browser's scheme stays the default
.AddElarionAppPasswordAuthentication(o => o.Realm = "Example");The scheme is not the default scheme. Name it on the routes calendar apps use, and only there:
app.MapGroup("/dav").RequireAuthorization(new AuthorizeAttribute {
AuthenticationSchemes = AppPasswordAuthenticationDefaults.AuthenticationScheme,
});An app password then authenticates nothing else (not /rpc, not [HttpEndpoint] routes), and the browser's cookie or
proxy token authenticates nothing under /dav. The DAV host of the CalDAV packages applies this to its route group
itself.
No calendar feeds? Turn the feed-token reader off. The scheme reads a feed token from {/dav}/feeds/{token}.ics by
default, for CalDAV's ICS feeds. Only an app password of scope calendar-feed verifies there, so an application that
issues none is not exposed, but one that serves no feeds (CardDAV only, or no DAV at all) should say so:
builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => o.FeedTokenReader = null);Creating, listing and revoking
[Handler] // an own-account handler: it acts only on the signed-in user's passwords
public sealed class CreateAppPassword(IAppPasswords appPasswords, ICurrentUser user)
: IHandler<CreateAppPassword.Command, Result<CreateAppPassword.Created>> {
public sealed record Command([property: StringLength(AppPasswordOptions.MaxNameLength, MinimumLength = 1)] string Name);
public sealed record Created(Guid Id, string Secret);
public async ValueTask<Result<Created>> HandleAsync(Command command, CancellationToken ct) {
var issued = await appPasswords.CreateAsync(user.UserId, command.Name, AppPasswordScope.Dav, ct);
if (!issued.IsSuccess) return issued.Error; // app_password.limit_reached
return new Created(issued.Value.Password.Id, issued.Value.Secret); // the only time the secret is readable
}
}CreateAsync(userId, name, scope)returnsResult<AppPasswordIssued>: the listing data and the secret. A user who already holdsMaxPerUserapp passwords gets a conflict with the codeAppPasswordErrorCodes.LimitReached(app_password.limit_reached) whoseDatais anAppPasswordLimitReachedDatawithMaxPerUser, so the message in the user's language needs no options: branch on the code, word the payload. A handler that returns the error over JSON-RPC declares[ProducesError(AppPasswordErrorCodes.LimitReached, ErrorKind.Conflict, typeof(AppPasswordLimitReachedData))], which puts the payload into its error contract and serializer context. The password is stored when the call returns, independent of the caller's transaction. A user id is at most 256 characters (AppPasswordOptions.MaxUserIdLength, the stored column's length); a longer one throws.ListAsync(userId)returnsAppPasswordInfos (id, name, scope, creation, last use), never a secret, oldest first (by creation). A page that shows the newest first reverses the list; it holds at mostMaxPerUserrows.RevokeAsync(userId, id)deletes the row; the next request with it is refused. Another user's id or an unknown one is a not-found withAppPasswordErrorCodes.NotFound(app_password.not_found).VerifyAsync(secret, scope)is what the scheme calls; it records the last use at most once perLastUseInterval.
Scopes and feed tokens
AppPasswordScope.Dav (dav) is a calendar app's account. AppPasswordScope.CalendarFeed(source, key)
(calendar-feed:{source}.{key}, each part 1 to 64 ASCII letters, digits, - or _) binds a feed token to one
published calendar. The scheme accepts a dav password only over HTTP Basic and a feed token only in a feed URL,
{prefix}/feeds/{token}.ics (AppPasswordFeedPaths), and answers a refused feed token with 404 rather than a
challenge, because the URL itself is the credential. Which calendar a feed token may read is checked by the DAV host
against the token's scope; see CalDAV feeds, where
AppPasswordScope.CalendarFeed(CalDavAddress) and CalDavLinks.FeedUrl create the scope and the URL.
The secret
A secret is SecretPrefix (default elap_) and 256 bits from RandomNumberGenerator, base64url without padding. Only
its hash is stored: SHA-256 over the UTF-8 bytes of the whole secret as the client sends it, prefix included, as
standard Base64 with padding (AppPasswordSecrets.ComputeHash), under a unique index. A machine-generated secret of this
entropy needs no slow hash and no lockout; a rate limiter on the route can still guard it.
The scheme and its events
For HTTP Basic the header is split at the first colon (the user name cannot contain one, the password can). Then four
events run, each a Func<TContext, ValueTask<…>> on AppPasswordAuthenticationEvents. Every context carries
HttpContext, Services (the request scope), Scheme, CredentialKind, UserName (Basic only) and
CancellationToken.
| Event | Default | Returning |
|---|---|---|
OnVerifyCredential | IAppPasswords.VerifyAsync: scope dav for Basic, any calendar-feed scope for a feed token | the AppPasswordMatch (id, user id, scope), or null to refuse |
OnValidateUserName | not checked (the secret identifies the credential); not run for feeds | false to refuse |
OnCreatePrincipal | none: the registered IAppPasswordPrincipalFactory, else the host fails to start | the ClaimsPrincipal, or null to refuse |
OnAuthenticated | nothing | — (audit, metrics) |
The principal is created on every request, so a deleted or deactivated account stops syncing at once.
AddElarionIdentityAppPasswordPrincipals<TUser>() does it through ASP.NET Core Identity: UserManager<TUser>.FindByIdAsync,
a refusal when the user is missing or locked out, when a registered SignInManager<TUser> would not sign the user in
(CanSignInAsync: a required confirmed e-mail, phone number or account through IUserConfirmation<TUser>, or the
application's override), or when the application's own rule says no, and IUserClaimsPrincipalFactory<TUser>:
builder.Services.AddElarionIdentityAppPasswordPrincipals<AppUser>(
(user, ctx) => ValueTask.FromResult(user.IsActive && (user.EndsAt is null || user.EndsAt > DateTimeOffset.UtcNow)));An application on proxy identity or OIDC sets the delegate over its own user service:
builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => {
o.Events.OnCreatePrincipal = async ctx => {
var accounts = ctx.Services.GetRequiredService<AccountService>();
return await accounts.CreatePrincipalAsync(ctx.Match.UserId, ctx.CancellationToken); // null refuses
};
});The scheme adds the claims elarion:app_password_id and elarion:app_password_scope (AppPasswordClaimTypes), so
ICurrentUser.HasClaim and the DAV host can tell an app-password request apart. Whatever OnVerifyCredential returns,
a match of the wrong kind is refused: a feed token never works as a Basic password.
A missing or refused credential is answered 401 with WWW-Authenticate: Basic realm="{Realm}", charset="UTF-8"
(iOS sends unauthenticated requests during discovery and gives up on a 403); an authenticated request the policy
refuses is answered 403 without a challenge.
Instead of setting delegates, an application can subclass AppPasswordAuthenticationEvents, override VerifyCredential,
ValidateUserName, CreatePrincipal or Authenticated, register the subclass and set o.EventsType, as with
JwtBearerEvents. The scheme is hand-written over AuthenticationHandler<T> with no reflection and publishes with
NativeAOT without warnings.
Adopting existing app passwords
An application that already issues its own Basic credentials to DAV clients moves to this scheme without asking anyone to create a new password and type it into every device. It has two paths.
1. Keep its own store. It registers no Elarion.AppPasswords.EntityFrameworkCore (and need not call
AddElarionAppPasswords), and points the events at what it has: OnVerifyCredential at its existing check,
OnValidateUserName at its user-name rule, and OnCreatePrincipal at its principal construction, with any account
checks of its own. IAppPasswords and IAppPasswordStore are then never resolved. Only the handler class changes; the
table, the management handlers and the page stay. No data migration.
builder.Services.AddAuthentication().AddElarionAppPasswordAuthentication(o => {
o.Events.OnVerifyCredential = async ctx => {
var tokens = ctx.Services.GetRequiredService<LegacyDeviceTokens>();
var token = await tokens.FindAsync(ctx.Secret, ctx.CancellationToken);
return token is null ? null
: new AppPasswordMatch { Id = token.Id.ToString(), UserId = token.UserId, Scope = AppPasswordScope.Dav };
};
o.Events.OnValidateUserName = async ctx => { // "the e-mail of the owning account"
var accounts = ctx.Services.GetRequiredService<AccountService>();
var email = await accounts.GetEmailAsync(ctx.Match.UserId, ctx.CancellationToken);
return string.Equals(email, ctx.UserName, StringComparison.OrdinalIgnoreCase);
};
o.Events.OnCreatePrincipal = async ctx => {
var accounts = ctx.Services.GetRequiredService<AccountService>();
return await accounts.CreateActivePrincipalAsync(ctx.Match.UserId, ctx.CancellationToken);
};
});2. Move the rows into Elarion's store. This works without the secrets when the old store kept SHA-256 over the UTF-8
secret as standard Base64 — the encoding above. A migration step copies each row into elarion_app_passwords with
scope = 'dav', the user id as a string, the name, the creation and last-use times, and the hash unchanged; then the
application drops its own table and handlers and uses IAppPasswords. The hash covers the whole secret as typed, so
secrets with the old prefix keep verifying; SecretPrefix affects only new ones. A store that kept SHA-256 as hex
converts in SQL (encode(decode(hash_hex, 'hex'), 'base64') on PostgreSQL); one with another hash function stays on
path 1, or its users re-create their passwords.
INSERT INTO elarion_app_passwords (id, user_id, name, scope, hash, created_at, last_used_at)
SELECT id, user_id::text, name, 'dav', token_hash, created_at, last_used_at FROM legacy_app_passwords;The cap per user (10), the last-use interval (15 minutes) and revoking by deleting match what such stores usually do, so
neither path changes what a user notices. What does not carry over is a user-name rule: path 2 still sets
OnValidateUserName when the application wants one.
Options
| Option | Default | Meaning |
|---|---|---|
AppPasswords:SecretPrefix | elap_ | The start of every new secret, so secret scanners recognise a leaked one. |
AppPasswords:MaxPerUser | 10 | How many app passwords one user may hold. |
AppPasswords:LastUseInterval | 00:15:00 | The shortest time between two writes of the last use; a polling client causes no write within it. |
AppPasswordAuthenticationOptions.Realm | DAV | The realm of the Basic challenge. |
AppPasswordAuthenticationOptions.FeedTokenReader | {/dav}/feeds/{token}.ics | Reads a feed token from a request; AppPasswordFeedPaths.CreateReader(prefix) for another prefix, null for no feeds. |
See configuration and the decision.
Proxy identity
Authenticate an app that sits behind an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy, an OIDC gateway) — validate the forwarded token, refuse to start unauthenticated, and develop locally with a stand-in identity.
Caching
Declarative handler result caching with [Cacheable] and tag-based invalidation with [CacheInvalidate], backed by HybridCache.