Added Authentication with user-auth and apikey-auth
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.OpenApi.Models;
|
||||
|
||||
@@ -41,6 +42,22 @@ builder.Services.AddDbContext<WatcherDbContext>((serviceProvider, options) =>
|
||||
// Add services to the container.
|
||||
builder.Services.AddControllersWithViews();
|
||||
|
||||
// Cookie-basierte Authentifizierung
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(options =>
|
||||
{
|
||||
options.LoginPath = "/Auth/Login";
|
||||
options.LogoutPath = "/Auth/Logout";
|
||||
options.AccessDeniedPath = "/Auth/AccessDenied";
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(8);
|
||||
options.SlidingExpiration = true;
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
// Health Checks
|
||||
builder.Services.AddHealthChecks();
|
||||
|
||||
@@ -69,6 +86,24 @@ using (var scope = app.Services.CreateScope())
|
||||
Log.Information("Führe Datenbank-Migrationen aus...");
|
||||
dbContext.Database.Migrate();
|
||||
Log.Information("Datenbank-Migrationen erfolgreich angewendet");
|
||||
|
||||
// Standard-Admin-User erstellen, falls noch kein User existiert
|
||||
if (!dbContext.Users.Any())
|
||||
{
|
||||
Log.Information("Erstelle Standard-Admin-User...");
|
||||
var adminUser = new watcher_monitoring.Models.User
|
||||
{
|
||||
Username = "admin",
|
||||
Email = "admin@watcher.local",
|
||||
Password = BCrypt.Net.BCrypt.HashPassword("admin"),
|
||||
IsActive = true,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
LastLogin = DateTime.UtcNow
|
||||
};
|
||||
dbContext.Users.Add(adminUser);
|
||||
dbContext.SaveChanges();
|
||||
Log.Information("Standard-Admin-User erstellt (Username: admin, Passwort: admin)");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -98,6 +133,7 @@ app.UseSwaggerUI(options =>
|
||||
options.RoutePrefix = "api/v1/swagger";
|
||||
});
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// Health Check Endpoint
|
||||
|
||||
Reference in New Issue
Block a user