Add authentication support with login/logout UI

- Introduced AuthService, IAuthApiClient, and AuthApiClient for managing authentication state and API calls (login, logout, session restore).
- Added Login.razor and LoginLayout.razor for the login page, including styling and logic.
- MainLayout.razor now checks authentication on load, restores sessions from sessionStorage, and redirects to /login if unauthenticated. Displays username and logout button when logged in.
- Implemented JS interop (authStorage) for persisting authentication info in sessionStorage.
- Registered AuthService, CookieContainer, and API clients in Program.cs to share cookies and support authentication.
- Updated AppSettings and appsettings files to support separate ApiBaseUrl and DataApiBaseUrl.
- Minor CSS improvements for username display in the top bar.
This commit is contained in:
OlgunR
2026-05-12 16:32:46 +02:00
parent 45011122b2
commit 1ad267e409
13 changed files with 462 additions and 11 deletions

View File

@@ -3,4 +3,5 @@
public class AppSettings
{
public string ApiBaseUrl { get; set; } = string.Empty;
public string DataApiBaseUrl { get; set; } = string.Empty;
}

View File

@@ -31,6 +31,18 @@
else
document.documentElement.classList.remove('dx-dark');
};
window.authStorage = {
get: function (key) { return sessionStorage.getItem(key); },
set: function (username, cookie) {
sessionStorage.setItem('auth_user', username);
sessionStorage.setItem('auth_cookie', cookie);
},
clear: function () {
sessionStorage.removeItem('auth_user');
sessionStorage.removeItem('auth_cookie');
}
};
</script>
<HeadOutlet />
</head>

View File

@@ -0,0 +1,10 @@
@inherits LayoutComponentBase
@inject ThemeState ThemeState
<div class="page @(ThemeState.IsDarkMode ? "app-dark" : "app-light") @(ThemeState.IsNativeDarkTheme ? "native-dark" : "")">
<main>
<article class="content">
@Body
</article>
</main>
</div>

View File

@@ -2,6 +2,9 @@
@implements IDisposable
@inject ThemeState ThemeState
@inject IJSRuntime JS
@inject AuthService AuthService
@inject IAuthApiClient AuthApiClient
@inject NavigationManager Navigation
<div class="page @(ThemeState.IsDarkMode ? "app-dark" : "app-light") @(ThemeState.IsNativeDarkTheme ? "native-dark" : "")">
<div class="sidebar">
@@ -18,11 +21,29 @@
<DxButton Text="@(ThemeState.IsDarkMode ? "Dark Mode aus" : "Dark Mode an")"
Click="ToggleTheme" />
</span>
@if (AuthService.IsAuthenticated)
{
<span class="ms-auto d-flex align-items-center gap-2">
<span class="top-row-username">@AuthService.UserName</span>
<DxButton Text="Abmelden"
Click="LogoutAsync"
RenderStyle="ButtonRenderStyle.Secondary" />
</span>
}
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
@if (_checkingAuth)
{
<div class="loading-container">
<span>Wird geladen…</span>
</div>
}
else
{
@Body
}
</article>
</main>
</div>
@@ -35,10 +56,12 @@
@code {
private bool _isInteractive;
private bool _checkingAuth = true;
protected override void OnInitialized()
{
ThemeState.OnChange += OnThemeChanged;
AuthService.OnChange += OnAuthChanged;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
@@ -46,17 +69,71 @@
if (firstRender)
{
_isInteractive = true;
if (!AuthService.IsAuthenticated)
{
try
{
var username = await JS.InvokeAsync<string?>("authStorage.get", "auth_user");
var cookie = await JS.InvokeAsync<string?>("authStorage.get", "auth_cookie");
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(cookie))
{
var restored = await AuthApiClient.RestoreAsync(username, cookie);
if (!restored)
{
await JS.InvokeVoidAsync("authStorage.clear");
Navigation.NavigateTo("/login", replace: true);
return;
}
}
else
{
Navigation.NavigateTo("/login", replace: true);
return;
}
}
catch
{
Navigation.NavigateTo("/login", replace: true);
return;
}
}
_checkingAuth = false;
StateHasChanged();
}
await ApplyDxDarkOverrideAsync();
}
private async Task LogoutAsync()
{
try
{
await AuthApiClient.LogoutAsync();
await JS.InvokeVoidAsync("authStorage.clear");
}
catch
{
// Fehler beim Abmelden ignorieren, trotzdem weiterleiten
}
Navigation.NavigateTo("/login", replace: true);
}
private void OnAuthChanged()
{
InvokeAsync(StateHasChanged);
}
private void OnThemeChanged()
{
InvokeAsync(async () =>
{
StateHasChanged();
if (_isInteractive)
await ApplyDxDarkOverrideAsync();
await ApplyDxDarkOverrideAsync();
});
}
@@ -82,5 +159,6 @@
public void Dispose()
{
ThemeState.OnChange -= OnThemeChanged;
AuthService.OnChange -= OnAuthChanged;
}
}

