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
This commit is contained in:
1 parent
550c621f35
commit
a379f2b136
4 files changed
+162
-25
No files matched your search
@@ -25,11 +25,13 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly IWebHostEnvironment _env;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
|
||||
public AuthController(IMediator mediator, IWebHostEnvironment env)
|
||||
public AuthController(IMediator mediator, IWebHostEnvironment env, ILogger<AuthController> logger)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_env = env;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Register a new user.</summary>
|
||||
@@ -39,11 +41,18 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Authenticate a user.</summary>
|
||||
@@ -53,11 +62,18 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Verify a 2FA code.</summary>
|
||||
@@ -67,11 +83,18 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Refresh an authentication token.</summary>
|
||||
@@ -81,10 +104,17 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Change the current user's password.</summary>
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
/// <summary>Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).</summary>
|
||||
@@ -116,13 +156,23 @@ public class AuthController : ControllerBase
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
/// <summary>Enable 2FA for the current user.</summary>
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
/// <summary>Disable 2FA for the current user.</summary>
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
/// <summary>Logout — revoke the current refresh token.</summary>
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user