feat(auth): add trusted-device 30-day 2FA skip (backend)

Adds a "trust this device" option to the 2FA challenge: on success, mints a
random token (only its SHA-256 hash is stored), sets it as a new httpOnly,
Secure, SameSite=Strict cookie, and records a TrustedDevice row. AuthController
checks that cookie for the exact signing-in user before gating on 2FA -- a
mismatched user, expired, or revoked device falls through to the normal 2FA
prompt, never errors. TwoFactorController also exposes list/revoke/revoke-all
endpoints for managing trusted devices, scoped to the owning user.

Schema added via the existing raw-SQL reconciler (SQLite + MySQL dialects),
not EF migrations, matching this repo's established pattern.
This commit is contained in:
cesnimda
2026-07-13 01:02:35 +02:00
parent b85dc1ffb7
commit b914630657
10 changed files with 554 additions and 9 deletions
+14 -1
View File
@@ -1,5 +1,6 @@
using System.Text.Json;
using System.Security.Claims;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
@@ -22,8 +23,9 @@ public sealed class AuthController : ControllerBase
private readonly IMicrosoftTokenValidator _microsoftTokens;
private readonly ILogger<AuthController> _logger;
private readonly ITwoFactorPendingTokenService _twoFactorPending;
private readonly JobTrackerContext _db;
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger, ITwoFactorPendingTokenService twoFactorPending)
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger, ITwoFactorPendingTokenService twoFactorPending, JobTrackerContext db)
{
_cfg = cfg;
_users = users;
@@ -33,6 +35,7 @@ public sealed class AuthController : ControllerBase
_microsoftTokens = microsoftTokens;
_logger = logger;
_twoFactorPending = twoFactorPending;
_db = db;
}
[HttpGet("config")]
@@ -671,6 +674,16 @@ public sealed class AuthController : ControllerBase
// decorative: skipping straight to AppSessionIssuer here would defeat the whole feature.
private async Task<IActionResult> CompleteSignInAsync(ApplicationUser user, bool rememberMe, string provider, CancellationToken cancellationToken)
{
// "Trust this device" cookie check happens BEFORE the 2FA gate: if it matches a
// non-expired row for this exact user, skip straight to a real session, same as if 2FA
// weren't required at all. Falls through to the normal gate for any other outcome
// (no cookie, wrong user, expired, revoked) -- never errors, just doesn't skip.
if (user.TwoFactorEnabled && await TrustedDeviceService.IsDeviceTrustedAsync(_db, Request, user.Id, cancellationToken))
{
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, user, rememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, provider));
}
if (user.TwoFactorEnabled)
{
var pendingToken = _twoFactorPending.IssuePendingToken(user.Id, rememberMe);
@@ -44,7 +44,8 @@ public sealed class TwoFactorController : ControllerBase
public sealed record VerifySetupResult(bool Enabled, IReadOnlyList<string> RecoveryCodes);
public sealed record StatusResult(bool Enabled, DateTimeOffset? EnabledAtUtc);
public sealed record RecoveryCodesResult(IReadOnlyList<string> RecoveryCodes);
public sealed record ChallengeRequest(string PendingToken, string Code);
public sealed record ChallengeRequest(string PendingToken, string Code, bool TrustDevice = false);
public sealed record TrustedDeviceDto(int Id, string? DeviceLabel, DateTimeOffset CreatedAtUtc, DateTimeOffset LastSeenAtUtc, DateTimeOffset ExpiresAtUtc, bool IsCurrentDevice);
[HttpPost("setup")]
[Authorize(AuthenticationSchemes = "local")]
@@ -202,9 +203,74 @@ public sealed class TwoFactorController : ControllerBase
_pending.Resolve(pendingToken, consume: true);
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, user, session.RememberMe, cancellationToken);
if (request.TrustDevice)
{
await TrustedDeviceService.IssueAsync(_db, Request, Response, user.Id, cancellationToken);
}
return Ok(new AuthController.AuthSessionResult(true, "local"));
}
[HttpGet("trusted-devices")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> ListTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
var devices = await _db.TrustedDevices
.Where(x => x.UserId == user.Id)
.OrderByDescending(x => x.LastSeenAtUtc)
.Select(x => new TrustedDeviceDto(x.Id, x.DeviceLabel, x.CreatedAtUtc, x.LastSeenAtUtc, x.ExpiresAtUtc, currentHash != null && x.TokenHash == currentHash))
.ToListAsync(cancellationToken);
return Ok(devices);
}
[HttpDelete("trusted-devices/{id:int}")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeTrustedDevice(int id, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var device = await _db.TrustedDevices.FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id, cancellationToken);
if (device is null) return NotFound();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
var isCurrentDevice = currentHash != null && string.Equals(device.TokenHash, currentHash, StringComparison.Ordinal);
_db.TrustedDevices.Remove(device);
await _db.SaveChangesAsync(cancellationToken);
if (isCurrentDevice)
{
TrustedDeviceService.ClearCookie(Request, Response);
}
return NoContent();
}
[HttpPost("trusted-devices/revoke-all")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeAllTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var devices = await _db.TrustedDevices.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);
if (devices.Count > 0)
{
_db.TrustedDevices.RemoveRange(devices);
await _db.SaveChangesAsync(cancellationToken);
}
TrustedDeviceService.ClearCookie(Request, Response);
return NoContent();
}
private static bool VerifyCode(string base32Secret, string? code)
{
code = (code ?? string.Empty).Trim();