| | | 1 | | using Microsoft.AspNetCore.Builder; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using OzonOrdersWeb.Middleware; |
| | | 6 | | |
| | | 7 | | namespace OzonOrdersWeb.Extensions; |
| | | 8 | | |
| | | 9 | | public static class SecurityExtensions |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Добавляет сервисы безопасности |
| | | 13 | | /// </summary> |
| | | 14 | | public static IServiceCollection AddSecurityServices(this IServiceCollection services, bool isProd) |
| | | 15 | | { |
| | | 16 | | // Настройка HSTS (HTTP Strict Transport Security) |
| | 0 | 17 | | services.AddHsts(options => |
| | 0 | 18 | | { |
| | 0 | 19 | | options.Preload = true; |
| | 0 | 20 | | options.IncludeSubDomains = true; |
| | 0 | 21 | | options.MaxAge = TimeSpan.FromDays(365); // 1 год |
| | 0 | 22 | | }); |
| | | 23 | | |
| | | 24 | | // Настройка Cookie безопасности |
| | 0 | 25 | | services.ConfigureApplicationCookie(options => |
| | 0 | 26 | | { |
| | 0 | 27 | | options.Cookie.HttpOnly = true; // Защита от XSS |
| | 0 | 28 | | options.Cookie.SecurePolicy = isProd |
| | 0 | 29 | | ? CookieSecurePolicy.Always // В production только HTTPS |
| | 0 | 30 | | : CookieSecurePolicy.SameAsRequest; // В development разрешаем HTTP |
| | 0 | 31 | | options.Cookie.SameSite = SameSiteMode.Strict; // Защита от CSRF |
| | 0 | 32 | | options.SlidingExpiration = true; // Обновление срока действия |
| | 0 | 33 | | options.ExpireTimeSpan = TimeSpan.FromHours(8); // Срок действия 8 часов |
| | 0 | 34 | | }); |
| | | 35 | | |
| | | 36 | | // Настройка Session Cookie |
| | 0 | 37 | | services.AddSession(options => |
| | 0 | 38 | | { |
| | 0 | 39 | | options.Cookie.HttpOnly = true; |
| | 0 | 40 | | options.Cookie.SecurePolicy = isProd |
| | 0 | 41 | | ? CookieSecurePolicy.Always |
| | 0 | 42 | | : CookieSecurePolicy.SameAsRequest; |
| | 0 | 43 | | options.Cookie.SameSite = SameSiteMode.Strict; |
| | 0 | 44 | | options.IdleTimeout = TimeSpan.FromMinutes(30); |
| | 0 | 45 | | options.Cookie.IsEssential = true; |
| | 0 | 46 | | }); |
| | | 47 | | |
| | 0 | 48 | | return services; |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Настраивает middleware безопасности |
| | | 53 | | /// </summary> |
| | | 54 | | public static IApplicationBuilder UseSecurityMiddleware(this IApplicationBuilder app, bool isProd) |
| | | 55 | | { |
| | | 56 | | // HSTS должен быть первым |
| | 0 | 57 | | if (isProd) |
| | | 58 | | { |
| | 0 | 59 | | app.UseHsts(); |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | // Security Headers Middleware |
| | 0 | 63 | | app.UseMiddleware<SecurityHeadersMiddleware>(); |
| | | 64 | | |
| | 0 | 65 | | return app; |
| | | 66 | | } |
| | | 67 | | } |