1 Commits

Author SHA1 Message Date
ad9b6bfdaf OIDC Integration
All checks were successful
Gitea CI/CD / dotnet-build-and-test (push) Successful in 10m0s
Gitea CI/CD / Set Tag Name (push) Successful in 5s
Gitea CI/CD / docker-build-and-push (push) Successful in 11m39s
Gitea CI/CD / Create Tag (push) Successful in 5s
2026-01-21 10:05:03 +01:00
10 changed files with 482 additions and 2 deletions

View File

@@ -44,6 +44,17 @@ services:
# Aktualisierungsrate Frontend # Aktualisierungsrate Frontend
- FRONTEND_REFRESH_INTERVAL_SECONDS=30 - FRONTEND_REFRESH_INTERVAL_SECONDS=30
# OIDC-Authentifizierung (Optional)
# - OIDC_ENABLED=true
# - OIDC_AUTHORITY=https://auth.example.com/realms/myrealm
# - OIDC_CLIENT_ID=watcher-client
# - OIDC_CLIENT_SECRET=your-client-secret
# - OIDC_SCOPES=openid profile email
# - OIDC_CALLBACK_PATH=/signin-oidc
# - OIDC_CLAIM_USERNAME=preferred_username
# - OIDC_CLAIM_EMAIL=email
# - OIDC_AUTO_PROVISION_USERS=true
# Ports # Ports
ports: ports:
- "5000:5000" - "5000:5000"

View File

@@ -0,0 +1,53 @@
namespace watcher_monitoring.Configuration;
public class OidcSettings
{
public bool Enabled { get; set; } = false;
public string Authority { get; set; } = string.Empty;
public string ClientId { get; set; } = string.Empty;
public string ClientSecret { get; set; } = string.Empty;
public string Scopes { get; set; } = "openid profile email";
public string CallbackPath { get; set; } = "/signin-oidc";
public string ClaimUsername { get; set; } = "preferred_username";
public string ClaimEmail { get; set; } = "email";
public bool AutoProvisionUsers { get; set; } = true;
public bool IsValid => Enabled &&
!string.IsNullOrWhiteSpace(Authority) &&
!string.IsNullOrWhiteSpace(ClientId) &&
!string.IsNullOrWhiteSpace(ClientSecret);
public string[] GetScopes() => Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries);
public static OidcSettings FromEnvironment()
{
return new OidcSettings
{
Enabled = GetBoolEnv("OIDC_ENABLED", false),
Authority = Environment.GetEnvironmentVariable("OIDC_AUTHORITY") ?? string.Empty,
ClientId = Environment.GetEnvironmentVariable("OIDC_CLIENT_ID") ?? string.Empty,
ClientSecret = Environment.GetEnvironmentVariable("OIDC_CLIENT_SECRET") ?? string.Empty,
Scopes = Environment.GetEnvironmentVariable("OIDC_SCOPES") ?? "openid profile email",
CallbackPath = Environment.GetEnvironmentVariable("OIDC_CALLBACK_PATH") ?? "/signin-oidc",
ClaimUsername = Environment.GetEnvironmentVariable("OIDC_CLAIM_USERNAME") ?? "preferred_username",
ClaimEmail = Environment.GetEnvironmentVariable("OIDC_CLAIM_EMAIL") ?? "email",
AutoProvisionUsers = GetBoolEnv("OIDC_AUTO_PROVISION_USERS", true)
};
}
private static bool GetBoolEnv(string key, bool defaultValue)
{
var value = Environment.GetEnvironmentVariable(key);
if (string.IsNullOrWhiteSpace(value)) return defaultValue;
return value.Equals("true", StringComparison.OrdinalIgnoreCase) ||
value.Equals("1", StringComparison.OrdinalIgnoreCase);
}
}

View File

