{"id":19407612,"url":"https://github.com/brickmakersgmbh/aspsecurityheaders","last_synced_at":"2025-04-24T09:31:42.035Z","repository":{"id":64447485,"uuid":"450541900","full_name":"BrickmakersGmbH/AspSecurityHeaders","owner":"BrickmakersGmbH","description":"A small package for ASP.Net (Core) to automatically configure secure HTTP-Headers","archived":false,"fork":false,"pushed_at":"2025-04-14T23:08:37.000Z","size":2196,"stargazers_count":16,"open_issues_count":5,"forks_count":0,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-04-15T00:23:05.976Z","etag":null,"topics":["asp-net","asp-net-core","brickmakers","csharp","csp","dotnet","dotnet-core","hsts","http-headers","https","security","security-headers"],"latest_commit_sha":null,"homepage":"","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/BrickmakersGmbH.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-01-21T15:25:26.000Z","updated_at":"2025-04-14T23:08:34.000Z","dependencies_parsed_at":"2023-10-03T04:12:43.908Z","dependency_job_id":"115e3472-6119-4a63-989d-be1c3060f386","html_url":"https://github.com/BrickmakersGmbH/AspSecurityHeaders","commit_stats":{"total_commits":252,"total_committers":2,"mean_commits":126.0,"dds":"0.39682539682539686","last_synced_commit":"bc0a72ff8dde5c9770dce82a7cd32783a360ed13"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BrickmakersGmbH%2FAspSecurityHeaders","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BrickmakersGmbH%2FAspSecurityHeaders/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BrickmakersGmbH%2FAspSecurityHeaders/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BrickmakersGmbH%2FAspSecurityHeaders/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BrickmakersGmbH","download_url":"https://codeload.github.com/BrickmakersGmbH/AspSecurityHeaders/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250600712,"owners_count":21457015,"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":["asp-net","asp-net-core","brickmakers","csharp","csp","dotnet","dotnet-core","hsts","http-headers","https","security","security-headers"],"created_at":"2024-11-10T12:03:11.280Z","updated_at":"2025-04-24T09:31:41.745Z","avatar_url":"https://github.com/BrickmakersGmbH.png","language":"C#","readme":"# BRICKMAKERS ASP.Net Security Headers\r\n\r\n[![License](https://img.shields.io/github/license/BrickmakersGmbH/AspSecurityHeaders)](https://github.com/BrickmakersGmbH/AspSecurityHeaders/blob/main/LICENSE.txt)\r\n[![CI-Pipeline](https://github.com/BrickmakersGmbH/AspSecurityHeaders/actions/workflows/ci.yml/badge.svg)](https://github.com/BrickmakersGmbH/AspSecurityHeaders/actions/workflows/ci.yml)\r\n[![Brickmakers.AspSecurityHeaders Nuget Version](https://img.shields.io/nuget/v/Brickmakers.AspSecurityHeaders?label=Brickmakers.AspSecurityHeaders)](https://www.nuget.org/packages/Brickmakers.AspSecurityHeaders)\r\n[![Brickmakers.AspSecurityHeaders.OrchardModule Nuget Version](https://img.shields.io/nuget/v/Brickmakers.AspSecurityHeaders.OrchardModule?label=Brickmakers.AspSecurityHeaders.OrchardModule)](https://www.nuget.org/packages/Brickmakers.AspSecurityHeaders.OrchardModule)\r\n[![Brickmakers.AspSecurityHeaders.Generators Nuget Version](https://img.shields.io/nuget/v/Brickmakers.AspSecurityHeaders.Generators?label=Brickmakers.AspSecurityHeaders.Generators)](https://www.nuget.org/packages/Brickmakers.AspSecurityHeaders.Generators)\r\n\r\nA small package for ASP.Net (Core) to automatically configure secure HTTP-Headers.\r\n\r\n## Table of Contents\r\n\r\n- [IMPORTANT CHANGES in version 2.1.0](#important-changes-in-version-210)\r\n- [Features](#features)\r\n- [Installation](#installation)\r\n- [Usage](#usage)\r\n    * [AspSecurityHeaders](#aspsecurityheaders)\r\n        + [Using the Built-In CSP Report Controller](#using-the-built-in-csp-report-controller)\r\n    * [Orchard Module](#orchard-module)\r\n        + [Overwriting the Orchard CSP](#overwriting-the-orchard-csp)\r\n        + [Support for Login with Microsoft/Azure AD](#support-for-login-with-microsoft-azure-ad)\r\n    * [Generators](#generators)\r\n        + [IIS web.config](#iis-webconfig)\r\n- [Attributions and Background](#attributions-and-background)\r\n\r\n\u003csmall\u003e\u003ci\u003e\u003ca href='https://ecotrust-canada.github.io/markdown-toc/'\u003eTable of contents generated with\r\nmarkdown-toc\u003c/a\u003e\u003c/i\u003e\u003c/small\u003e\r\n\r\n## IMPORTANT CHANGES in version 2.1.0\r\n\r\nIn 2.1.0, support for strict site isolation has been added and enabled. Check the release notes for more details.\r\n\r\n## Features\r\n\r\n- Secure defaults for HTTP-Headers, CSP, Cookies and more\r\n- Opt-Out mechanism for different security controls\r\n- Easily configurable via `IApplicationBuilder.UseBmSecurityHeaders()` extension\r\n    - Or use `IApplicationBuilder.UseBmApiSecurityHeaders()` for API-Projects\r\n- Developed and Maintained by the BRICKMAKERS Security Advisory Team\r\n    - Based on the widely\r\n      used [NetEscapades.AspNetCore.SecurityHeaders](https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders)\r\n- Easy integration in any project and build pipelines\r\n- Provides additional generator package to create config files with security headers for:\r\n    - IIS `web.config` files\r\n\r\n## Installation\r\n\r\nThis package is available on NuGet.org, you can simply add it to your C#-Project like any other dependency.\r\n\r\n- Main Package: [Brickmakers.AspSecurityHeaders](https://www.nuget.org/packages/Brickmakers.AspSecurityHeaders/)\r\n- Generators\r\n  Package: [Brickmakers.AspSecurityHeaders.Generators](https://www.nuget.org/packages/Brickmakers.AspSecurityHeaders.Generators/)\r\n\r\n## Usage\r\n\r\n### AspSecurityHeaders\r\n\r\nFor the standard features of the Security Headers you only need to install `Brickmakers.AspSecurityHeaders`.\r\n\r\nTo get started, all you have to to is to register the middleware in the `Configure` method. This should happen **at the\r\nbeginning** of the method to ensure the headers are added to all responses, as different middlewares might end\r\nprocessing early, which would prevent the headers from being set:\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    // ! Should be the first step in the Configure method\r\n\r\n    // For \"normal\" Websites or combinations of Websites and APIs\r\n    app.UseBmSecurityHeaders();\r\n\r\n    // For pure APIs\r\n    app.UseBmApiSecurityHeaders();\r\n\r\n    // continue as usual with configuring the application\r\n    // ...\r\n}\r\n```\r\n\r\nThis will add *all* security headers, as well as a strict CSP and cookie policy. To further configure it and opt out of\r\ncertain security controls, you can use the `configure` parameter of the method. In the following example, scripts,\r\nstyles and images are allowed to be loaded from the current origin and the minimum cookie same site requirements are\r\nreduced to be lax instead of strict.\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    app.UseBmSecurityHeaders(collection =\u003e collection  // Or .UseBmApiSecurityHeaders for APIs\r\n        .AddBmContentSecurityPolicy(builder =\u003e\r\n        {\r\n            builder.AddScriptSrc().Self();\r\n            builder.AddStyleSrc().Self();\r\n            builder.AddImgSrc().Self();\r\n        })\r\n        .SetMinimumSameSitePolicy(SameSiteMode.Lax));\r\n\r\n    // ...\r\n}\r\n```\r\n\r\n#### Using the Built-In CSP Report Controller\r\n\r\nThe library includes a ready-made API-Controller to automatically report CSP-Violations. It will provide an endpoint to\r\nbe used by the browser to report CSP errors and passes them to a customizable handler function. If you want to use the\r\ncontroller, there are a few steps that need to be taken.\r\n\r\nFirst, you have to add the controller to your controllers by extending the `CspReportControllerBase`:\r\n\r\n```cs\r\n[ApiController]\r\n[Route(\"[controller]\")]\r\npublic class CspReportController : CspReportControllerBase\r\n{\r\n    protected override Task HandleCspReport(CspReport cspReport)\r\n    {\r\n        // Implement logging or other handling here\r\n        // IMPORTANT: If you log the report values, you should sanitized them to prevent log forgery attacks\r\n        // See: https://owasp.org/www-community/attacks/Log_Injection\r\n        \r\n        return Task.CompletedTask;\r\n    }\r\n}\r\n```\r\n\r\nIf you are using the standard `Microsoft.Extensions.Logging.ILogger` for logging, you can use a handy extension method\r\non the logger that automatically handles formatting and also logs the properties of the report in case you are using\r\na structured logging backend like App Insights.\r\n\r\n```cs\r\n[ApiController]\r\n[Route(\"[controller]\")]\r\npublic class CspReportController : CspReportControllerBase\r\n{\r\n    protected override Task HandleCspReport(CspReport cspReport)\r\n    {\r\n        _logger.LogCspReport(cspReport); // default log level ist \"Error\", but can be adjusted\r\n        return Task.CompletedTask;\r\n    }\r\n}\r\n```\r\n\r\nNext, you have to add the controller to the MVC instance inside of the `ConfigureServices` method. Typically,\r\nthe `AddMvc` method is used, but you can also use any other of the MVC initializers, like for example `AddControllers`\r\nin case of a pure API. In addition to registering controllers, you also need to add the CSP-Report content type. You can\r\nsimply use the `AddCspMediaType` method for that:\r\n\r\n```cs\r\npublic void ConfigureServices(IServiceCollection services)\r\n{\r\n    services.AddMvc() // works on .AddRazorPages() and .AddControllers() as well\r\n        .AddCspMediaType();\r\n}\r\n```\r\n\r\nIn the case that this is the first controller you add to your project, you also need to ensure that controllers are\r\ncorrectly mapped to endpoints. You can do so via the `UseEndpoints` method at the end of `Configure`:\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\r\n{\r\n    // do your normal setup\r\n    // ...\r\n\r\n    // at the end, UseEndpoints should already exist\r\n    app.UseEndpoints(endpoints =\u003e\r\n    {\r\n        // this one must be present\r\n        endpoints.MapControllers();\r\n        \r\n        // other mappings, e.g. MapRazorPages, depends on your application\r\n        // ...\r\n    });\r\n}\r\n```\r\n\r\nFinally, you need to actually set the report URI in the CSP. This can be done by adding it inside the CSP builder of\r\nthe `UseBmSecurityHeaders` by adding `AddReportUri` to the CSP. There you should set the path to the previously defined\r\nCSP controller. In this example, the controller path was defined as `CspReport`.\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    app.UseBmSecurityHeaders(collection =\u003e collection  // Or .UseBmApiSecurityHeaders for APIs\r\n        .AddBmContentSecurityPolicy(builder =\u003e\r\n        {\r\n            // setup your CSP\r\n            // ...\r\n            \r\n            builder.AddReportUri().To(\"/CspReport\");\r\n        }));\r\n    // ...\r\n}\r\n```\r\n\r\nIn case you also have additional projects that should also report to this controller, or in case you separate API and\r\nweb project, the controller will always be accessible via `https://\u003chost\u003e/CspReport`. You can use it as any other CSP\r\nreporting endpoint.\r\n\r\n### Orchard Module\r\n\r\nIf you are working with [Orchard Core](https://orchardcore.net/), then instead of using the Security Headers package\r\ndirectly, you should instead use the `Brickmakers.AspSecurityHeaders.OrchardModule` package, which itself is an orchard\r\nmodule that automatically configures the security headers for you. To use it, follow the standard Steps to add an\r\nOrchard module as dependency:\r\n\r\n1. Add the NuGet package reference\r\n2. Update your `Manifest.cs` and add `Brickmakers.AspSecurityHeaders.OrchardModule` as dependency\r\n3. Enable MVC in your application `Startup.cs`: `services.AddOrchardCore().AddMvc();`\r\n4. For Orchard CMS installations: Enter the \"Features\" Admin Menu and manually enable the module\r\n\r\nWith the, the module is automatically loaded and activated. It will:\r\n\r\n1. Enable all standard security headers, including a customized CSP\r\n2. Register the CSP report controller under `/CspReport`\r\n\r\nTo customize the security headers, you can basically follow the standard instructions of the normal Security headers\r\npackage, with 2 exceptions: Use `UseOrchardBmSecurityHeaders` and `AddOrchardBmContentSecurityPolicy` instead of their \"\r\nnormal\" counterparts:\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    // ! Should be the first step in the Configure method\r\n\r\n    // Only needed if customization is required\r\n    app.UseOrchardBmSecurityHeaders(config =\u003e config\r\n        .AddOrchardBmContentSecurityPolicy(/* ... */) // csp config\r\n        // ... other configuration, just like with the normal security headers\r\n    );\r\n}\r\n```\r\n\r\n\u003e **Note:** Orchard core is not the most security aware framework. The default CSP that is required to make it work\r\n\u003e includes `unsafe-inline` `unsafe-eval`. Be aware that for a security sensitive application, it should be carefully\r\n\u003e evaluated if orchard core is the right choice, or whether critical components should be provided in a pure ASP.net\r\n\u003e application that allows for tighter security controls and a better CSP.\r\n\r\n#### Overwriting the Orchard CSP\r\n\r\nWhen customizing the Orchard CSP, you can simply add new rules to the existing ones. This will not overwrite the\r\nstandard orchard rules anymore. If you need to disable the standard rules, you can use the optional `clear` parameter.\r\nFor example, if a script source should be added but the image sources should be cleared and replaced, it would look\r\nlike the following:\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    app.UseOrchardBmSecurityHeaders(config =\u003e config\r\n        .AddOrchardBmContentSecurityPolicy(builder =\u003e \r\n        {\r\n            builder.AddScriptSrc() // Adds new diretives\r\n                .From(\"https://example.com\");\r\n            builder.AddImgSrc(clear: true) // Replaces directives (usually not needed)\r\n                .Self()\r\n                .From(\"https://example.com\");\r\n        })\r\n    );\r\n}\r\n```\r\n\r\n#### Support for Login with Microsoft/Azure AD\r\n\r\nIf you want to allow a login with Microsoft in your orchard application, special cookie policy rules need to be added so\r\nthat azure can pass the authentication result back to the orchard application. Additionally, some CSP rules need to be\r\nadjusted, as otherwise your page cannot redirect to microsoft. You can either manually configure the rules via the\r\n`AddCookieOption` and the CSP builder, or use the helper methods that do that for you:\r\n\r\n```cs\r\npublic void Configure(IApplicationBuilder app)\r\n{\r\n    app.UseOrchardBmSecurityHeaders(config =\u003e config\r\n        .AddMicrosoftLoginCookieWhitelist()\r\n        .AddOrchardBmContentSecurityPolicy(cspBuilder =\u003e {\r\n            cspBuilder.AddFormAction()\r\n                .MicrosoftLogin();\r\n        })\r\n    );\r\n}\r\n```\r\n\r\n### Generators\r\n\r\nTo use the generators, you have to install the `Brickmakers.AspSecurityHeaders.Generators` package. The you can use the\r\nvarious writers to generate your configuration.\r\n\r\n#### IIS web.config\r\n\r\nTo generate a web.config file with security headers, you can use the `IISWebConfigWriter` class:\r\n\r\n```cs\r\nawait IISWebConfigWriter.Create() // or .CreateApi()\r\n    .SetBmSecurityHeadersConfig(config =\u003e config\r\n        .AddBmContentSecurityPolicy(builder =\u003e\r\n        {\r\n            builder.AddScriptSrc().Self();\r\n            builder.AddStyleSrc().Self();\r\n            builder.AddImgSrc().Self();\r\n        }))\r\n    .EnforceHttps(false)\r\n    .Run(\"web.config\");\r\n```\r\n\r\nWith the `SetBmSecurityHeadersConfig`, you can configure your security headers in exactly the same way as with the\r\nstandard security headers package. In addition to that, there are also some extra configuration options that are only\r\navailable with web.config files. These are:\r\n\r\n- XML Writer configuration for controlling how the generated XML is formatted\r\n- Advanced removal of server identifying headers\r\n- Enforce HTTPS\r\n- Flags to control if the generated headers should be for HTTP / TLS\r\n\r\n## Attributions and Background\r\n\r\nThis project is heavily based\r\non [NetEscapades.AspNetCore.SecurityHeaders](https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders),\r\nthanks to everyone involved on that project.\r\n\r\nThe reason this package exists is because it enforces even stricter defaults than the original package and adds\r\nadditional features. It has not been integrated into the original security headers, as some of these feature would be\r\nbreaking changes and too strict for some users.\r\n\r\nHowever, we at BRICKMAKERS prefer to use tight secure defaults, which is why we created this package. It will always set\r\neverything to no by default and may add new, even more restricting headers in the future.\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrickmakersgmbh%2Faspsecurityheaders","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrickmakersgmbh%2Faspsecurityheaders","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrickmakersgmbh%2Faspsecurityheaders/lists"}