{"id":13431581,"url":"https://github.com/juunas11/aspnetcore-security-headers","last_synced_at":"2025-03-16T12:30:41.383Z","repository":{"id":38816615,"uuid":"79739234","full_name":"juunas11/aspnetcore-security-headers","owner":"juunas11","description":"Middleware for adding security headers to an ASP.NET Core application.","archived":false,"fork":false,"pushed_at":"2023-11-14T12:30:03.000Z","size":681,"stargazers_count":268,"open_issues_count":36,"forks_count":44,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-02-22T10:02:39.345Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/juunas11.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-01-22T19:17:46.000Z","updated_at":"2025-01-11T23:14:19.000Z","dependencies_parsed_at":"2024-01-05T21:03:07.499Z","dependency_job_id":null,"html_url":"https://github.com/juunas11/aspnetcore-security-headers","commit_stats":{"total_commits":69,"total_committers":14,"mean_commits":4.928571428571429,"dds":0.6956521739130435,"last_synced_commit":"4290c91b2fdebbe1c116ec43a3c8f5e1ed6629d4"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juunas11%2Faspnetcore-security-headers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juunas11%2Faspnetcore-security-headers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juunas11%2Faspnetcore-security-headers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/juunas11%2Faspnetcore-security-headers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/juunas11","download_url":"https://codeload.github.com/juunas11/aspnetcore-security-headers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243869178,"owners_count":20360967,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T02:01:04.252Z","updated_at":"2025-03-16T12:30:41.026Z","avatar_url":"https://github.com/juunas11.png","language":"C#","funding_links":[],"categories":["Frameworks, Libraries and Tools","C# #","C\\#","框架, 库和工具","Libraries"],"sub_categories":["Security","安全"],"readme":"# Add CSP, HSTS or HPKP headers to an ASP.NET Core app\n\nThis library allows you to add Content Security Policy, Strict Transport Security and Public Key Pin headers via middleware.\n\nYou can get the library from NuGet: [https://www.nuget.org/packages/Joonasw.AspNetCore.SecurityHeaders](https://www.nuget.org/packages/Joonasw.AspNetCore.SecurityHeaders)\n\n## Example configuration\n\n```cs\n// Enable Strict Transport Security with a 30-day caching period\n// Do not include subdomains\n// Do not allow preload\napp.UseStrictTransportSecurity(new HstsOptions(TimeSpan.FromDays(30), includeSubDomains: false, preload: false));\n\n// Use certificate pinning with:\n// - 30-day caching period\n// - One pin in SHA-256 form\n// - Report-Only = Invalid certificate should not be reported, but:\n// - Report problems to /hpkp-report\napp.UseHpkp(hpkp =\u003e\n{\n    hpkp.UseMaxAgeSeconds(30 * 24 * 60 * 60)\n        .AddSha256Pin(\"nrmpk4ZI3wbRBmUZIT5aKAgP0LlKHRgfA2Snjzeg9iY=\")\n        .SetReportOnly()\n        .ReportViolationsTo(\"/hpkp-report\");\n});\n\n// Content Security Policy\napp.UseCsp(csp =\u003e\n{\n    // If nothing is mentioned for a resource class, allow from this domain\n    csp.ByDefaultAllow\n        .FromSelf();\n\n    // Allow JavaScript from:\n    csp.AllowScripts\n        .FromSelf() //This domain\n        .From(\"localhost:1591\") //These two domains\n        .From(\"ajax.aspnetcdn.com\");\n\n    // CSS allowed from:\n    csp.AllowStyles\n        .FromSelf()\n        .From(\"ajax.aspnetcdn.com\");\n\n    csp.AllowImages\n        .FromSelf();\n\n    // HTML5 audio and video elemented sources can be from:\n    csp.AllowAudioAndVideo\n        .FromNowhere();\n\n    // Contained iframes can be sourced from:\n    csp.AllowFrames\n        .FromNowhere(); //Nowhere, no iframes allowed\n\n    // Allow AJAX, WebSocket and EventSource connections to:\n    csp.AllowConnections\n        .To(\"ws://localhost:1591\")\n        .To(\"http://localhost:1591\")\n        .ToSelf();\n\n    // Allow fonts to be downloaded from:\n    csp.AllowFonts\n        .FromSelf()\n        .From(\"ajax.aspnetcdn.com\");\n\n    // Allow object, embed, and applet sources from:\n    csp.AllowPlugins\n        .FromNowhere();\n\n    // Allow other sites to put this in an iframe?\n    csp.AllowFraming\n        .FromNowhere(); // Block framing on other sites, equivalent to X-Frame-Options: DENY\n\n    // Do not block violations, only report\n    // This is a good idea while testing your CSP\n    // Remove it when you know everything will work\n    csp.SetReportOnly();\n    // Where should the violation reports be sent to?\n    csp.ReportViolationsTo(\"/csp-report\");\n\n    // Do not include the CSP header for requests to the /api endpoints\n    csp.OnSendingHeader = context =\u003e\n    {\n        context.ShouldNotSend = context.HttpContext.Request.Path.StartsWithSegments(\"/api\");\n        return Task.CompletedTask;\n    };\n});\n```\n\nContent Security Policy can be quite daunting. Here is a nice page to find out what the options do: [https://content-security-policy.com/](https://content-security-policy.com/.)\n\nFor violation reports, I recommend using Scott Helme's Report URI service at [https://report-uri.io/](https://report-uri.io/).\n\n## Nonces\n\nCSP allows you to also specify a nonce value, which makes it easier to have inline script and style elements like this on a page:\n\n```html\n\u003chead\u003e\n  \u003cscript\u003e\n    console.log(\"Hello\");\n  \u003c/script\u003e\n  \u003cstyle\u003e\n    h1 {\n      color: red;\n    }\n  \u003c/style\u003e\n\u003c/head\u003e\n```\n\nTo allow them without nonces, you might have to use the unsafe-inline option.\n\nInstead of doing that, we can add the following service in `Startup`:\n\n```cs\npublic void ConfigureServices(IServiceCollection services)\n{\n    // ... other service registrations\n\n    // Add services necessary for nonces in CSP, 32-byte nonces\n    services.AddCsp(nonceByteAmount: 32);\n}\n```\n\nThen you need to modify your CSP definition to include the nonce:\n\n```cs\ncsp.AllowScripts\n    .FromSelf()\n    .From(\"localhost:1591\")\n    .From(\"ajax.aspnetcdn.com\")\n    .AddNonce(); //\u003c----\n\ncsp.AllowStyles\n    .FromSelf()\n    .From(\"ajax.aspnetcdn.com\")\n    .AddNonce(); //\u003c-----\n```\n\nThen to use the nonce tag helper, we need to import it in *_ViewImports.cshtml*:\n\n```c#\n@addTagHelper *, Joonasw.AspNetCore.SecurityHeaders\n```\n\nThen we just need to use it in the Razor view:\n\n```html\n\u003chead\u003e\n  \u003cscript asp-add-nonce=\"true\"\u003e\n    console.log(\"Hello\");\n  \u003c/script\u003e\n  \u003cstyle asp-add-nonce=\"true\"\u003e\n    h1 {\n      color: red;\n    }\n  \u003c/style\u003e\n\u003c/head\u003e\n```\n\nNow a unique nonce is generated every request and inserted into the CSP header + the elements you want.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjuunas11%2Faspnetcore-security-headers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjuunas11%2Faspnetcore-security-headers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjuunas11%2Faspnetcore-security-headers/lists"}