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];
    rng.GetBytes(nonceBytes);
    string nonceValue = Convert.ToBase64String(nonceBytes);
    context.Items.Add("ScriptNonce", nonceValue);
    context.Response.Headers.Add("Content-Security-Policy", string.Format(
    "script-src 'self' 'nonce-{0}' cdn.syncfusion.com;" +
    "style-src-elem 'self' cdn.syncfusion.com fonts.googleapis.com;" +
    "font-src 'self' data: fonts.gstatic.com;" +
    "object-src 'none';", nonceValue));
    await next();
});
  • Open _Layout.cshtml file and add nonce attribute in the client side resources like below,
<head>
    ...
    <!-- Syncfusion ASP.NET Core controls scripts -->
    <script src="https://cdn.syncfusion.com/ej2/20.1.55/dist/ej2.min.js" nonce="@Context.Items["ScriptNonce"]"></script>
</head>
  • Set add-nonce for ejs-scripts while registering the script manager at the end of <body> of _Layout.cshtml file as follows,
<body>
    ...
    <!-- Syncfusion ASP.NET Core Script Manager -->
    <ejs-scripts add-nonce="@Context.Items["ScriptNonce"]"></ejs-scripts>
</body>
  • Run the application then see the DOM, nonce attribute is added in script tag and it’s value hidden for security purpose.

See also