feat(auth): add per-account lockout and TOTP 2FA with recovery codes
Adds three layers of account-security hardening, all gated behind the existing SignInWithAppSessionAsync-equivalent (now AppSessionIssuer) so every sign-in path -- local, Google, Microsoft -- goes through the same lockout/2FA checks: - Per-account lockout: Identity's built-in lockout store (columns already provisioned, previously unused) is now wired up in AuthController.Login via IsLockedOutAsync/AccessFailedAsync/ResetAccessFailedCountAsync, 5 failed attempts / 15 min, same generic 401 as wrong-password to avoid enumeration. - RFC 6238 TOTP 2FA (Otp.NET) with QR-code setup (QRCoder, fully local/ offline) on a new TwoFactorController: setup requires password re-confirmation and returns a pending (unconfirmed) secret + QR; the secret is only persisted as active once verify-setup checks a real code. Secrets are encrypted at rest via the same IDataProtector pattern already used for Gmail/Microsoft OAuth refresh tokens. - Login/OAuth exchange now checks TwoFactorEnabled before issuing a real session. If enabled, it hands back an opaque, server-side (IMemoryCache) pending token via a new ITwoFactorPendingTokenService -- deliberately NOT a JWT, so it can never be presented as a bearer token to bypass the 2FA check on any other endpoint. Only POST /api/auth/2fa/challenge can redeem it, rate-limited at 5/5min (tighter than password login, since a 6-digit space is far more brute-forceable). - One-time recovery codes (10 per enable/regenerate, SHA-256-hashed at rest, shown once in plaintext) accepted in the same challenge endpoint as an alternative to a TOTP code. Schema: AspNetUsers gains TotpSecretEncrypted / TotpPendingSecretEncrypted / TotpEnabledAtUtc, plus a new TwoFactorRecoveryCodes table, added to both the SQLite and MySQL dialect blocks in the startup schema reconciler. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,8 +21,9 @@ public sealed class AuthController : ControllerBase
|
||||
private readonly IGoogleTokenValidator _googleTokens;
|
||||
private readonly IMicrosoftTokenValidator _microsoftTokens;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
private readonly ITwoFactorPendingTokenService _twoFactorPending;
|
||||
|
||||
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger)
|
||||
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger, ITwoFactorPendingTokenService twoFactorPending)
|
||||
{
|
||||
_cfg = cfg;
|
||||
_users = users;
|
||||
@@ -31,6 +32,7 @@ public sealed class AuthController : ControllerBase
|
||||
_googleTokens = googleTokens;
|
||||
_microsoftTokens = microsoftTokens;
|
||||
_logger = logger;
|
||||
_twoFactorPending = twoFactorPending;
|
||||
}
|
||||
|
||||
[HttpGet("config")]
|
||||
@@ -55,6 +57,7 @@ public sealed class AuthController : ControllerBase
|
||||
public sealed record LoginRequest(string Email, string Password, bool RememberMe = true);
|
||||
public sealed record RegisterRequest(string Email, string Password, bool RememberMe = true);
|
||||
public sealed record AuthSessionResult(bool Authenticated, string Provider);
|
||||
public sealed record TwoFactorRequiredResult(bool RequiresTwoFactor, string PendingToken);
|
||||
public sealed record GoogleLinkDto(bool Linked, string? Email, DateTimeOffset? LinkedAt);
|
||||
public sealed record MicrosoftLinkDto(bool Linked, string? Email, DateTimeOffset? LinkedAt);
|
||||
public sealed record MeResult(
|
||||
@@ -83,7 +86,7 @@ public sealed class AuthController : ControllerBase
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("auth-login")]
|
||||
public async Task<ActionResult<AuthSessionResult>> Login([FromBody] LoginRequest request, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var email = (request.Email ?? string.Empty).Trim();
|
||||
var password = request.Password ?? string.Empty;
|
||||
@@ -94,17 +97,26 @@ public sealed class AuthController : ControllerBase
|
||||
var user = await _users.FindByEmailAsync(email) ?? await _users.FindByNameAsync(email);
|
||||
if (user is null) return Unauthorized();
|
||||
|
||||
var ok = await _users.CheckPasswordAsync(user, password);
|
||||
if (!ok) return Unauthorized();
|
||||
// Same generic 401 whether the account doesn't exist, is locked out, or the password is
|
||||
// wrong -- don't let a client distinguish "locked" from "wrong password" (enumeration).
|
||||
if (await _users.IsLockedOutAsync(user)) return Unauthorized();
|
||||
|
||||
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
|
||||
return Ok(new AuthSessionResult(true, "local"));
|
||||
var ok = await _users.CheckPasswordAsync(user, password);
|
||||
if (!ok)
|
||||
{
|
||||
await _users.AccessFailedAsync(user);
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
await _users.ResetAccessFailedCountAsync(user);
|
||||
|
||||
return await CompleteSignInAsync(user, request.RememberMe, "local", cancellationToken);
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("auth-login")]
|
||||
public async Task<ActionResult<AuthSessionResult>> Register([FromBody] RegisterRequest request, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var allow = _cfg.GetValue("Auth:AllowRegistration", false);
|
||||
if (!allow) return StatusCode(403, "Registration is disabled.");
|
||||
@@ -125,14 +137,13 @@ public sealed class AuthController : ControllerBase
|
||||
return BadRequest(string.Join("; ", res.Errors.Select(e => e.Description)));
|
||||
}
|
||||
|
||||
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
|
||||
return Ok(new AuthSessionResult(true, "local"));
|
||||
return await CompleteSignInAsync(user, request.RememberMe, "local", cancellationToken);
|
||||
}
|
||||
|
||||
[HttpPost("google/exchange")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("auth-login")]
|
||||
public async Task<ActionResult<AuthSessionResult>> ExchangeGoogleToken([FromBody] GoogleTokenRequest request, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> ExchangeGoogleToken([FromBody] GoogleTokenRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = (request.Token ?? string.Empty).Trim();
|
||||
if (token.Length == 0) return BadRequest("Google token is required.");
|
||||
@@ -193,14 +204,13 @@ public sealed class AuthController : ControllerBase
|
||||
await _users.UpdateAsync(user);
|
||||
}
|
||||
|
||||
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
|
||||
return Ok(new AuthSessionResult(true, "google"));
|
||||
return await CompleteSignInAsync(user, request.RememberMe, "google", cancellationToken);
|
||||
}
|
||||
|
||||
[HttpPost("microsoft/exchange")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("auth-login")]
|
||||
public async Task<ActionResult<AuthSessionResult>> ExchangeMicrosoftToken([FromBody] MicrosoftTokenRequest request, CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> ExchangeMicrosoftToken([FromBody] MicrosoftTokenRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = (request.Token ?? string.Empty).Trim();
|
||||
if (token.Length == 0) return BadRequest("Microsoft token is required.");
|
||||
@@ -261,8 +271,7 @@ public sealed class AuthController : ControllerBase
|
||||
await _users.UpdateAsync(user);
|
||||
}
|
||||
|
||||
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
|
||||
return Ok(new AuthSessionResult(true, "microsoft"));
|
||||
return await CompleteSignInAsync(user, request.RememberMe, "microsoft", cancellationToken);
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
@@ -655,12 +664,21 @@ public sealed class AuthController : ControllerBase
|
||||
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: detail);
|
||||
}
|
||||
|
||||
private async Task SignInWithAppSessionAsync(ApplicationUser user, bool rememberMe, CancellationToken cancellationToken)
|
||||
// Shared by local/Google/Microsoft sign-in. If the account has TOTP 2FA enabled, this does
|
||||
// NOT issue the real session -- it hands back a short-lived opaque pending token that only
|
||||
// POST /api/auth/2fa/challenge can redeem, after the caller proves they hold the TOTP device
|
||||
// (or a recovery code). This is the gate that makes 2FA actually mandatory rather than
|
||||
// decorative: skipping straight to AppSessionIssuer here would defeat the whole feature.
|
||||
private async Task<IActionResult> CompleteSignInAsync(ApplicationUser user, bool rememberMe, string provider, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = await _tokens.CreateAccessTokenAsync(user, cancellationToken);
|
||||
var secure = Request.IsHttps || string.Equals(Request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
|
||||
Response.Cookies.Append(AuthSessionOptions.SessionCookieName, token, AuthSessionOptions.BuildSessionCookie(rememberMe, secure));
|
||||
EnsureCsrfCookie(rememberMe, secure);
|
||||
if (user.TwoFactorEnabled)
|
||||
{
|
||||
var pendingToken = _twoFactorPending.IssuePendingToken(user.Id, rememberMe);
|
||||
return Ok(new TwoFactorRequiredResult(true, pendingToken));
|
||||
}
|
||||
|
||||
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, user, rememberMe, cancellationToken);
|
||||
return Ok(new AuthSessionResult(true, provider));
|
||||
}
|
||||
|
||||
private void EnsureCsrfCookie(bool persistent, bool? secureOverride = null)
|
||||
|
||||
Reference in New Issue
Block a user