In AnQiCMS template creation, handling character escaping is a very important topic, especially related to website security and the correct display of content. When people first encounter such issues, they might naturally think of some common escaping functions, such asaddslashes.However, in the template environment of AnQiCMS, we actually have more suitable alternatives that are more in line with the design philosophy and safer, and they can more accurately meet the needs of escaping in different scenarios.
Firstly, let's understandaddslashesWhat is this function usually used for?It is mainly to add a backslash before the specific characters (such as single quotes, double quotes, backslashes).This operation is usually performed to safely insert a string into a context that requires a string literal expression, such as when constructing an SQL query statement or in some old-style JavaScript strings.It mainly focuses on preventing string injection, rather than protecting against the browser's parsing behavior for HTML or JavaScript code.
In the AnQiCMS system based on Go language and Django-style template engine, the security of content output has been considered very thoroughly. This system has always paid great attention to security and ease of expansion from the beginning of its design, and it incorporates powerful security mechanisms, the most core of which is自动转义(Auto-escaping).
AnQiCMS 模板中的核心安全机制:自动转义(English)
When you use double curly braces in AnQiCMS templates{{ 变量 }}When outputting content, the system will automatically escape the values of these variables. This means that if your variables contain HTML special characters, such as</>/&/"/'They will be automatically converted to the corresponding HTML entity encoding, such as</>/&etc. This mechanism is the first and most important line of defense against cross-site scripting attacks (XSS).
For example, if a user submits a comment content that is<script>alert('XSS');</script>when you output it directly in the template in the form of{{ comment.Content }}it will automatically become<script>alert('XSS');</script>The browser will display it as plain text, rather than executing malicious scripts.This default behavior greatly simplifies the work of template developers, allowing everyone to focus more on content display without having to manually consider HTML escaping issues every time.
for more precise control over HTML output:escapeFilter
Although AnQiCMS templates default to automatic escaping, in certain specific situations, you may need to have more explicit control over the escaping behavior. AnQiCMS providesescape(or its alias)e)Filter, it can explicitly convert HTML special characters in a string to HTML entities.
What scenarios is this filter useful in? It is mainly when you go through{% autoescape off %}标签显式关闭了某个模板块的自动转义功能,但该块内的某个特定变量仍需要HTML转义时。通过English{{ variable | escape }}You can ensure that specific variables can be safely output even in environments where automatic escaping is not applied.
For example:
{% autoescape off %}
<p>这个内容不会自动转义:{{ user_input }}</p>
<p>但是这个变量被强制HTML转义了:{{ user_input | escape }}</p>
{% endautoescape %}
This ensures that while you have flexible control over automatic escaping, you can still maintain the necessary data security.
The exclusive tool for processing JavaScript content:escapejsFilter
Insert dynamic content into a JavaScript code block requires special handling different from HTML escaping, because JavaScript has its own special characters and syntax rules.If only HTML escaping is used, it may cause JavaScript syntax errors or new security vulnerabilities.escapejsFilter.
escapejsThe filter will remove special characters from strings (such as\rcarriage return\nsingle quotes', double quotes)"backslash\Convert to JavaScript string literals that can be safely parsed into English\uxxxxForm. This is especially important when embedding dynamic data as JavaScript variables, function arguments, or JSON strings into HTML pages.<script>within tags.
For example, if you want to assign a string variable to a JavaScript variable:
<script>
var dynamicMessage = "{{ article.Title | escapejs }}";
alert(dynamicMessage);
</script>
Here are theescapejsensured that evenarticle.TitleContains special characters such as quotes, which will not disrupt the syntax of JavaScript, thus avoiding potential XSS vulnerabilities.
When to use with cautionsafeFilter?
WithescapeThe filter is relative, AnQiCMS also providessafeFilter.safeThe function of filters isMarking variable content as safe, no escaping is required. Once you have usedsafeThe system will fully trust the content of the variable and output it as raw HTML or text.
Because of its power,safethe filter mustextremely cautiousbe used properly. Its main application scenarios are:
- Rich text editor content:If you are sure that the content entered through the backend rich text editor has been strictly sanitized and verified on the server side, and does not contain any malicious scripts, then you can use
safeTo display its contained HTML format. - Trusted, pre-rendered HTML fragments:For example, the content of static HTML files obtained from trusted sources.
Any data from user input or untrusted sources, if not strictly purified on the server side,should never be used directlysafeFilter outputIf not, it will be directly exposed to the risk of XSS attacks, which is contrary to the original intention of AnQiCMS to provide a secure website.
实战建议:How to choose the correct escape method
In the template creation of AnQiCMS, choosing the correct character escape method is actually very simple:
- Most of the time: Believe in automatic escaping.For the output of general text content (such as article titles, summaries, etc.), AnQiCMS's default automatic HTML escaping function is sufficiently secure.
- Embed dynamic values in HTML attributes:Similarly, under normal circumstances, automatic escaping is sufficient. However, if the attribute value may contain special URLs or JS, it is recommended to perform additional encoding or validation based on the specific scenario.
- Embed dynamic values in JavaScript code blocks:it is essential to use
escapejsFilter. This is the key to prevent JavaScript injection and XSS attacks. - Output rich text editor content:If the background has a perfect security filtering mechanism for rich text content, it can be used
safeFilter. If you cannot fully trust the content source, you need to perform additional server-side purification or reconsider the design scheme. - Avoid
addslashes:In the AnQiCMS template,addslashesThis filter is mainly used to add a backslash before the predefined characters in a string, its purpose is relatively narrow, and it is usually not used to handle security issues of HTML or JavaScript output.Overusing or misusing it may cause content display to be abnormal (such as additional backslashes).
通过合理运用AnQiCMS提供的自动转义机制和Englishescape/escapejs/safeFilter settings, not only can you ensure the correct display of website content, but also build a solid security barrier, making your AnQiCMS website operate efficiently while staying away from potential security risks.
Common Questions (FAQ)
1. I found that some HTML tags were displayed instead of being parsed when I output content in the template<p>Why is that?
This is the default automatic HTML escaping mechanism of AnQiCMS template system. It will convert</>English special characters are converted to HTML entities to prevent cross-site scripting (XSS) attacks. If your content is from a rich text editor and you confirm it is safe HTML, you can use|safeFilter to unescape, so that HTML tags can be parsed normally.
2. I embedded AnQiCMS variables in my JS code and the page JS reported an error. Is this related to character escaping?
很可能有关。Directly embedding a string variable containing special characters (such as quotes, newline characters) into JavaScript code may break the JS syntax.|escapejsFilterer to