Skip to content

Harden external login lifecycle and account linking - #12

Merged
hifeamin merged 6 commits into
mainfrom
feature/harden-external-login-lifecycle
Nov 25, 2026
Merged

hifeamin merged 6 commits into
mainfrom
feature/harden-external-login-lifecycle

Conversation

@hifeamin

@hifeamin hifeamin commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Context

External login previously resolved accounts inside UserAccountService, matched existing accounts by email only through a trust policy that rejected most providers, left half-created accounts behind on failure, and offered no way for a signed-in user to link or unlink a provider. This PR hardens the whole external login lifecycle: account resolution, email trust, linking, unlinking, and listing. It adds no schema changes or migrations.

Summary of changes

Delivered as five reviewable commits:

  1. Provider validation tests and a Google validation seam (b0dac61). Google, Microsoft and Facebook tests cover invalid signature, issuer/audience mismatch, expiry, missing subject, unverified email, invalid config and cancellation. GoogleExternalLoginProvider gets a protected virtual ValidatePayloadAsync so library rejection can be simulated.
  2. Resolve-only IExternalLoginService<TUser> (f0b7bea). UserAccountService.ExternalLoginAsync delegates to it. Untrusted emails are ignored (not used for lookup, not stored). A trusted email that matches an unconfirmed account first neutralizes it (remove password, revoke refresh tokens), then links the login and confirms the email. A newly created account is deleted if its login cannot be attached. All failures return the same generic ExternalAuthenticationFailed 400.
  3. Per-provider email trust modes (ae353db). New ExternalLoginEmailTrustMode (Verified, Always, Never) set through each provider's EmailTrust option and carried on ExternalLoginProviderResult. Defaults: Google Verified, Facebook Always, Microsoft Never.
  4. Link, unlink and list (7b77f21). GET logins, POST logins/link, POST logins/unlink in MapAccountManagementApi, mapped only when IExternalLoginService<TUser> is registered.
  5. Documentation and sample (2b5cb1d). README (trust modes, account resolution, endpoints, limits, upgrade notes), Basic sample appsettings.json and ReadMe.

Architectural decisions

  • IExternalLoginService<TUser> is new and optional. UserAccountService keeps all existing constructors; when no service is registered it composes one from its existing dependencies. The 16-parameter constructor signature is preserved so existing explicit calls still bind to it, while DI selects the new constructor with optional dependencies.
  • No new public transaction abstraction. Atomicity comes from write ordering (remove password, revoke tokens, add login, confirm email), a compensating delete guarded by Identity's concurrency stamp, and re-check and undo for link and unlink races.
  • Link and unlink stay separate from ISignInManager and user-management responsibilities. ISignInManager is used only for the password re-authentication check.
  • IUserPasswordManager<TUser> gains HasPasswordAsync as a default interface member returning false, so custom managers still compile and fail closed.
  • Unchanged by design: POST password, usernames (PROVIDER_subject fallback, trusted email otherwise), RequireEmailVerificationForExternalLogins.

Security considerations

  1. Unauthenticated user: can sign in with a valid provider token only. An untrusted or unverified email is never used to find or link an account. Matching by email requires a trusted claim.
  2. Pre-hijack: an attacker who registered a victim's address (unconfirmed) cannot keep access once the victim signs in with a trusted provider; the password is removed and sessions are revoked before the login is attached.
  3. Microsoft: email claims are mutable and the common endpoint is multi-tenant, so Microsoft is Never by default. The README warns before enabling Always.
  4. Account enumeration: failures are generic and identical whether or not an account exists; untrusted email is never looked up.
  5. Authenticated but unauthorized: linking requires fresh proof of control (current password, counted toward lockout, or a fresh token from a provider already linked to the same account). The provider email does not need to match and is never copied onto the account. An identity belonging to another account returns 409. One identity per provider per account.
  6. Lockout prevention: unlinking is refused (409) when it would remove the last usable authentication method; it re-checks after removal and restores the login if a concurrent request raced it, and revokes refresh tokens.
  7. Information leakage: error bodies use the public error mapping only. No internal codes, Identity errors or subject keys; the list endpoint returns provider names only.
  8. Concurrency and defaults: duplicate links are re-checked and undone; custom password managers fail closed.

Tests

New or updated: ExternalLoginProviderValidationTest, ExternalLoginServiceTest (resolve), ExternalLoginLinkingTest (link, unlink, list, races, fail-closed), AccountExternalLoginEndpointTest (mapping, auth metadata, status codes, sanitized bodies), ExternalLoginEmailTrustPolicyTest, UserAccountServiceTest. Four UserAccountServiceTest cases changed because behavior changed (untrusted email now creates an account without it; a failed link after create now deletes the created user).

