Baustein 1: Server-Auth-Fix (Kapitel 10)
/api/auth/login und /api/auth/register akzeptierten zuvor jeden beliebigen Nutzernamen/Passwort und stellten ein gueltiges 30-Tage-JWT aus - konkrete, ausnutzbare Luecke bei echtem Deployment. - PasswordHasher (PBKDF2, Salt pro Nutzer) + UserStore (LiteDB) statt des ungeprueften Stubs - /api/auth/register ersatzlos entfernt (kein offener Registrierungs-Endpunkt fuer ein Einzel-/Familien-Deployment) - Neue Nutzer per CLI (dotnet LehrerApp.Api.dll create-user <name>), dokumentiert in docker/README.md - Neues Testprojekt LehrerApp.Api.Tests (bisher als einziges Projekt ohne Tests) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace LehrerApp.Api;
|
||||
|
||||
internal static class Cli
|
||||
{
|
||||
public static Task<int> RunCreateUserAsync(string dataPath, string[] args)
|
||||
{
|
||||
if (args.Length < 2)
|
||||
{
|
||||
Console.Error.WriteLine("Verwendung: create-user <benutzername> [--password <passwort>]");
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
|
||||
var username = args[1];
|
||||
string? password = null;
|
||||
for (var i = 2; i < args.Length - 1; i++)
|
||||
if (args[i] == "--password") password = args[i + 1];
|
||||
|
||||
password ??= ReadPassword("Passwort (mind. 12 Zeichen): ");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(password) || password.Length < 12)
|
||||
{
|
||||
Console.Error.WriteLine("Passwort muss mindestens 12 Zeichen lang sein.");
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(dataPath);
|
||||
using var store = new UserStore(dataPath);
|
||||
if (!store.CreateUser(username, password))
|
||||
{
|
||||
Console.Error.WriteLine($"Nutzer '{username}' existiert bereits.");
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Nutzer '{username}' angelegt.");
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
// docker exec ohne -it liefert kein TTY -> ReadKey wäre nicht möglich, dann normal lesen.
|
||||
private static string ReadPassword(string prompt)
|
||||
{
|
||||
Console.Write(prompt);
|
||||
if (Console.IsInputRedirected) return Console.ReadLine() ?? "";
|
||||
|
||||
var sb = new StringBuilder();
|
||||
ConsoleKeyInfo key;
|
||||
while ((key = Console.ReadKey(intercept: true)).Key != ConsoleKey.Enter)
|
||||
{
|
||||
if (key.Key == ConsoleKey.Backspace && sb.Length > 0) { sb.Length--; Console.Write("\b \b"); }
|
||||
else if (!char.IsControl(key.KeyChar)) { sb.Append(key.KeyChar); Console.Write('*'); }
|
||||
}
|
||||
Console.WriteLine();
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
@@ -14,19 +14,12 @@ public static class Endpoints
|
||||
|
||||
public static void MapAuthEndpoints(this WebApplication app, string secret)
|
||||
{
|
||||
app.MapPost("/api/auth/login", (LoginRequest req) =>
|
||||
app.MapPost("/api/auth/login", (LoginRequest req, UserStore store) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
|
||||
return Results.Unauthorized();
|
||||
// TODO: Passwort gegen DB prüfen
|
||||
return Results.Ok(new { token = Jwt(req.Username, secret), userId = req.Username });
|
||||
});
|
||||
|
||||
app.MapPost("/api/auth/register", (RegisterRequest req) =>
|
||||
{
|
||||
if (req.Password.Length < 12)
|
||||
return Results.BadRequest("Passwort mind. 12 Zeichen.");
|
||||
// TODO: User anlegen, Passwort hashen (BCrypt)
|
||||
if (!store.VerifyPassword(req.Username, req.Password))
|
||||
return Results.Unauthorized();
|
||||
return Results.Ok(new { token = Jwt(req.Username, secret), userId = req.Username });
|
||||
});
|
||||
}
|
||||
@@ -130,4 +123,3 @@ public static class Endpoints
|
||||
}
|
||||
|
||||
public record LoginRequest(string Username, string Password);
|
||||
public record RegisterRequest(string Username, string Password, string DisplayName);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace LehrerApp.Api;
|
||||
|
||||
public static class PasswordHasher
|
||||
{
|
||||
private const int Iterations = 100_000;
|
||||
private const int SaltSize = 16;
|
||||
private const int HashSize = 32;
|
||||
|
||||
public static string Hash(string password)
|
||||
{
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltSize);
|
||||
var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, Iterations, HashAlgorithmName.SHA256, HashSize);
|
||||
return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
|
||||
}
|
||||
|
||||
public static bool Verify(string password, string stored)
|
||||
{
|
||||
var parts = stored.Split(':');
|
||||
if (parts.Length != 2) return false;
|
||||
var salt = Convert.FromBase64String(parts[0]);
|
||||
var expected = Convert.FromBase64String(parts[1]);
|
||||
var actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, Iterations, HashAlgorithmName.SHA256, HashSize);
|
||||
return CryptographicOperations.FixedTimeEquals(actual, expected);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,11 @@ builder.WebHost.UseKestrel(o =>
|
||||
o.ListenAnyIP(port);
|
||||
});
|
||||
|
||||
var data = builder.Configuration["Api:DataPath"] ?? "./data";
|
||||
|
||||
if (args.Length > 0 && args[0] == "create-user")
|
||||
return await Cli.RunCreateUserAsync(data, args);
|
||||
|
||||
var secret = builder.Configuration["JWT_SECRET"]
|
||||
?? throw new InvalidOperationException("JWT_SECRET nicht konfiguriert.");
|
||||
|
||||
@@ -24,7 +29,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
});
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
var data = builder.Configuration["Api:DataPath"] ?? "./data";
|
||||
builder.Services.AddSingleton<UserStore>(_ => new UserStore(data));
|
||||
builder.Services.AddSingleton<EventStore>(_ => new EventStore(data));
|
||||
builder.Services.AddSingleton<SnapshotStore>(_ => new SnapshotStore(data));
|
||||
builder.Services.AddSingleton<ReadableSnapshotStore>(_ => new ReadableSnapshotStore(data));
|
||||
@@ -40,3 +45,4 @@ app.MapSnapshotEndpoints();
|
||||
app.MapReadableSnapshotEndpoints();
|
||||
app.MapPlainSyncEndpoints();
|
||||
app.Run();
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using LiteDB;
|
||||
|
||||
namespace LehrerApp.Api;
|
||||
|
||||
public class UserStore(string dataPath) : IDisposable
|
||||
{
|
||||
private readonly LiteDatabase _db = new(Path.Combine(dataPath, "users.db"));
|
||||
|
||||
private ILiteCollection<UserEntry> Col
|
||||
{
|
||||
get
|
||||
{
|
||||
var col = _db.GetCollection<UserEntry>("users");
|
||||
col.EnsureIndex(x => x.Username, unique: true);
|
||||
return col;
|
||||
}
|
||||
}
|
||||
|
||||
public bool CreateUser(string username, string password)
|
||||
{
|
||||
if (Col.Exists(x => x.Username == username)) return false;
|
||||
Col.Insert(new UserEntry { Username = username, PasswordHash = PasswordHasher.Hash(password) });
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool VerifyPassword(string username, string password)
|
||||
{
|
||||
var user = Col.FindOne(x => x.Username == username);
|
||||
return user is not null && PasswordHasher.Verify(password, user.PasswordHash);
|
||||
}
|
||||
|
||||
public void Dispose() => _db.Dispose();
|
||||
}
|
||||
|
||||
internal class UserEntry
|
||||
{
|
||||
public ObjectId Id { get; set; } = ObjectId.NewObjectId();
|
||||
public string Username { get; set; } = "";
|
||||
public string PasswordHash { get; set; } = "";
|
||||
}
|
||||
Reference in New Issue
Block a user