Cross-Site Scripting (XSS)

16 May 20223 minutes to read

Cross-Site Scripting is a security vulnerability and a client-side injection attack. Attackers inject the malicious code in a web application, usually JavaScript but could also be HTML or CSS. To prevent this aspect, the API EnableHtmlSanitizer is provided and its default value is set to true.

EnableHtmlSanitizer Supported Controls

The following list demonstrates the Syncfusion ASP.NET Core controls that are supported with EnableHtmlSanitizer property.

Adding Nonce to Script tag in ASP.NET Core

Nonce attribute is used in content security policy to find out whether given request is valid or not and it prevents the attackers injecting the javascript code in a web application.

The following steps demonstrates how to create and include the nonce attribute in ASP.NET Core application.

  • Generate the nonce attribute value by adding the below code in Program.cs file.
using System.Security.Cryptography;

app.Use(async (context, next) =>
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] nonceBytes = new byte[32];
    string nonceValue = Convert.ToBase64String(nonceBytes);
    context.Items.Add("ScriptNonce", nonceValue);
    context.Response.Headers.Add("Content-Security-Policy", string.Format(
    "script-src 'self' 'nonce-{0}';" +
    "style-src-elem 'self';" +
    "font-src 'self' data:;" +
    "object-src 'none';", nonceValue));
    await next();
  • Open _Layout.cshtml file and add nonce attribute in the client side resources like below,
    <!-- Syncfusion ASP.NET Core controls scripts -->
    <script src="" nonce="@Context.Items["ScriptNonce"]"></script>
  • Set add-nonce for ejs-scripts while registering the script manager at the end of <body> of _Layout.cshtml file as follows,
    <!-- Syncfusion ASP.NET Core Script Manager -->
    <ejs-scripts add-nonce="@Context.Items["ScriptNonce"]"></ejs-scripts>
  • Run the application then see the DOM, nonce attribute is added in script tag and it’s value hidden for security purpose.

See also