
本文详解如何在 Spring Cloud Function + AWS Lambda 函数 URL(v2.0 负载格式)场景下,正确提取并校验客户端源 IP,避免误用不可信的 X-Forwarded-For 头,确保 Stripe Webhook 等敏感接口的 IP 白名单机制安全可靠。
本文详解如何在 spring cloud function + aws lambda 函数 url(v2.0 负载格式)场景下,正确提取并校验客户端源 ip,避免误用不可信的 `x-forwarded-for` 头,确保 stripe webhook 等敏感接口的 ip 白名单机制安全可靠。
AWS Lambda 函数 URL 默认使用 Payload Format Version 2.0(如您日志中 "version": "2.0" 所示),而 APIGatewayProxyRequestEvent 是为 API Gateway REST/HTTP API 的 v1.0 格式设计的——它不包含 requestContext.http.sourceIp 字段,因此无法直接访问真实客户端 IP。强行尝试从 headers.get("x-forwarded-for") 获取 IP 存在严重安全隐患:该头可被恶意客户端伪造,绝不适用于安全敏感的白名单校验场景。
正确的解决方案是:改用 APIGatewayV2HTTPEvent 类型作为函数输入参数。该类型原生支持 v2.0 负载结构,其 getRequestContext().getHttp().getSourceIp() 方法可直接、可信地返回经 Lambda 服务验证的真实源 IP(即 $.requestContext.http.sourceIp)。
✅ 正确实现步骤
-
添加依赖(确保使用支持 v2 事件的 AWS Java Events 库):
<!-- Maven --> <dependency><groupid>com.amazonaws</groupid><artifactid>aws-lambda-java-events</artifactid><version>3.11.4</version><!-- 推荐 ≥3.11.0 --></dependency>
-
修改函数签名与逻辑(关键变更):
import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPResponse;
@Bean
public Function
// ✅ 安全获取真实源 IP(Lambda 自动注入,不可伪造)
String sourceIp = request.getRequestContext()
.getHttp()
.getSourceIp();
// ? 拒绝非 Stripe 官方 IP(参考:https://stripe.com/docs/ips)
if (!isStripeIp(sourceIp)) {
return new APIGatewayV2HTTPResponse()
.withStatusCode(403)
.withBody("Forbidden: Invalid source IP");
}
String jsonPayload = request.getBody();
String sigHeader = request.getHeaders().get("stripe-signature");
if (sigHeader == null) {
return new APIGatewayV2HTTPResponse()
.withStatusCode(400)
.withBody("Invalid signature");
}
try {
Event event = Webhook.constructEvent(jsonPayload, sigHeader, "whsec_...");
stripeEventService.processEvent(event);
return new APIGatewayV2HTTPResponse()
.withStatusCode(200)
.withBody("Event processed");
} catch (SignatureVerificationException e) {
return new APIGatewayV2HTTPResponse()
.withStatusCode(400)
.withBody("Invalid signature");
}
};
}
private boolean isStripeIp(String ip) { // 实际生产中应使用 Stripe 提供的官方 IP 段列表(定期更新) // 示例仅作示意,务必替换为最新 CIDR 列表 return ip != null && ( ip.startsWith("192.168.1.") || // ⚠️ 替换为真实 Stripe CIDR(如 151.101.0.0/20) "204.236.220.1".equals(ip) // ⚠️ 同上 ); }
### ⚠️ 重要注意事项 - **不要混用事件类型**:若使用 `APIGatewayV2HTTPEvent`,则必须确保 Lambda 的触发源为 **Function URL 或 API Gateway HTTP API(v2.0)**;REST API 仍需 `APIGatewayProxyRequestEvent`。 - **IP 白名单需动态维护**:Stripe 公开的 [Webhook IP 地址范围](https://stripe.com/docs/ips) 可能调整,请通过其官方文档或 API 定期同步 CIDR 列表,避免硬编码。 - **Spring Cloud Function 适配器兼容性**:确认 `spring-cloud-function-adapter-aws` 版本 ≥ 4.0.0(对应 Spring Boot 3.x),旧版本可能默认强制解析为 v1 事件,需检查 `AwsProxyRequestHandler` 配置。 - **日志调试建议**:首次部署时,可临时打印 `request.toString()` 验证事件结构是否为 v2.0 格式,确认 `requestContext.http.sourceIp` 字段存在。 通过以上改造,您即可在函数 URL 场景下,以零信任原则安全、精准地完成源 IP 校验,为 Stripe Webhook 构建坚实的第一道网络防线。










