Files
NTBug/web/Helpdesk.Web/Program.cs
T

132 lines
5.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<ApiExceptionFilter>();
});
// Klient REST API. Web nemá přístup k databázi – všechna data jdou přes API (kap. 9.4).
builder.Services.AddOptions<ApiOptions>()
.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<IOptions<ApiOptions>>().Value;
http.BaseAddress = options.VersionedBaseAddress();
http.Timeout = options.Timeout;
}
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<BearerTokenHandler>();
builder.Services.AddTransient<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>()
.AddHttpMessageHandler<BearerTokenHandler>();
// 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<TokenRefresher>();
builder.Services.AddScoped<HelpdeskCookieEvents>();
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<ForwardedHeadersOptions>(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();
/// <summary>Vstupní bod – veřejný kvůli testům (WebApplicationFactory).</summary>
public partial class Program;