In website content operation, displaying user input information is one of the core functions, especially like the main text of the article, which may contain rich formatting.However, how to safely and accurately display these user-entered HTML contents on the website while preventing potential security risks (such as cross-site scripting XSS attacks) is a problem that every website operator needs to think deeply about.AnQiCMS provides flexible and powerful tools for template design and content processing to meet this challenge.
The default security mechanism of AnQiCMS: automatic escaping is the cornerstone
AnQiCMS uses the Django template engine syntax, which has a strong built-in security mechanism by default when handling variable output. This means that when you use double curly braces in the template{{变量}}When displaying content, the system will automatically escape any HTML tags and special characters contained within. For example, if the user enters<script>alert('XSS')</script>It will not be parsed by the browser as executable JavaScript code, but will be displayed safely as<script>alert('XSS')</script>.
This automatic escaping is the first line and also the most crucial defense against XSS attacks, which can effectively prevent malicious code from being executed on your website, thereby protecting the website and visitors.For those who do not expect plain text content to contain HTML formatting, or any input from untrusted sources, this default behavior is**selected.
When do you need to display raw HTML?——Understanding|safeFilter
However, not all user input should be processed as plain text.For example, the main text of an article is often written through a rich text editor, which includes bold, italic, images, links, and other HTML formats.If this content is also escaped, the formatting and style of the article will be completely lost, turning into a pile of unreadable raw tags.
At this time,|safeThe filter comes into play. When you are sure that the content of a variable is carefully designed and trusted HTML and needs to be rendered directly in HTML format, you can add it after the variable.|safeFilter. For example, when displaying the article detail page,Contentyou would usually use it like this:
{% archiveDetail articleContent with name="Content" %}
{{ articleContent|safe }}
By|safeyou clearly tell AnQiCMS, this section,articleContentIt is safe, no HTML encoding is required. But this is like opening a 'green channel' for trusted content, you need to ensure that this part of the content is strictly reviewed and from a reliable source to avoid potential cross-site scripting (XSS) attacks.In other words,|safeIt endows you with great flexibility, but also comes with corresponding security responsibilities.
Secure rendering of Markdown content:renderThe magic of parameters
The new AnQiCMS has added support for Markdown editors, which brings great convenience to content creators.Markdown content itself is plain text, but it is designed to be easily converted to HTML.AnQiCMS also provides an intelligent and safe way to display Markdown formatted text.
If the Markdown editor is enabled in the background content settings, thenContentThe field is beingarchiveDetailWhen the tag is retrieved, it will usually automatically convert Markdown to HTML.This means you do not need to manually write the conversion logic, the system will automatically parse Markdown syntax into the corresponding HTML structure.
If you need more detailed control, or if you want to override the default settings in a specific scenario,archiveDetailandpageDetailsuch as tags,ContentField supportsrenderparameter. Throughrender=trueorrender=falseYou can manually specify whether to render Markdown content:
{# 明确要求渲染Markdown内容为HTML #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}</div>
{# 明确要求不渲染Markdown内容,保持原始Markdown文本 #}
<div>原始Markdown:{% archiveDetail archiveContent with name="Content" render=false %}{{archiveContent}}</div>
Please note that even if you go throughrender=trueEnabled Markdown to HTML conversion, still need to be配合 in the output template|safeThe filter ensures that the converted HTML is correctly parsed by the browser and is not escaped again. This emphasizes|safeits core role in displaying HTML content.
Finer control: stripping, conversion and validation
In addition to the aforementioned core mechanisms, AnQiCMS template filters also provide more fine-grained content processing options to meet the security and formatting requirements of different scenarios:
Remove unnecessary HTML tags: Sometimes, you may only want to allow some HTML tags (such as
<b>/<i>), while prohibiting all other tags (such as<script>/<img>)striptagsThe filter can remove all HTML tags, leaving only plain text content; andremovetags:"标签1,标签2"The filter can remove specified HTML tags while retaining the rest. This is very useful in scenarios such as handling user comments where strict HTML restrictions are required.{# 移除所有HTML标签 #} {{ userComment|striptags }} {# 只移除script和style标签 #} {{ userComment|removetags:"script,style"|safe }}Securely convert URLs and email addressesWhen a user enters a URL or email in the text, we want them to automatically become clickable links while ensuring safety.
urlizeThe filter will automatically identify URLs and email addresses in the text and convert them to withrel="nofollow"properties<a>Tags, to enhance security and prevent spam links. If you need to limit the display length of link text, you can useurlizetrunc:长度.{# 自动将文本中的URL和邮箱转换为链接 #} {{ articleDescription|urlize|safe }} {# 转换链接并截断显示文本为15个字符 #} {{ articleDescription|urlizetrunc:15|safe }}Insert data in JavaScript: If you need to dynamically insert data from user input into JavaScript code, directly inserting unprocessed HTML can lead to serious JavaScript injection vulnerabilities.
escapejsThe filter can escape special characters in strings (such as newline characters, quotes, etc.) to ensure that the data is safely treated as a string in the JS environment.<script> var userName = "{{ userInputName|escapejs }}"; alert("Hello, " + userName); </script>
Summary: Balancing safety and flexibility.
AnQiCMS provides us with multi-level tools at the template level, ensuring a balance between flexibility and security in content display.The core principle is 'default security, release as needed': the system defaults to escaping all outputs in HTML to maximize the avoidance of XSS risks.When you know the content is safe and need to render as HTML, use it cautiously|safeFilter. Combined with Markdown'srenderParameter,striptags/urlizeFilters, you can fully utilize the expressiveness of HTML to provide visitors with rich and high-quality content experience under the premise of ensuring website security.