Build and test status (accurate):

  • Executed and passed locally by the maintainer after each of steps 1, 2 and 3.
  • Steps 4 and 5: the code and tests were written in an environment without the .NET SDK and were only syntax-checked there. A local build and test run of the final branch head is still to be confirmed before merge.
  • Not covered: an end-to-end HTTP test against the sample app.

Breaking changes and migration notes

No schema changes or migrations, and no changes to existing constructors or POST password. Behavior changes to review:

  • Facebook emails are now trusted by default. Set EmailTrust = ExternalLoginEmailTrustMode.Never to keep the old behavior.
  • Microsoft emails remain untrusted; opt in explicitly.
  • An untrusted email no longer rejects the login: a new account is created without that email. Keep RequireEmailVerificationForExternalLogins = true where a verified email is required.
  • A trusted login matching an unconfirmed account now removes that account's password.
  • Custom IUserPasswordManager<TUser> implementations should implement HasPasswordAsync; until then unlinking is refused and password re-authentication is rejected.

Known limitations

  • Identity has no cross-store transaction. A process crash between steps cannot be repaired automatically (for example after the password of an unconfirmed account is removed and before the login is linked); retrying the same trusted login completes the link.
  • Unlink does not require re-authentication (only linking does), as agreed.
  • The password re-authentication check relies on Identity lockout; no additional rate limiting.

https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR


Generated by Claude Code

Add a protected virtual ValidatePayloadAsync to GoogleExternalLoginProvider so
the provider's own handling can be tested without reaching Google's certificate
endpoint. The default implementation is unchanged: it calls
GoogleJsonWebSignature.ValidateAsync with the configured client ID as the only
accepted audience. The provider now also returns null if validation yields no
payload.

Add ExternalLoginProviderValidationTest covering invalid signature, issuer and
audience mismatch, expiry, unverified email and missing subject:
- Microsoft: real JWT validation against stubbed metadata and signing keys.
- Facebook: stubbed Graph API responses (invalid token, app mismatch, expiry,
  missing and mismatched subject, invalid configured app id).
- Google: simulated library rejection plus subject, unverified email, missing
  configuration and cancellation handling.

Not built or run: the authoring environment has no .NET SDK.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR
…unconfirmed accounts

Move external login account resolution out of UserAccountService into a
resolve-only IExternalLoginService. Untrusted provider emails are ignored
(not used for lookup, not stored). A trusted email on an unconfirmed account
removes its password and revokes sessions before the login is attached. A
newly created account is deleted if its login cannot be attached.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR
Introduce ExternalLoginEmailTrustMode (Verified, Always, Never) configured per
provider through EmailTrust and carried on ExternalLoginProviderResult. The
default policy applies it. Defaults: Google Verified, Facebook Always,
Microsoft Never (Microsoft email claims are mutable and not proof of mailbox
ownership). Custom providers and policies keep the previous Verified behavior.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR
Extend IExternalLoginService with LinkAsync, UnlinkAsync and ListLoginsAsync and
expose them as GET logins, POST logins/link and POST logins/unlink in the
account management API (mapped only when the service is registered).

Linking requires re-authentication with the current password (counted toward
lockout) or a fresh token of an already linked identity, does not require the
provider email to match, allows one identity per provider per account and
rejects identities that belong to another account. Concurrent links are
re-checked and undone. Unlinking is refused when it would remove the last
usable authentication method, re-checks and restores the login if a concurrent
request raced it, and revokes refresh tokens. IUserPasswordManager gains a
HasPasswordAsync default interface member that fails closed for custom managers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR
Describe per-provider EmailTrust modes and defaults (with the Microsoft
warning), how an external login resolves to an account including neutralizing
unconfirmed accounts, the link/unlink/list endpoints and step-up
re-authentication, the non-transactional crash-window limitation and upgrade
notes. Update the Basic sample settings and ReadMe, and refresh README text that
described the previous behavior.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017CaSpXU2uU4P75CdgjJ6NR
@hifeamin hifeamin changed the title Feature/harden external login lifecycle Harden external login lifecycle and account linking Nov 25, 2026
@hifeamin
hifeamin merged commit 0fb1206 into main Nov 25, 2026
3 checks passed
@hifeamin
hifeamin deleted the feature/harden-external-login-lifecycle branch November 25, 2026 18:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants