导航菜单

前端安全基础

前端安全概述

1. 前端安全的重要性

前端安全是Web应用安全的第一道防线。随着Web应用的复杂性增加,前端面临的安全威胁也越来越多。前端安全不仅关系到用户体验,更关系到整个应用的安全性。

2. 前端安全的核心概念

同源策略(Same-Origin Policy)

同源策略是浏览器最基本的安全机制,它限制了来自不同源的文档或脚本之间的交互。同源的定义包括:

  • 协议相同(http/https)
  • 域名相同
  • 端口相同
// 同源示例
http://example.com/page1.html 和 http://example.com/page2.html 是同源
http://example.com 和 https://example.com 不是同源
http://example.com 和 http://api.example.com 不是同源
http://example.com:80 和 http://example.com:8080 不是同源
内容安全策略(CSP)

CSP是一个额外的安全层,用于检测和减轻某些类型的攻击,如XSS和数据注入攻击。它通过指定允许加载的资源类型和来源来实现。

// CSP配置示例
Content-Security-Policy: 
  default-src 'self';  // 只允许从同源加载资源
  script-src 'self' https://trusted-cdn.com;  // 允许从指定CDN加载脚本
  style-src 'self' 'unsafe-inline';  // 允许内联样式
  img-src 'self' data: https:;  // 允许从同源、data URL和HTTPS加载图片
  connect-src 'self' https://api.example.com;  // 允许向指定API发送请求
跨域资源共享(CORS)

CORS是一种机制,允许Web应用服务器进行跨域访问控制,从而使跨域数据传输得以安全进行。

// 服务器端CORS配置示例(Node.js/Express)
app.use(cors({
  origin: 'https://trusted-site.com',  // 允许的源
  methods: ['GET', 'POST'],  // 允许的HTTP方法
  allowedHeaders: ['Content-Type', 'Authorization'],  // 允许的请求头
  credentials: true,  // 允许发送凭证
  maxAge: 86400  // 预检请求的缓存时间
}));

// 客户端跨域请求示例
fetch('https://api.example.com/data', {
  method: 'POST',
  credentials: 'include',  // 包含凭证
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ data: 'example' })
});

3. 前端安全最佳实践

// 1. 输入验证
function validateInput(input) {
  // 使用正则表达式验证输入
  const pattern = /^[a-zA-Z0-9]+$/;
  return pattern.test(input);
}

// 2. 输出编码
function encodeOutput(input) {
  return input
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

// 3. 安全的Cookie设置
document.cookie = "sessionId=123; Secure; HttpOnly; SameSite=Strict";

// 4. 安全的本地存储
// 使用加密存储敏感数据
const encryptedData = CryptoJS.AES.encrypt(
  JSON.stringify(sensitiveData),
  secretKey
).toString();
localStorage.setItem('encryptedData', encryptedData);