安全风险
- 数据泄露:恶意脚本可能利用反射 API 跨域获取敏感数据,例如用户登录信息、业务关键数据等。
- XSS 攻击放大:结合反射 API 跨域能力,攻击者可将恶意脚本注入到不同域页面,扩大攻击范围。
- CSRF 风险:跨域调用可能被利用来伪造用户请求,执行非用户意愿的操作,如转账、修改密码等。
代码层面防范
- 验证来源:在接收跨域请求时,通过
origin
头信息验证请求来源是否合法。
// 假设使用 Express 框架
const express = require('express');
const app = express();
app.use((req, res, next) => {
const allowedOrigins = ['http://allowed1.com', 'http://allowed2.com'];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access - Control - Allow - Origin', origin);
}
next();
});
- 输入验证与过滤:对跨域调用传入的参数进行严格验证和过滤,防止恶意数据传入。
function processData(data) {
if (typeof data ==='string' && data.length < 100) {
// 处理数据
} else {
throw new Error('Invalid data');
}
}
服务器配置层面防范
- 设置 CORS 策略:合理配置服务器的 CORS(跨域资源共享)策略,限制可跨域访问的来源。
- Apache 服务器:在
.htaccess
文件中设置
Header set Access - Control - Allow - Origin "http://allowed1.com"
location / {
add_header Access - Control - Allow - Origin http://allowed1.com;
}
- 启用安全头:设置
Content - Security - Policy
(CSP)头,限制页面可加载的资源来源,防止 XSS 攻击。
// Express 中设置 CSP
app.use((req, res, next) => {
res.setHeader('Content - Security - Policy', "default - src'self'");
next();
});