using System.Globalization; using System.Net; using Helpdesk.Web.Api; using Helpdesk.Web.Auth; using Helpdesk.Web.Infrastructure; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews(options => { // Všechny stránky vyžadují přihlášení, výjimky jsou označené [AllowAnonymous]. options.Filters.Add(new AuthorizeFilter()); // Anti-forgery token u všech formulářů odesílaných metodou POST (CSRF, kap. 10). options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); options.Filters.Add(); }); // Klient REST API. Web nemá přístup k databázi – všechna data jdou přes API (kap. 9.4). builder.Services.AddOptions() .BindConfiguration(ApiOptions.Section) .Validate(o => Uri.TryCreate(o.BaseUrl, UriKind.Absolute, out _), "Nastavte Api:BaseUrl na adresu backendu, např. http://api:8080/.") .ValidateOnStart(); static void ConfigureApiClient(IServiceProvider services, HttpClient http) { var options = services.GetRequiredService>().Value; http.BaseAddress = options.VersionedBaseAddress(); http.Timeout = options.Timeout; } builder.Services.AddHttpContextAccessor(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddHttpClient(ConfigureApiClient) .AddHttpMessageHandler(); builder.Services.AddHttpClient(ConfigureApiClient) .AddHttpMessageHandler() .AddHttpMessageHandler(); // Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie. builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = AuthCookie.Name; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Lax; options.Cookie.SecurePolicy = builder.Environment.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; options.LoginPath = "/login"; options.LogoutPath = "/logout"; options.AccessDeniedPath = "/error/403"; // Cookie nepřežije refresh token (14 dní); po jeho vypršení se uživatel přihlásí znovu. options.ExpireTimeSpan = TimeSpan.FromDays(14); options.SlidingExpiration = false; options.EventsType = typeof(HelpdeskCookieEvents); }); // Klíče Data Protection šifrují autentizační cookie. Bez uložení na volume by // restart kontejneru odhlásil všechny uživatele (kap. 15.3). var dataProtection = builder.Services.AddDataProtection().SetApplicationName("Helpdesk.Web"); var keysPath = builder.Configuration["DataProtection:KeysPath"]; if (!string.IsNullOrWhiteSpace(keysPath)) dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath)); var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"]; if (!string.IsNullOrWhiteSpace(trustedProxy)) { if (!IPAddress.TryParse(trustedProxy, out var proxyAddress)) throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy."); builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownIPNetworks.Clear(); options.KnownProxies.Clear(); options.KnownProxies.Add(proxyAddress); }); } var app = builder.Build(); if (!string.IsNullOrWhiteSpace(trustedProxy)) app.UseForwardedHeaders(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error"); app.UseHsts(); } app.UseStatusCodePagesWithReExecute("/error/{0}"); app.UseSecurityHeaders(); var czech = new CultureInfo("cs-CZ"); app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(czech), SupportedCultures = [czech], SupportedUICultures = [czech], }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapSwaggerUI("swagger", options => { options.SwaggerEndpoint("v1/swagger.json", "Helpdesk API v1"); options.DocumentTitle = "Helpdesk API"; options.CacheLifetime = null; }).RequireAuthorization(policy => policy.RequireRole(UserRoles.Admin)); app.MapStaticAssets(); app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets(); app.Run(); /// Vstupní bod – veřejný kvůli testům (WebApplicationFactory). public partial class Program;