@@ -1,9 +1,11 @@
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using watcher_monitoring.Configuration;
using watcher_monitoring.Data; using watcher_monitoring.Data;
using watcher_monitoring.Models; using watcher_monitoring.Models;
@@ -13,11 +15,13 @@ public class AuthController : Controller
{ {
private readonly WatcherDbContext _context; private readonly WatcherDbContext _context;
private readonly ILogger<AuthController> _logger; private readonly ILogger<AuthController> _logger;
private readonly OidcSettings _oidcSettings;
public AuthController(WatcherDbContext context, ILogger<AuthController> logger) public AuthController(WatcherDbContext context, ILogger<AuthController> logger, OidcSettings oidcSettings)
{ {
_context = context; _context = context;
_logger = logger; _logger = logger;
_oidcSettings = oidcSettings;
} }
[AllowAnonymous] [AllowAnonymous]
@@ -31,9 +35,138 @@ public class AuthController : Controller
} }
ViewData["ReturnUrl"] = returnUrl; ViewData["ReturnUrl"] = returnUrl;
ViewData["OidcEnabled"] = _oidcSettings.IsValid;
return View(); return View();
} }
[AllowAnonymous]
[HttpGet]
public IActionResult OidcLogin(string? returnUrl = null)
{
if (!_oidcSettings.IsValid)
{
_logger.LogWarning("OIDC-Login versucht, aber OIDC ist nicht konfiguriert");
return RedirectToAction("Login");
}
var properties = new AuthenticationProperties
{
RedirectUri = Url.Action("OidcCallback", "Auth", new { returnUrl }),
Items = { { "returnUrl", returnUrl ?? "/" } }
};
return Challenge(properties, OpenIdConnectDefaults.AuthenticationScheme);
}
[AllowAnonymous]
[HttpGet]
public async Task<IActionResult> OidcCallback(string? returnUrl = null)
{
var authenticateResult = await HttpContext.AuthenticateAsync(OpenIdConnectDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
{
_logger.LogWarning("OIDC-Authentifizierung fehlgeschlagen: {Failure}", authenticateResult.Failure?.Message);
TempData["Error"] = "OIDC-Anmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.";
return RedirectToAction("Login");
}
var oidcClaims = authenticateResult.Principal?.Claims;
var oidcSubject = oidcClaims?.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value
?? oidcClaims?.FirstOrDefault(c => c.Type == "sub")?.Value;
if (string.IsNullOrEmpty(oidcSubject))
{
_logger.LogError("OIDC-Claims enthalten keine Subject-ID");
TempData["Error"] = "OIDC-Anmeldung fehlgeschlagen: Keine Benutzer-ID erhalten.";
return RedirectToAction("Login");
}
var username = oidcClaims?.FirstOrDefault(c => c.Type == _oidcSettings.ClaimUsername)?.Value
?? oidcClaims?.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value
?? oidcClaims?.FirstOrDefault(c => c.Type == "name")?.Value
?? oidcSubject;
var email = oidcClaims?.FirstOrDefault(c => c.Type == _oidcSettings.ClaimEmail)?.Value
?? oidcClaims?.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value
?? $"{username}@oidc.local";
var user = await _context.Users.FirstOrDefaultAsync(u => u.OidcSubject == oidcSubject);
if (user == null)
{
if (!_oidcSettings.AutoProvisionUsers)
{
_logger.LogWarning("OIDC-User {Subject} existiert nicht und Auto-Provisioning ist deaktiviert", oidcSubject);
TempData["Error"] = "Ihr Benutzerkonto existiert nicht. Bitte kontaktieren Sie den Administrator.";
return RedirectToAction("Login");
}
var existingUsername = await _context.Users.AnyAsync(u => u.Username == username);
if (existingUsername)
{
username = $"{username}_{oidcSubject[..Math.Min(8, oidcSubject.Length)]}";
}
user = new User
{
Username = username,
Email = email,
OidcSubject = oidcSubject,
Password = string.Empty,
IsActive = true,
CreatedAt = DateTime.UtcNow,
LastLogin = DateTime.UtcNow
};
_context.Users.Add(user);
await _context.SaveChangesAsync();
_logger.LogInformation("OIDC-User {Username} wurde automatisch erstellt (Subject: {Subject})", username, oidcSubject);
}
else
{
if (!user.IsActive)
{
_logger.LogWarning("OIDC-User {Username} ist deaktiviert", user.Username);
TempData["Error"] = "Ihr Benutzerkonto ist deaktiviert.";
return RedirectToAction("Login");
}
user.LastLogin = DateTime.UtcNow;
user.Email = email;
await _context.SaveChangesAsync();
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Email, user.Email),
new Claim("LastLogin", user.LastLogin.ToString("o")),
new Claim("AuthMethod", "OIDC")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(8)
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);
_logger.LogInformation("OIDC-User {Username} erfolgreich angemeldet", user.Username);
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
[AllowAnonymous] [AllowAnonymous]
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]

