在前端开发中,防止 XSS(跨站脚本攻击) 是确保应用安全的关键。以下是全面的防护策略和代码示例:
一、XSS 攻击类型
类型 | 描述 | 示例 |
存储型 XSS | 恶意脚本存储到服务器,用户访问时触发 | 评论区插入 <script>alert(1)</script> |
反射型 XSS | 恶意脚本通过 URL 参数注入并立即执行 | ?q=<script>alert(1)</script> |
DOM 型 XSS | 前端脚本直接操作 DOM 导致恶意代码执行 | document.write(location.hash) |
二、防护策略
1. 输入验证与过滤
- 规则:对用户输入进行严格验证,拒绝非法字符
- 示例:
- javascript
- 复制
- function sanitizeInput(input) { return input.replace(/[<>"'&]/g, ''); // 移除危险字符 } const userInput = '<script>alert(1)</script>'; const safeInput = sanitizeInput(userInput); // 输出空字符串
2. 输出编码
- 规则:在渲染动态内容时,对特殊字符进行转义
- 示例:
- javascript
- 复制
- function escapeHTML(str) { return str.replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } const userInput = '<script>alert(1)</script>'; const safeOutput = escapeHTML(userInput); // 输出转义后的字符串
3. 使用安全的 DOM API
- 规则:避免直接操作 innerHTML,优先使用 textContent 或 setAttribute
- 示例:
- javascript
- 复制
- // 不安全的写法 document.getElementById('output').innerHTML = userInput; // 安全的写法 document.getElementById('output').textContent = userInput;
4. 启用 CSP(内容安全策略)
- 规则:通过 HTTP 头限制脚本加载来源
- 示例:
- http
- 复制
- Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;
5. 使用安全的第三方库
- 推荐库:
- DOMPurify:净化 HTML 内容
- sanitize-html:过滤危险标签
- 示例:
- javascript
- 复制
- import DOMPurify from 'dompurify'; const dirtyHTML = '<script>alert(1)</script>
安全内容
'; const cleanHTML = DOMPurify.sanitize(dirtyHTML); // 输出:安全内容
三、框架内置防护
1. React
- 自动转义:React 默认对 JSX 中的动态内容进行转义
- 危险操作:避免使用 dangerouslySetInnerHTML
- 示例:
- jsx
- 复制
- const userInput = '<script>alert(1)</script>'; return {userInput}; // 自动转义,安全
2. Vue
- 自动转义:Vue 的模板语法默认对插值内容进行转义
- 危险操作:避免使用 v-html
- 示例:
- html
- 复制
- <div>{{ userInput }}