fix(web): add cookie authentication to fix IAuthenticationService missing error
This commit is contained in:
1 parent
f5c4bcd5f0
commit
39f08e39ed
6 files changed
+142
-3
No files matched your search
@@ -1,6 +1,8 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Web.Components;
|
||||
using Heimdall.Web.Services;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using MudBlazor.Services;
|
||||
|
||||
@@ -22,11 +24,32 @@ builder.WebHost.UseSentry(options =>
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// Auth for Blazor
|
||||
builder.Services.AddScoped<AuthenticationStateProvider, HeimdallAuthStateProvider>();
|
||||
// ── Authentication (Microsoft Identity pattern: cookie auth) ──────
|
||||
// The app uses JWT auth via the Heimdall API at the application level.
|
||||
// At the ASP.NET Core middleware level, we use cookie authentication
|
||||
// to persist the user session across requests.
|
||||
// The cookie is created after successful API login (see /_auth/signin).
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.LoginPath = "/login";
|
||||
options.LogoutPath = "/_auth/signout";
|
||||
options.AccessDeniedPath = "/not-found";
|
||||
options.Cookie.Name = ".Heimdall.Auth";
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorizationCore();
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
|
||||
// Blazor auth state provider (reads JWT from ProtectedLocalStorage)
|
||||
builder.Services.AddScoped<AuthenticationStateProvider, HeimdallAuthStateProvider>();
|
||||
|
||||
// ── MudBlazor ─────────────────────────────────────────────────────
|
||||
builder.Services.AddMudServices(config =>
|
||||
{
|
||||
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
||||
@@ -35,6 +58,7 @@ builder.Services.AddMudServices(config =>
|
||||
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
||||
});
|
||||
|
||||
// ── HTTP client for Heimdall API ──────────────────────────────────
|
||||
builder.Services.AddScoped<HeimdallApiClient>();
|
||||
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
|
||||
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
||||
@@ -45,11 +69,12 @@ builder.Services.AddHttpClient("HeimdallApi", client =>
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
});
|
||||
|
||||
// Auth state
|
||||
// Auth state (shared between services and components)
|
||||
builder.Services.AddScoped<AuthState>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// ── Middleware pipeline ────────────────────────────────────────────
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||||
@@ -60,7 +85,54 @@ app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages:
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAntiforgery();
|
||||
app.MapStaticAssets();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
|
||||
// /_auth/signin — Creates an authentication cookie after successful API login
|
||||
// /_auth/signout — Clears the authentication cookie on logout
|
||||
|
||||
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request) =>
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.Id) || string.IsNullOrEmpty(request.Email))
|
||||
return Results.BadRequest(new { error = "Id and Email are required" });
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, request.Id),
|
||||
new(ClaimTypes.Email, request.Email),
|
||||
new(ClaimTypes.Name, request.DisplayName ?? request.Email),
|
||||
};
|
||||
|
||||
if (request.Roles is not null)
|
||||
{
|
||||
foreach (var role in request.Roles)
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
|
||||
return Results.Ok();
|
||||
});
|
||||
|
||||
app.MapPost("/_auth/signout", async (HttpContext httpContext) =>
|
||||
{
|
||||
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return Results.Ok();
|
||||
});
|
||||
|
||||
app.Run();
|
||||
|
||||
// ─── DTO for the cookie sign-in request ───────────────────────────
|
||||
|
||||
internal sealed record SignInRequest(
|
||||
string Id,
|
||||
string Email,
|
||||
string? DisplayName,
|
||||
IList<string>? Roles);
|
||||
Reference in new issue
Block a user