View File

@@ -0,0 +1,181 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using watcher_monitoring.Data;
#nullable disable
namespace watcher_monitoring.Migrations
{
[DbContext(typeof(WatcherDbContext))]
[Migration("20260121084748_AddOidcSubjectToUser")]
partial class AddOidcSubjectToUser
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.6");
modelBuilder.Entity("watcher_monitoring.Models.ApiKey", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Description")
.HasColumnType("TEXT");
b.Property<DateTime?>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<bool>("IsActive")
.HasColumnType("INTEGER");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("watcher_monitoring.Models.Container", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ContainerName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Containers");
});
modelBuilder.Entity("watcher_monitoring.Models.Server", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("CpuCores")
.HasColumnType("INTEGER");
b.Property<string>("CpuType")
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("DiskSpace")
.HasColumnType("TEXT");
b.Property<string>("GpuType")
.HasColumnType("TEXT");
b.Property<string>("IPAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsOnline")
.HasColumnType("INTEGER");
b.Property<bool>("IsVerified")
.HasColumnType("INTEGER");
b.Property<DateTime>("LastSeen")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<double>("RamSize")
.HasColumnType("REAL");
b.HasKey("Id");
b.ToTable("Servers");
});
modelBuilder.Entity("watcher_monitoring.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("IsActive")
.HasColumnType("INTEGER");
b.Property<DateTime>("LastLogin")
.HasColumnType("TEXT");
b.Property<string>("OidcSubject")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("watcher_monitoring.Models.ApiKey", b =>
{
b.HasOne("watcher_monitoring.Models.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("watcher_monitoring.Models.User", b =>
{
b.Navigation("ApiKeys");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace watcher_monitoring.Migrations
{
/// <inheritdoc />
public partial class AddOidcSubjectToUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "OidcSubject",
table: "Users",
type: "TEXT",
maxLength: 255,
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Users_OidcSubject",
table: "Users",
column: "OidcSubject",
unique: true,
filter: "OidcSubject IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_OidcSubject",
table: "Users");
migrationBuilder.DropColumn(
name: "OidcSubject",
table: "Users");
}
}
}

View File

@@ -139,6 +139,10 @@ namespace watcher_monitoring.Migrations
b.Property<DateTime>("LastLogin") b.Property<DateTime>("LastLogin")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("OidcSubject")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("Password") b.Property<string>("Password")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");

View File

@@ -27,6 +27,11 @@ public class User
public bool IsActive { get; set; } = true; public bool IsActive { get; set; } = true;
[StringLength(255)]
public string? OidcSubject { get; set; }
public bool IsOidcUser => !string.IsNullOrEmpty(OidcSubject);
// Navigation Property: Ein User kann mehrere API-Keys haben // Navigation Property: Ein User kann mehrere API-Keys haben
public ICollection<ApiKey> ApiKeys { get; set; } = new List<ApiKey>(); public ICollection<ApiKey> ApiKeys { get; set; } = new List<ApiKey>();
} }

View File

