Filter JavaScript from properties and files
Shows how to sanitize potentially malicious JavaScript
A user can embed JavaScript in XhtmlString
properties and in uploaded files (such as SVG images). Often this is intended, but sometimes it can be malicious. Through configuration, you can specify the following options for MediaUploadMode
, ScriptParserMode
, XhtmlString
, LinkItem
and Url
when you upload a file with scripts or in other properties.
The following example shows how to configure it programmatically in the startup.cs
.
public void ConfigureServices(IServiceCollection services)
{
// ... existing configuration ...
// Configure ScriptParserOptions
services.Configure<ScriptParserOptions>(options =>
{
// Configure parsing modes
options.LoadingMode = ScriptParserMode.Remove; // Remove scripts when loading from database
options.SavingMode = ScriptParserMode.ThrowException; // Throw exception when saving scripts
options.MediaUploadMode = ScriptParserMode.ThrowException; // Throw exception when uploading media with scripts
// Configure which media file extensions should be parsed for scripts
options.MediaExtensionsToParse = new[] { ".svg", ".svgz", ".html", ".htm", ".xml" };
// Configure illegal URI schemes
options.IllegalUriSchemes = new List<string> { "javascript"};
// Configure element attributes handling
options.Mode = ScriptParserOperationMode.Block; // Block mode (blacklist)
// Clear default settings and add custom rules
options.ElementAttributes.Clear();
// Block all "on*" event attributes on all elements
options.ElementAttributes.Add("*", "on*");
// Block specific attributes on specific elements
options.ElementAttributes.Add("img", "onerror,onload");
// Alternative: Use Allow mode (whitelist)
// options.Mode = ScriptParserOperationMode.Allow;
// options.ElementAttributes.Clear();
// options.ElementAttributes.Add("div", "class,id,style");
// options.ElementAttributes.Add("img", "src,alt,class,id");
});
// ... rest of your existing configuration ...
}
Updated about 2 hours ago