Skip to content

How to implement a nonce-based Content Security Policy (CSP) for an ASP.NET Core Dashboard Application

License

Notifications You must be signed in to change notification settings

DevExpress-Examples/asp-net-core-dashboard-content-security-policy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BI Dashboard for ASP.NET Core - Content Security Policy (CSP)

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.

Example Overview

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>

Files to Review

Documentation

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)