46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using EnvelopeGenerator.ReceiverUI.Client.Services;
|
|
|
|
namespace EnvelopeGenerator.ReceiverUI.Client.Auth;
|
|
|
|
/// <summary>
|
|
/// Fragt die API, ob der Nutzer eingeloggt ist.
|
|
///
|
|
/// WARUM nicht selbst Token lesen?
|
|
/// - Das Auth-Cookie ist HttpOnly → JavaScript/WASM kann es nicht lesen
|
|
/// - Stattdessen: Frage die API "bin ich eingeloggt?" → GET /api/auth/check
|
|
/// - Die API prüft das Cookie serverseitig und antwortet mit 200 oder 401
|
|
/// </summary>
|
|
public class ApiAuthStateProvider : AuthenticationStateProvider
|
|
{
|
|
private readonly IAuthService _authService;
|
|
|
|
public ApiAuthStateProvider(IAuthService authService)
|
|
{
|
|
_authService = authService;
|
|
}
|
|
|
|
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
var result = await _authService.CheckAuthAsync();
|
|
|
|
if (result.IsSuccess)
|
|
{
|
|
// Eingeloggt → Erstelle einen authentifizierten ClaimsPrincipal
|
|
var identity = new ClaimsIdentity("cookie");
|
|
return new AuthenticationState(new ClaimsPrincipal(identity));
|
|
}
|
|
|
|
// Nicht eingeloggt
|
|
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Wird nach Login/Logout aufgerufen, damit Blazor den Auth-State aktualisiert.
|
|
/// </summary>
|
|
public void NotifyAuthChanged()
|
|
{
|
|
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
|
}
|
|
} |