This example demonstrates how to implement a nonce-based Content Security Policy (CSP) for an ASP.NET Core Application with Razor Pages through a HTTP response header.
Use the nonce-based approach to disallow inline script and style execution.
In a page model (DashboardModel.cs), generate the nonce value. In this example, the RandomNumberGenerator class is used to generate cryptographically strong random values.
using System.Security.Cryptography;
//...
public string Nonce { get; set; }
public DashboardModel() {
var nonceBytes = new byte[32];
var generator = RandomNumberGenerator.Create();
generator.GetBytes(nonceBytes);
Nonce = Convert.ToBase64String(nonceBytes);
}
In the OnGet
handler method, add a HTTP header with the Content Security Policy with the nonce for script-src
and style-src
directives:
public IActionResult OnGet() {
HttpContext.Response.Headers.Add("Content-Security-Policy",
"img-src data: https: http:;" +
string.Format("script-src 'self' 'nonce-{0}';", Nonce) +
string.Format("style-src 'self' 'nonce-{0}';", Nonce)
);
return Page();
}
The new nonce value is generated each time the page loads.
On the page (Index.cshtml), add the @model
directive and pass the nonce value to Nonce
method:
@page
@model CSPDashboardExample.Models.DashboardModel
<div class="my-dashboard-container">
@(Html.DevExpress().Dashboard("dashboardControl1")
.ControllerName("DefaultDashboard")
.Nonce(Model.Nonce)
.Width(null)
.Height(null)
.OnBeforeRender("onBeforeRender")
)
</div>
(you will be redirected to DevExpress.com to submit your response)