威胁类型 | 风险描述 | 典型案例 |
---|---|---|
中间人攻击(MITM) | 传输数据被窃听/篡改 | SSLStrip攻击 |
凭证泄露 | API密钥/令牌被盗用 | GitHub API密钥泄漏事件 |
重放攻击(Replay) | 合法请求被重复使用 | 支付接口重复扣款 |
未授权访问 | 权限绕过漏洞 | AWS S3桶配置错误 |
DDoS攻击 | 服务资源耗尽 | Memcached放大攻击 |
# Flask IP白名单示例
from flask import request, abort
ALLOWED_IPS = {'192.168.1.0/24', '10.0.0.1'}
@app.before_request
def check_ip():
client_ip = request.remote_addr
if not any(client_ip in network for network in ALLOWED_IPS):
abort(403) # Forbidden
原理:
192.168.1.0/24
)优势:
劣势:
# 生成CA证书
openssl genrsa -out ca.key 2048
openssl req -x509 -new -key ca.key -out ca.crt -days 365
# 生成服务端证书
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
# 生成客户端证书(同理)
Java客户端实现:
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream("client.p12"), "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "password".toCharArray());
sslContext.init(kmf.getKeyManagers(), null, null);
try (CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.build()) {
HttpGet request = new HttpGet("https://server/api");
return client.execute(request);
}
原理:
优势:
劣势:
令牌生成:
import jwt
from datetime import datetime, timedelta
secret_key = "SUPER_SECRET_KEY"
payload = {
"iss": "auth_server",
"aud": "api_server",
"sub": "service_account",
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(minutes=10),
"scope": "read:data write:logs"
}
token = jwt.encode(payload, secret_key, algorithm="HS256")
服务端验证:
try:
decoded = jwt.decode(
token,
secret_key,
algorithms=["HS256"],
audience="api_server",
issuer="auth_server"
)
except jwt.ExpiredSignatureError:
abort(401, "Token expired")
except jwt.InvalidTokenError:
abort(401, "Invalid token")
原理:
优势:
劣势:
关键参数:
POST /token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=your_client_id
&client_secret=your_client_secret
&scope=api.read
优势:
劣势:
架构示例:
[Client] → [API Gateway] → [JWT验证] → [Rate Limiter] → [Upstream Services]
│ │
└─[Auth Server]
网关功能:
Nginx配置片段:
location /api/ {
auth_request /auth;
proxy_pass http://upstream_servers;
}
location = /auth {
internal;
proxy_pass http://auth_server/validate;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
}
优势:
劣势:
架构核心:
RBAC策略定义:
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: service-a-access
spec:
selector:
matchLabels:
app: service-b
rules:
- from:
- source:
principals: ["cluster.local/ns/default/sa/service-a"]
to:
- operation:
methods: ["GET", "POST"]
paths: ["/api/v1/*"]
优势:
劣势:
方案 | 认证强度 | 加密能力 | 延迟增加 | 运维复杂度 | 适用场景 |
---|---|---|---|---|---|
IP白名单 | ★☆☆☆☆ | ✘ | <1ms | ★☆☆☆☆ | 内部可信网络 |
mTLS | ★★★★★ | ★★★★★ | 50-100ms | ★★★☆☆ | 金融/医疗等高安全要求 |
JWT | ★★★★☆ | 可选 | 5-10ms | ★★☆☆☆ | 无状态API/微服务 |
OAuth2客户端凭证 | ★★★★☆ | 依赖传输 | 200-500ms | ★★★★☆ | 第三方服务集成 |
API网关 | ★★★★☆ | 可选 | 5-15ms | ★★★☆☆ | 统一入口管理 |
服务网格 | ★★★★★ | ★★★★★ | 10-20ms | ★★★★★ | 云原生架构 |
请求签名(HTTP Signatures)
POST /data HTTP/1.1
Host: api.example.com
Signature: keyId="client1",algorithm="rsa-sha256",headers="(request-target) date",signature="Base64(RSA-SHA256(...))"
Date: Tue, 20 Jun 2023 12:00:00 GMT
动态凭证轮转
审计日志标准化
{
"timestamp": "2023-06-20T12:00:00Z",
"client_ip": "192.168.1.100",
"user_agent": "API-Client/1.0",
"endpoint": "/api/v1/users",
"status_code": 200,
"request_id": "a1b2c3d4",
"latency_ms": 45
}
金融支付系统
mTLS + JWT细粒度授权 + 硬件安全模块(HSM)
物联网设备通信
证书预置(PKI) + MQTT over TLS + 离线吊销列表(OCSP Stapling)
微服务架构
服务网格(Istio) + OPA策略引擎 + 分布式追踪
# OPA策略示例
default allow = false
allow {
input.method == "GET"
input.path = "/api/v1/products"
token.payload.scope[_] == "read:products"
}
重放攻击防御
SETEX nonce:${nonce} 60 1 # 设置60秒过期
DDoS缓解
http {
limit_req_zone $binary_remote_addr zone=api_zone:10m rate=100r/s;
server {
location /api/ {
limit_req zone=api_zone burst=50 nodelay;
}
}
}
注入攻击防护
text/xml
)__proto__
)量子安全密码学
零信任架构扩展
机密计算
终极建议:采用深度防御策略,组合mTLS(传输层)+JWT(应用层)+网关审计(监控层),并定期进行渗透测试(建议使用Burp Suite Enterprise+OWASP ZAP组合扫描)。
所有方案需配套实施: