| | | 1 | | using Microsoft.Net.Http.Headers; |
| | | 2 | | |
| | | 3 | | namespace Anichron.API.Infrastructure; |
| | | 4 | | |
| | | 5 | | public static class SecurityHeaders |
| | | 6 | | { |
| | | 7 | | private const string appPolicy = |
| | | 8 | | "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; media-src 'self' blob:; " |
| | | 9 | | + "connect-src 'self'; worker-src 'self'; manifest-src 'self'; font-src 'self'; object-src 'none'; base-uri 'non |
| | | 10 | | + "form-action 'self'; frame-ancestors 'none'; require-trusted-types-for 'script'"; |
| | | 11 | | |
| | | 12 | | private const string apiPolicy = "frame-ancestors 'none'"; |
| | | 13 | | |
| | | 14 | | private const string appPermissions = |
| | | 15 | | "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"; |
| | | 16 | | |
| | | 17 | | extension(WebApplication app) |
| | | 18 | | { |
| | | 19 | | public WebApplication UseSecurityHeaders() |
| | 12 | 20 | | { |
| | 12 | 21 | | app.Use((context, next) => |
| | 12 | 22 | | { |
| | 12 | 23 | | context.Response.OnStarting(() => |
| | 12 | 24 | | { |
| | 12 | 25 | | Apply(context); |
| | 12 | 26 | | return Task.CompletedTask; |
| | 12 | 27 | | }); |
| | 12 | 28 | | return next(context); |
| | 12 | 29 | | }); |
| | 12 | 30 | | return app; |
| | | 31 | | } |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | private static void Apply(HttpContext context) |
| | 11 | 35 | | { |
| | 11 | 36 | | var headers = context.Response.Headers; |
| | 11 | 37 | | headers[HeaderNames.XContentTypeOptions] = "nosniff"; |
| | 11 | 38 | | if (ApiPaths.IsApi(context.Request.Path)) |
| | 4 | 39 | | { |
| | 4 | 40 | | headers[HeaderNames.ContentSecurityPolicy] = apiPolicy; |
| | 4 | 41 | | return; |
| | | 42 | | } |
| | | 43 | | |
| | 7 | 44 | | headers[HeaderNames.ContentSecurityPolicy] = appPolicy; |
| | 7 | 45 | | headers["Referrer-Policy"] = "same-origin"; |
| | 7 | 46 | | headers["Permissions-Policy"] = appPermissions; |
| | 11 | 47 | | } |
| | | 48 | | } |