1 怎么在jinja模板中原始输出模板语法
1.1 用双引号引起来后放到 {{ }} 中
例如
{{ "{{}}" }}
输出
1.2 利用raw
例如
{% raw %} {% for i in range(11) %} <li>{{ i }}</li> {% endfor %} {% endraw %}
输出
2 模板中遇到带有script标签怎么办
如果在模板遇到 >、<、&、” 等字符时Jinja2模板会自动进行转义,即利用其它的字符来代替这些模板,例如:利用 < 代替<
2.1 Jinja2模板如何判断需要渲染的字符串是否需要转义
如果渲染的字符串有 __html__ 属性就认为是安全的,不需要进行转义;否则就会自动进行转义
注意:也可以利用 {{ to_escape is escaped }} 去判断 to_escape 变量是否拥有 __html__ 属性,如果返回false就没有
2.2 如何取消转义
让需要进行渲染的模板拥有 __html__ 属性就会自动取消转义
{{待渲染字符串|safe}} 这样写的话待渲染字符串就会拥有 __html__ 属性,从而会取消转义
2.3 如何判断转义
{{待转义字符串 is escaped}} 返回结果为False就表示需要进行转义,为True就表示不需要进行转义
2.4 如何自定义是否需要进行转义
利用 autoescape,设置为false表示不会进行转义,设置为true表示会进行转义
3 XSS攻击
例如:用户评论的内容是一段 html 代码,如果这段代码不经过转义处理,那么其他用户在加载页面的时候机会执行这段代码
3.1 模拟一个用户评论模块
3.1.1 编写评论页面
{% from 'my_macros.html' import form, input, textarea %} {% autoescape true %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试XSS</title> </head> <body> <h4>测试XSS相关知识</h4> <hr /> {% call form('xss.test_xss') %} {{ textarea('comment') }} {{ input('button', type='submit', value='发表') }} {% endcall %} <hr /> {% if comments %} <ul> {% for comment in comments %} <li>{{ comment }}</li> {% endfor %} </ul> {% endif %} </body>he </html> {% endautoescape %}