@@ -1,10 +1,13 @@
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Serilog; using Serilog;
using watcher_monitoring.Configuration;
using watcher_monitoring.Data; using watcher_monitoring.Data;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -27,6 +30,10 @@ builder.Host.UseSerilog();
DotNetEnv.Env.Load(); DotNetEnv.Env.Load();
builder.Configuration.AddEnvironmentVariables(); builder.Configuration.AddEnvironmentVariables();
// OIDC-Einstellungen laden
var oidcSettings = OidcSettings.FromEnvironment();
builder.Services.AddSingleton(oidcSettings);
// Konfiguration laden // Konfiguration laden
var configuration = builder.Configuration; var configuration = builder.Configuration;
@@ -44,7 +51,7 @@ builder.Services.AddDbContext<WatcherDbContext>((serviceProvider, options) =>
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
// Cookie-basierte Authentifizierung // Cookie-basierte Authentifizierung
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) var authBuilder = builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => .AddCookie(options =>
{ {
options.LoginPath = "/Auth/Login"; options.LoginPath = "/Auth/Login";
@@ -57,6 +64,36 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SameSite = SameSiteMode.Lax;
}); });
// OIDC-Authentifizierung (wenn aktiviert)
if (oidcSettings.IsValid)
{
Log.Information("OIDC-Authentifizierung aktiviert für Authority: {Authority}", oidcSettings.Authority);
authBuilder.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = oidcSettings.Authority;
options.ClientId = oidcSettings.ClientId;
options.ClientSecret = oidcSettings.ClientSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.CallbackPath = oidcSettings.CallbackPath;
options.SignedOutCallbackPath = "/signout-callback-oidc";
options.Scope.Clear();
foreach (var scope in oidcSettings.GetScopes())
{
options.Scope.Add(scope);
}
options.TokenValidationParameters.NameClaimType = oidcSettings.ClaimUsername;
options.TokenValidationParameters.RoleClaimType = "roles";
});
}
else if (oidcSettings.Enabled)
{
Log.Warning("OIDC ist aktiviert aber nicht korrekt konfiguriert. Erforderlich: OIDC_AUTHORITY, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET");
}
builder.Services.AddAuthorization(); builder.Services.AddAuthorization();
// Health Checks // Health Checks

View File

@@ -97,6 +97,21 @@
<button type="submit" class="btn btn-primary btn-login">Anmelden</button> <button type="submit" class="btn btn-primary btn-login">Anmelden</button>
</form> </form>
@if (ViewData["OidcEnabled"] is true)
{
<hr class="my-4" />
<div class="text-center">
<p class="text-muted mb-3">oder</p>
<a href="@Url.Action("OidcLogin", "Auth", new { returnUrl = ViewData["ReturnUrl"] })" class="btn btn-outline-secondary w-100">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-shield-lock me-2" viewBox="0 0 16 16">
<path d="M5.338 1.59a61 61 0 0 0-2.837.856.48.48 0 0 0-.328.39c-.554 4.157.726 7.19 2.253 9.188a10.7 10.7 0 0 0 2.287 2.233c.346.244.652.42.893.533q.18.085.293.118a1 1 0 0 0 .101.025 1 1 0 0 0 .1-.025q.114-.034.294-.118c.24-.113.547-.29.893-.533a10.7 10.7 0 0 0 2.287-2.233c1.527-1.997 2.807-5.031 2.253-9.188a.48.48 0 0 0-.328-.39c-.651-.213-1.75-.56-2.837-.855C9.552 1.29 8.531 1.067 8 1.067c-.53 0-1.552.223-2.662.524zM5.072.56C6.157.265 7.31 0 8 0s1.843.265 2.928.56c1.11.3 2.229.655 2.887.87a1.54 1.54 0 0 1 1.044 1.262c.596 4.477-.787 7.795-2.465 9.99a11.8 11.8 0 0 1-2.517 2.453 7 7 0 0 1-1.048.625c-.28.132-.581.24-.829.24s-.548-.108-.829-.24a7 7 0 0 1-1.048-.625 11.8 11.8 0 0 1-2.517-2.453C1.928 10.487.545 7.169 1.141 2.692A1.54 1.54 0 0 1 2.185 1.43 63 63 0 0 1 5.072.56"/>
<path d="M9.5 6.5a1.5 1.5 0 0 1-1 1.415l.385 1.99a.5.5 0 0 1-.491.595h-.788a.5.5 0 0 1-.49-.595l.384-1.99a1.5 1.5 0 1 1 2-1.415"/>
</svg>
Mit oidc anmelden
</a>
</div>
}
</div> </div>
</div> </div>

View File

@@ -17,6 +17,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.6" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.6" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.6" />
</ItemGroup> </ItemGroup>