Token fix?

This commit is contained in:
dingo
2025-12-04 15:37:22 -05:00
parent ea3cf510e5
commit 4decec8ff2
2 changed files with 30 additions and 11 deletions
+24 -5
View File
@@ -14,11 +14,13 @@ public class AuthApiController : ControllerBase
{ {
private readonly GameDbContext _db; private readonly GameDbContext _db;
private readonly IPasswordHasher _hasher; private readonly IPasswordHasher _hasher;
private readonly ILogger<AuthApiController> _log;
public AuthApiController(GameDbContext db, IPasswordHasher hasher) public AuthApiController(GameDbContext db, IPasswordHasher hasher, ILogger<AuthApiController> log)
{ {
_db = db; _db = db;
_hasher = hasher; _hasher = hasher;
_log = log;
} }
/// <summary> /// <summary>
@@ -50,14 +52,16 @@ public class AuthApiController : ControllerBase
// Generate session token // Generate session token
var token = GenerateToken(); var token = GenerateToken();
var tokenHash = HashTokenToString(token); var tokenHash = HashTokenToBase64(token);
_log.LogInformation("Login: Generated token for user {User}, hash: {Hash}", account.Username, tokenHash);
var session = new Session var session = new Session
{ {
AccountId = account.Id, AccountId = account.Id,
TokenHash = tokenHash, TokenHash = tokenHash,
CreatedAt = DateTime.UtcNow, CreatedAt = DateTime.UtcNow,
ExpiresAt = DateTime.UtcNow.AddDays(7), // 7 day expiry for API tokens ExpiresAt = DateTime.UtcNow.AddDays(7),
CreatedIp = HttpContext.Connection.RemoteIpAddress?.ToString(), CreatedIp = HttpContext.Connection.RemoteIpAddress?.ToString(),
UserAgent = Request.Headers.UserAgent.ToString() UserAgent = Request.Headers.UserAgent.ToString()
}; };
@@ -85,7 +89,7 @@ public class AuthApiController : ControllerBase
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
return BadRequest(new { error = "No token provided" }); return BadRequest(new { error = "No token provided" });
var tokenHash = HashTokenToString(token); var tokenHash = HashTokenToBase64(token);
var session = await _db.Sessions var session = await _db.Sessions
.FirstOrDefaultAsync(s => s.TokenHash == tokenHash && s.RevokedAt == null); .FirstOrDefaultAsync(s => s.TokenHash == tokenHash && s.RevokedAt == null);
@@ -98,6 +102,16 @@ public class AuthApiController : ControllerBase
return Ok(new { message = "Logged out successfully" }); return Ok(new { message = "Logged out successfully" });
} }
/// <summary>
/// Debug endpoint to verify token hashing
/// </summary>
[HttpPost("debug-token")]
public IActionResult DebugToken([FromBody] DebugTokenRequest request)
{
var hash = HashTokenToBase64(request.Token);
return Ok(new { token = request.Token, hash, hashLength = hash.Length });
}
private static string GenerateToken() private static string GenerateToken()
{ {
var bytes = new byte[32]; var bytes = new byte[32];
@@ -106,7 +120,7 @@ public class AuthApiController : ControllerBase
return Convert.ToBase64String(bytes); return Convert.ToBase64String(bytes);
} }
private static string HashTokenToString(string token) private static string HashTokenToBase64(string token)
{ {
using var sha = System.Security.Cryptography.SHA256.Create(); using var sha = System.Security.Cryptography.SHA256.Create();
var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token)); var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token));
@@ -128,3 +142,8 @@ public class LoginResponse
public string Username { get; set; } = ""; public string Username { get; set; } = "";
public string Role { get; set; } = ""; public string Role { get; set; } = "";
} }
public class DebugTokenRequest
{
public string Token { get; set; } = "";
}
+6 -6
View File
@@ -45,10 +45,10 @@ public sealed class AdminAuthService : IAdminAuthService
using var scope = _scopeFactory.CreateScope(); using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>(); var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Hash the token to match against stored hash // Hash the token to match against stored hash (base64 format)
var tokenHash = HashTokenToString(token); var tokenHash = HashTokenToBase64(token);
_log.LogDebug("Validating token hash: {Hash}", tokenHash); _log.LogDebug("Validating token, computed hash: {Hash}", tokenHash);
// Find valid session with this token // Find valid session with this token
var session = await db.Sessions var session = await db.Sessions
@@ -60,7 +60,7 @@ public sealed class AdminAuthService : IAdminAuthService
if (session == null) if (session == null)
{ {
_log.LogDebug("No session found for hash {Hash}", tokenHash); _log.LogWarning("No session found for token hash: {Hash}", tokenHash);
return AdminAuthResult.Fail("Invalid or expired token"); return AdminAuthResult.Fail("Invalid or expired token");
} }
@@ -79,10 +79,10 @@ public sealed class AdminAuthService : IAdminAuthService
return AdminAuthResult.Success(account); return AdminAuthResult.Success(account);
} }
private static string HashTokenToString(string token) private static string HashTokenToBase64(string token)
{ {
using var sha = System.Security.Cryptography.SHA256.Create(); using var sha = System.Security.Cryptography.SHA256.Create();
var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token)); var hashBytes = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(hashBytes).ToLowerInvariant(); // Hex is safer than base64 return Convert.ToBase64String(hashBytes);
} }
} }