View File

@@ -0,0 +1,106 @@
@page "/login"
@layout DbFirst.BlazorWebApp.Components.Layout.LoginLayout
@rendermode InteractiveServer
@inject IAuthApiClient AuthApiClient
@inject AuthService AuthService
@inject NavigationManager Navigation
@inject IJSRuntime JS
<PageTitle>Anmelden DbFirst</PageTitle>
<div class="login-container">
<div class="login-card">
<div class="login-header">
<span class="login-brand">DbFirst</span>
<p class="login-subtitle">Bitte melden Sie sich an</p>
</div>
<form @onsubmit="HandleLoginAsync" @onsubmit:preventDefault>
<div class="login-field">
<label class="login-label" for="username">Benutzername</label>
<input id="username"
type="text"
class="login-text-input"
placeholder="Benutzername eingeben"
autocomplete="username"
@bind="_username"
@bind:event="oninput" />
</div>
<div class="login-field">
<label class="login-label" for="password">Passwort</label>
<input id="password"
type="password"
class="login-text-input"
placeholder="Passwort eingeben"
autocomplete="current-password"
@bind="_password"
@bind:event="oninput" />
</div>
@if (!string.IsNullOrEmpty(_errorMessage))
{
<div class="alert alert-danger mt-2 mb-1" role="alert">
@_errorMessage
</div>
}
<div class="login-actions">
<button type="submit"
class="login-submit-btn"
disabled="@_isLoading">
@(_isLoading ? "Wird angemeldet…" : "Anmelden")
</button>
</div>
</form>
</div>
</div>
@code {
private string _username = string.Empty;
private string _password = string.Empty;
private string _errorMessage = string.Empty;
private bool _isLoading;
protected override void OnInitialized()
{
if (AuthService.IsAuthenticated)
Navigation.NavigateTo("/");
}
private async Task HandleLoginAsync()
{
if (_isLoading) return;
_errorMessage = string.Empty;
if (string.IsNullOrWhiteSpace(_username) || string.IsNullOrWhiteSpace(_password))
{
_errorMessage = "Bitte Benutzername und Passwort eingeben.";
return;
}
_isLoading = true;
try
{
var success = await AuthApiClient.LoginAsync(_username, _password);
if (success)
{
await JS.InvokeVoidAsync("authStorage.set", AuthService.UserName, AuthService.RawCookieHeader);
Navigation.NavigateTo("/");
}
else
{
_errorMessage = "Anmeldung fehlgeschlagen. Bitte Benutzerdaten prüfen.";
}
}
catch
{
_errorMessage = "Verbindungsfehler. Bitte später erneut versuchen.";
}
finally
{
_isLoading = false;
}
}
}

View File

