CSRF(Cross-Site Request Forgery,跨站请求伪造)是一种常见的Web安全威胁,攻击者诱使用户在已登录的Web应用中执行非预期的操作。作为IT工程师,在Nginx层面实施防护策略可以有效减轻这类风险。
# 限制跨域请求
add_header 'Access-Control-Allow-Origin' 'yourdomain.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
# 确保敏感Cookie设置Secure和HttpOnly属性
proxy_cookie_path / "/; Secure; HttpOnly; SameSite=Strict";
# 对于POST请求验证CSRF Token
location /api/ {
if ($request_method = POST) {
set $csrf_check "failed";
if ($http_x_csrf_token = $cookie_csrf_token) {
set $csrf_check "passed";
}
if ($csrf_check = "failed") {
return 403;
}
}
# 其他代理配置...
}
# 限制只允许特定HTTP方法
location /sensitive-action {
limit_except GET POST {
deny all;
}
# 其他配置...
}
# 验证Referer头
location /protected/ {
valid_referers none blocked server_names *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
# 其他配置...
}
# 要求特定API请求包含自定义头
location /api/v1/ {
if ($http_x_requested_with != "XMLHttpRequest") {
return 403;
}
# 其他配置...
}
# 限制敏感端点请求频率
limit_req_zone $binary_remote_addr zone=csrflimit:10m rate=10r/m;
location /login {
limit_req zone=csrflimit burst=20 nodelay;
# 其他配置...
}
# 强制HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
通过以上Nginx配置策略,可以显著提高Web应用对CSRF攻击的抵御能力,但需注意安全是一个持续的过程,需要定期更新和调整防护措施。