HtmlSanitizer is a .NET library for cleaning HTML fragments and documents from constructs that can lead to XSS attacks.
It uses AngleSharp to parse, manipulate, and render HTML and CSS.
Because HtmlSanitizer is based on a robust HTML parser it can also shield you from deliberate or accidental
"tag poisoning" where invalid HTML in one fragment can corrupt the whole document leading to broken layout or style.
In order to facilitate different use cases, HtmlSanitizer can be customized at several levels:
Configure allowed HTML tags through the property AllowedTags. All other tags will be stripped.
Configure allowed HTML attributes through the property AllowedAttributes. All other attributes will be stripped.
Configure allowed CSS property names through the property AllowedCssProperties. All other styles will be stripped.
Configure allowed CSS at-rules through the property AllowedAtRules. All other at-rules will be stripped.
Configure allowed URI schemes through the property AllowedSchemes. All other URIs will be stripped.
Configure HTML attributes that contain URIs (such as "src", "href" etc.) through the property UriAttributes.
Provide a base URI that will be used to resolve relative URIs against.
Cancelable events are raised before a tag, attribute, or style is removed.
Note: to prevent classjacking and interference with classes where the sanitized fragment is to be integrated, the class attribute is disallowed by default.
It can be added as follows:
style refers to style declarations within other at-rules such as @media. Disallowing @namespace while allowing other types of at-rules can lead to errors.
Property declarations in @font-face and @viewport are not sanitized.
The Sanitize() and SanitizeDocument() methods are thread-safe, i.e. you can use these methods on a single shared instance from different threads provided you do not simultaneously set instance or static properties. A typical use case is that you prepare an HtmlSanitizer instance once (i.e. set desired properties such as AllowedTags etc.) from a single thread, then call Sanitize()/SanitizeDocument() from multiple threads.
Text content not necessarily preserved as-is
Please note that as the input is parsed by AngleSharp's HTML parser and then rendered back out, you cannot expect the text content to be preserved exactly as it was input, even if no elements or attributes were removed. Examples:
请发表评论