@@ -0,0 +1,111 @@
.login-container {
display: flex;
align-items: center;
justify-content: center;
min-height: calc(100vh - 2rem);
}
.login-card {
width: 100%;
max-width: 400px;
padding: 2rem;
border-radius: 8px;
border: 1px solid var(--band-editor-border, #dee2e6);
background-color: var(--band-editor-bg, #fff);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.login-header {
text-align: center;
margin-bottom: 1.75rem;
}
.login-brand {
font-size: 1.8rem;
font-weight: 700;
color: #1b6ec2;
letter-spacing: 0.02em;
}
.login-subtitle {
margin-top: 0.35rem;
margin-bottom: 0;
font-size: 0.9rem;
color: #6c757d;
}
.login-field {
margin-bottom: 1rem;
}
.login-label {
display: block;
font-size: 0.85rem;
font-weight: 500;
margin-bottom: 0.3rem;
}
.login-actions {
margin-top: 1.25rem;
}
/* Gemeinsamer Stil für Text- und Passwort-Eingabefelder */
.login-text-input {
display: block;
width: 100%;
height: 2.25rem;
padding: 0.25rem 0.65rem;
font-size: 1rem;
font-family: inherit;
line-height: 1.5;
color: inherit;
background-color: transparent;
border: 1px solid #ced4da;
border-radius: 4px;
box-sizing: border-box;
outline: none;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.login-text-input:focus {
border-color: #86b7fe;
box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}
/* Submit-Button */
.login-submit-btn {
display: block;
width: 100%;
padding: 0.45rem 1rem;
font-size: 1rem;
font-family: inherit;
font-weight: 500;
color: #fff;
background-color: #1b6ec2;
border: 1px solid #1861ac;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out;
}
.login-submit-btn:hover:not(:disabled) {
background-color: #1558a0;
border-color: #1456a0;
}
.login-submit-btn:disabled {
opacity: 0.65;
cursor: not-allowed;
}
/* Dark-Mode */
.app-dark .login-text-input {
border-color: #555;
color: #e8e8e8;
background-color: #2d2d2d;
}
.app-dark .login-text-input:focus {
border-color: #6cb6ff;
box-shadow: 0 0 0 0.2rem rgba(108, 182, 255, 0.25);
}

View File

@@ -2,6 +2,7 @@ using DbFirst.BlazorWebApp;
using DbFirst.BlazorWebApp.Components;
using DbFirst.BlazorWebApp.Services;
using DevExpress.Blazor;
using System.Net;
var builder = WebApplication.CreateBuilder(args);
@@ -12,19 +13,45 @@ builder.Services.AddRazorComponents()
builder.Services.AddDevExpressBlazor(options => options.BootstrapVersion = BootstrapVersion.v5);
builder.Services.AddScoped<ThemeState>();
builder.Services.AddScoped<BandLayoutService>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<CookieContainer>();
builder.Services.Configure<AppSettings>(builder.Configuration);
var appSettings = builder.Configuration.Get<AppSettings>() ?? new AppSettings();
void ConfigureClient(HttpClient client)
// Alle API-Clients teilen sich denselben scoped CookieContainer (pro Blazor-Circuit),
// damit das Auth-Cookie nach dem Login automatisch an alle Folgeanfragen angehängt wird.
static HttpClient CreateHttpClientWithCookies(CookieContainer cookieContainer, string? baseUrl)
{
if (!string.IsNullOrWhiteSpace(appSettings.ApiBaseUrl))
client.BaseAddress = new Uri(appSettings.ApiBaseUrl);
var handler = new HttpClientHandler { CookieContainer = cookieContainer, UseCookies = true };
var client = new HttpClient(handler);
if (!string.IsNullOrWhiteSpace(baseUrl))
client.BaseAddress = new Uri(baseUrl);
return client;
}
builder.Services.AddHttpClient<ICatalogApiClient, CatalogApiClient>(ConfigureClient);
builder.Services.AddHttpClient<IDashboardApiClient, DashboardApiClient>(ConfigureClient);
builder.Services.AddHttpClient<IMassDataApiClient, MassDataApiClient>(ConfigureClient);
builder.Services.AddHttpClient<ILayoutApiClient, LayoutApiClient>(ConfigureClient);
builder.Services.AddScoped<IAuthApiClient>(sp =>
{
var cc = sp.GetRequiredService<CookieContainer>();
var client = CreateHttpClientWithCookies(cc, appSettings.ApiBaseUrl);
return new AuthApiClient(client, sp.GetRequiredService<AuthService>(), cc);
});
var dataApiBaseUrl = !string.IsNullOrWhiteSpace(appSettings.DataApiBaseUrl)
? appSettings.DataApiBaseUrl
: appSettings.ApiBaseUrl;
builder.Services.AddScoped<ICatalogApiClient>(sp =>
new CatalogApiClient(CreateHttpClientWithCookies(sp.GetRequiredService<CookieContainer>(), dataApiBaseUrl)));
builder.Services.AddScoped<IDashboardApiClient>(sp =>
new DashboardApiClient(CreateHttpClientWithCookies(sp.GetRequiredService<CookieContainer>(), dataApiBaseUrl)));
builder.Services.AddScoped<IMassDataApiClient>(sp =>
new MassDataApiClient(CreateHttpClientWithCookies(sp.GetRequiredService<CookieContainer>(), dataApiBaseUrl)));
builder.Services.AddScoped<ILayoutApiClient>(sp =>
new LayoutApiClient(CreateHttpClientWithCookies(sp.GetRequiredService<CookieContainer>(), dataApiBaseUrl)));
var app = builder.Build();

View File

@@ -0,0 +1,64 @@
using System.Net;
namespace DbFirst.BlazorWebApp.Services;
public class AuthApiClient(HttpClient httpClient, AuthService authService, CookieContainer cookieContainer) : IAuthApiClient
{
private const string LoginEndpoint = "api/Auth/db-first/login";
private const string LogoutEndpoint = "api/Auth/logout";
private const string CheckEndpoint = "api/Auth/check";
public async Task<bool> LoginAsync(string username, string password, CancellationToken ct = default)
{
var content = new MultipartFormDataContent();
content.Add(new StringContent(username), "Username");
content.Add(new StringContent(password), "Password");
content.Add(new StringContent(string.Empty), "UserId");
var response = await httpClient.PostAsync(LoginEndpoint, content, ct);
if (!response.IsSuccessStatusCode)
return false;
var rawCookie = ExtractCookies();
authService.SetAuthenticated(username, rawCookie);
return true;
}
public async Task LogoutAsync(CancellationToken ct = default)
{
await httpClient.PostAsync(LogoutEndpoint, null, ct);
authService.SetUnauthenticated();
}
public async Task<bool> RestoreAsync(string username, string rawCookieHeader, CancellationToken ct = default)
{
RestoreCookies(rawCookieHeader);
var response = await httpClient.GetAsync(CheckEndpoint, ct);
if (response.IsSuccessStatusCode)
{
authService.SetAuthenticated(username, rawCookieHeader);
return true;
}
authService.SetUnauthenticated();
return false;
}
private string ExtractCookies()
{
if (httpClient.BaseAddress is null) return string.Empty;
var cookies = cookieContainer.GetCookies(httpClient.BaseAddress);
return string.Join("; ", cookies.Cast<Cookie>().Select(c => $"{c.Name}={c.Value}"));
}
private void RestoreCookies(string rawCookieHeader)
{
if (httpClient.BaseAddress is null) return;
foreach (var part in rawCookieHeader.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
var eqIdx = part.IndexOf('=');
if (eqIdx > 0)
cookieContainer.Add(httpClient.BaseAddress, new Cookie(part[..eqIdx].Trim(), part[(eqIdx + 1)..].Trim()));
}
}
}

View File

@@ -0,0 +1,26 @@
namespace DbFirst.BlazorWebApp.Services;
public class AuthService
{
public bool IsAuthenticated { get; private set; }
public string UserName { get; private set; } = string.Empty;
public string? RawCookieHeader { get; private set; }
public event Action? OnChange;
public void SetAuthenticated(string userName, string rawCookieHeader)
{
IsAuthenticated = true;
UserName = userName;
RawCookieHeader = rawCookieHeader;
OnChange?.Invoke();
}
public void SetUnauthenticated()
{
IsAuthenticated = false;
UserName = string.Empty;
RawCookieHeader = null;
OnChange?.Invoke();
}
}

View File

@@ -0,0 +1,8 @@
namespace DbFirst.BlazorWebApp.Services;
public interface IAuthApiClient
{
Task<bool> LoginAsync(string username, string password, CancellationToken ct = default);
Task LogoutAsync(CancellationToken ct = default);
Task<bool> RestoreAsync(string username, string rawCookieHeader, CancellationToken ct = default);
}

View File

@@ -5,7 +5,8 @@
"Microsoft.AspNetCore": "Warning"
}
},
"ApiBaseUrl": "https://localhost:7204/",
"ApiBaseUrl": "http://172.24.12.39:9090/",
"DataApiBaseUrl": "https://localhost:7204/",
"BrowserLink": {
"Enabled": false
},

View File

@@ -5,6 +5,7 @@
"Microsoft.AspNetCore": "Warning"
}
},
"ApiBaseUrl": "https://localhost:7204/",
"ApiBaseUrl": "http://172.24.12.39:9090/",
"DataApiBaseUrl": "https://localhost:7204/",
"AllowedHosts": "*"
}

View File

@@ -294,4 +294,10 @@ html.dx-dark .dxbl-grid > .dxbl-grid-top-panel {
.top-row .btn-gap {
margin-left: 8px;
}
.top-row-username {
font-size: 0.85rem;
color: #6c757d;
white-space: nowrap;
}