To implement Content Security Policy (CSP) in C# using ASP.NET Core, you can add the appropriate CSP header to the HTTP response in the Startup.cs
file. Below is an example of how to set the CSP header using a custom middleware in the Configure
method of Startup.cs
.
- First, install the
Microsoft.AspNetCore.Http
package if you haven’t already:
Install-Package Microsoft.AspNetCore.Http
In your Startup.cs
file, add the following code:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace YourAppName
{
public class Startup
{
// ... Other configuration code ...
public void ConfigureServices(IServiceCollection services)
{
// ... Other services registration ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... Other middleware configurations ...
// Add custom middleware for setting CSP header
app.Use(async (context, next) =>
{
// Define the CSP header with your desired policy
string cspDirective = "default-src 'self'; script-src 'self' trusted-scripts.example.com;";
// Set the Content-Security-Policy header
context.Response.Headers.Add("Content-Security-Policy", cspDirective);
// Call the next middleware in the pipeline
await next();
});
// ... Other middleware configurations ...
}
}
}
In the code above, we added a custom middleware that sets the Content-Security-Policy
header on the HTTP response. You can customize the cspDirective
variable to include your desired CSP policy. The example provided allows scripts only from the same origin ('self'
) and from the domain trusted-scripts.example.com
.
Keep in mind that this is a basic example, and you may want to adjust the CSP policy to fit your specific needs. Additionally, you should thoroughly test your application to ensure that the CSP policy does not interfere with the proper functioning of your website.