From a379f2b1366501fd259ced5b2b6a23673dcb6125 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 24 Jul 2026 18:25:33 +0000 Subject: [PATCH] feat(logging): add comprehensive authentication logging - Add cookie authentication event logging in Program.cs (redirect to login, access denied, principal validation) - Add logging in RedirectToLogin.razor for redirection tracking - Add detailed logging in Login.razor for login attempts, 2FA verification, and authentication completion - Add structured logging in AuthController for all authentication endpoints (register, login, 2fa, refresh, change-password, logout, etc.) - Use appropriate log levels (Information, Warning, Error, Debug) based on event importance --- src/Heimdall.Web/Components/Pages/Login.razor | 32 +++++ .../Components/Pages/RedirectToLogin.razor | 3 + .../Controllers/AuthController.cs | 125 ++++++++++++++---- src/Heimdall.Web/Program.cs | 27 ++++ 4 files changed, 162 insertions(+), 25 deletions(-) diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index 74ec3bc..fe4ff4f 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -6,6 +6,7 @@ @inject ISnackbar Snackbar @inject HeimdallAuthStateProvider AuthStateProvider @inject IJSRuntime JsRuntime +@inject Microsoft.Extensions.Logging.ILogger Logger @using Microsoft.AspNetCore.WebUtilities
@@ -97,8 +98,14 @@ protected override void OnInitialized() { + Logger.LogInformation("Login page initialized. User logged in: {IsLoggedIn}", Auth.IsLoggedIn); + if (Auth.IsLoggedIn) + { + Logger.LogInformation("User already logged in, redirecting to dashboard"); Navigation.NavigateTo("/dashboard"); + return; + } // Extract returnUrl from query string (validate local/relative only) var uri = Navigation.ToAbsoluteUri(Navigation.Uri); @@ -107,7 +114,10 @@ { var raw = returnUrl.FirstOrDefault() ?? "/dashboard"; if (raw.StartsWith('/') && !raw.StartsWith("//") && !raw.Contains("://", StringComparison.Ordinal)) + { _returnUrl = raw; + Logger.LogInformation("Return URL extracted: {ReturnUrl}", _returnUrl); + } } } @@ -115,20 +125,26 @@ { _loading = true; _errorMessage = ""; + Logger.LogInformation("Login attempt for email: {Email}", _email); + try { var result = await Api.LoginAsync(_email, _password); if (result is null) { + Logger.LogWarning("Login failed: Invalid credentials for {Email}", _email); _errorMessage = "Email ou mot de passe invalide"; return; } + Logger.LogInformation("Login successful for {Email}. Requires 2FA: {Requires2fa}", _email, result.Requires2fa); + // Check if 2FA is required if (result.Requires2fa) { _requires2fa = true; _loading = false; + Logger.LogInformation("2FA required for {Email}", _email); return; } @@ -136,6 +152,7 @@ } catch (Exception ex) { + Logger.LogError(ex, "Login error for {Email}", _email); _errorMessage = $"Erreur : {ex.Message}"; } finally { _loading = false; } @@ -145,25 +162,31 @@ { if (string.IsNullOrWhiteSpace(_twoFactorCode)) { + Logger.LogWarning("2FA verification attempted with empty code for {Email}", _email); _errorMessage = "Le code 2FA est requis"; return; } _loading = true; _errorMessage = ""; + Logger.LogInformation("2FA verification attempt for {Email}", _email); + try { var result = await Api.Verify2faAsync(_email, _twoFactorCode.Trim()); if (result is null) { + Logger.LogWarning("2FA verification failed for {Email}", _email); _errorMessage = "Code 2FA invalide. Veuillez réessayer."; return; } + Logger.LogInformation("2FA verification successful for {Email}", _email); await CompleteAuthAsync(result); } catch (Exception ex) { + Logger.LogError(ex, "2FA verification error for {Email}", _email); _errorMessage = $"Erreur : {ex.Message}"; } finally { _loading = false; } @@ -171,6 +194,8 @@ private async Task CompleteAuthAsync(AuthResponse result) { + Logger.LogInformation("Completing authentication for {Email}", _email); + // Update Blazor-level auth state await AuthStateProvider.NotifyLoginAsync(result); @@ -178,16 +203,23 @@ var cookieOk = true; if (!string.IsNullOrEmpty(result.AccessToken)) { + Logger.LogDebug("Creating auth cookie for {Email}", _email); cookieOk = await AuthHelper.SignInAsync(JsRuntime, AuthHelper.CreateSignInPayload(result.AccessToken)); } + else + { + Logger.LogWarning("No access token in auth response for {Email}", _email); + } if (!cookieOk) { + Logger.LogError("Failed to create auth cookie for {Email}", _email); _errorMessage = "Erreur lors de la création de la session. Veuillez réessayer."; return; } + Logger.LogInformation("Authentication completed successfully for {Email}, redirecting to {ReturnUrl}", _email, _returnUrl); Snackbar.Add("Connexion réussie", Severity.Success); Navigation.NavigateTo(_returnUrl); } diff --git a/src/Heimdall.Web/Components/Pages/RedirectToLogin.razor b/src/Heimdall.Web/Components/Pages/RedirectToLogin.razor index 1ae2564..f11aa3f 100644 --- a/src/Heimdall.Web/Components/Pages/RedirectToLogin.razor +++ b/src/Heimdall.Web/Components/Pages/RedirectToLogin.razor @@ -1,9 +1,12 @@ @inject NavigationManager Navigation +@inject Microsoft.Extensions.Logging.ILogger Logger @code { protected override void OnInitialized() { var returnUrl = Uri.EscapeDataString(Navigation.ToBaseRelativePath(Navigation.Uri)); + Logger.LogInformation("RedirectToLogin: Redirecting from {CurrentUri} to /login?returnUrl={ReturnUrl}", + Navigation.Uri, returnUrl); Navigation.NavigateTo($"/login?returnUrl={returnUrl}", true); } } diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index 33930cf..d4617bc 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -25,11 +25,13 @@ public class AuthController : ControllerBase { private readonly IMediator _mediator; private readonly IWebHostEnvironment _env; + private readonly ILogger _logger; - public AuthController(IMediator mediator, IWebHostEnvironment env) + public AuthController(IMediator mediator, IWebHostEnvironment env, ILogger logger) { _mediator = mediator; _env = env; + _logger = logger; } /// Register a new user. @@ -39,11 +41,18 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Register([FromBody] RegisterRequest request, CancellationToken ct) { + _logger.LogInformation("Register attempt for {Email}", request.Email); var command = new RegisterCommand(request.Email, request.Password, request.DisplayName); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("User registered successfully: {Email}", request.Email); + return Ok(result.Data); + } + + _logger.LogWarning("User registration failed for {Email}: {Error}", request.Email, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Authenticate a user. @@ -53,11 +62,18 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Login([FromBody] LoginRequest request, CancellationToken ct) { + _logger.LogInformation("Login attempt for {Email}", request.Email); var command = new LoginCommand(request.Email, request.Password); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("Login successful for {Email}", request.Email); + return Ok(result.Data); + } + + _logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error); + return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Verify a 2FA code. @@ -67,11 +83,18 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct) { + _logger.LogInformation("2FA verification attempt for {Email}", request.Email); var command = new Verify2faCommand(request.Email, request.Code); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("2FA verification successful for {Email}", request.Email); + return Ok(result.Data); + } + + _logger.LogWarning("2FA verification failed for {Email}: {Error}", request.Email, result.Error); + return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Refresh an authentication token. @@ -81,10 +104,17 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct) { + _logger.LogDebug("Token refresh attempt"); var result = await _mediator.Send(new RefreshTokenCommand(request.RefreshToken), ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogDebug("Token refresh successful"); + return Ok(result.Data); + } + + _logger.LogWarning("Token refresh failed: {Error}", result.Error); + return StatusCode(result.StatusCode ?? 401, new { error = result.Error }); } /// Change the current user's password. @@ -98,13 +128,23 @@ public class AuthController : ControllerBase { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + { + _logger.LogWarning("Change password failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); + } + _logger.LogInformation("Password change attempt for user {UserId}", userId); var command = new ChangePasswordCommand(userId, request.CurrentPassword, request.NewPassword); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("Password changed successfully for user {UserId}", userId); + return Ok(); + } + + _logger.LogWarning("Password change failed for user {UserId}: {Error}", userId, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg). @@ -116,13 +156,23 @@ public class AuthController : ControllerBase public async Task RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct) { if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment()) + { + _logger.LogWarning("RegisterAdmin endpoint accessed in {Environment} environment - returning 404", _env.EnvironmentName); return NotFound(); + } + _logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email); var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("Admin user registered successfully: {Email}", request.Email); + return Ok(result.Data); + } + + _logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Enable 2FA for the current user. @@ -134,12 +184,22 @@ public class AuthController : ControllerBase { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + { + _logger.LogWarning("Enable2fa failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); + } + _logger.LogInformation("2FA enable attempt for user {UserId}", userId); var result = await _mediator.Send(new Enable2faCommand(userId), ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("2FA enabled successfully for user {UserId}", userId); + return Ok(); + } + + _logger.LogWarning("2FA enable failed for user {UserId}: {Error}", userId, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Disable 2FA for the current user. @@ -151,12 +211,22 @@ public class AuthController : ControllerBase { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + { + _logger.LogWarning("Disable2fa failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); + } + _logger.LogInformation("2FA disable attempt for user {UserId}", userId); var result = await _mediator.Send(new Disable2faCommand(userId), ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + if (result.IsSuccess) + { + _logger.LogInformation("2FA disabled successfully for user {UserId}", userId); + return Ok(); + } + + _logger.LogWarning("2FA disable failed for user {UserId}: {Error}", userId, result.Error); + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Logout — revoke the current refresh token. @@ -167,9 +237,14 @@ public class AuthController : ControllerBase { var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + { + _logger.LogWarning("Logout failed: Invalid user identity"); return Unauthorized(new { error = "Invalid user identity" }); + } + _logger.LogInformation("Logout attempt for user {UserId}", userId); await _mediator.Send(new LogoutCommand(userId, request.RefreshToken), ct); + _logger.LogInformation("Logout successful for user {UserId}", userId); return Ok(); } } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 31b3077..fe33ea9 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -232,6 +232,33 @@ public partial class Program { options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.ExpireTimeSpan = TimeSpan.FromDays(7); options.SlidingExpiration = true; + + // Add logging events + options.Events = new CookieAuthenticationEvents + { + OnRedirectToLogin = context => + { + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + logger.LogWarning("Redirect to login: {Path} -> {LoginPath}", + context.Request.Path, options.LoginPath); + context.Response.Redirect(context.RedirectUri); + return Task.CompletedTask; + }, + OnRedirectToAccessDenied = context => + { + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + logger.LogWarning("Access denied: {Path} -> {AccessDeniedPath}", + context.Request.Path, options.AccessDeniedPath); + context.Response.Redirect(context.RedirectUri); + return Task.CompletedTask; + }, + OnValidatePrincipal = context => + { + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + logger.LogDebug("Validating principal for {Path}", context.HttpContext.Request.Path); + return Task.CompletedTask; + } + }; }) .AddJwtBearer("JwtBearer", options => {