You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lambda Function URL场景下如何安全获取源IP并实现IP白名单?

解决方案

1. 正确获取Function URL的源IP

Lambda Function URL的请求事件中,源IP存储在APIGatewayProxyRequestEvent的requestContext.http.sourceIp字段,而非requestContext.identity.sourceIp(后者仅适用于传统API Gateway)。如果你当前无法获取该值,先检查spring-cloud-function-aws-adapter的版本——低版本可能未适配Function URL的事件结构,建议升级到4.x及以上的稳定版。

示例代码片段:

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import java.util.function.Function;

public class StripeWebhookFunction implements Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    @Override
    public APIGatewayProxyResponseEvent apply(APIGatewayProxyRequestEvent event) {
        // 获取真实源IP
        String sourceIp = event.getRequestContext().getHttp().getSourceIp();
        // 后续白名单校验逻辑...
        return new APIGatewayProxyResponseEvent();
    }
}

2. 用Lambda Function URL资源策略实现IP白名单(推荐)

直接在AWS层面配置资源策略拦截非白名单IP,比代码校验更安全(请求不会到达Lambda),步骤如下:

  • 打开Lambda控制台,找到目标函数,进入「配置」>「Function URL」>「编辑资源策略」
  • 添加允许Stripe官方IP段的策略(Stripe会定期公布其webhook使用的IP范围),示例策略结构:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "lambda:InvokeFunctionUrl",
      "Resource": "arn:aws:lambda:你的区域:账号ID:function:目标函数名",
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": [
            "3.18.12.0/22",
            "3.130.192.0/21",
            // 补充Stripe最新的IP段
          ]
        }
      }
    }
  ]
}

3. 结合Stripe Webhook签名验证(双重保障)

IP白名单可能存在IP更新的问题,建议同时启用Stripe的webhook签名验证,确保请求确实来自Stripe:

  • 在Stripe控制台获取你的webhook签名密钥
  • 使用Stripe Java SDK验证请求头中的Stripe-Signature:
import com.stripe.exception.SignatureVerificationException;
import com.stripe.net.Webhook;

public class StripeWebhookValidator {
    private static final String STRIPE_WEBHOOK_SECRET = "你的签名密钥";

    public static boolean verifySignature(String payload, String signatureHeader) {
        try {
            Webhook.verifyHeader(payload, signatureHeader, STRIPE_WEBHOOK_SECRET, 300);
            return true;
        } catch (SignatureVerificationException e) {
            return false;
        }
    }
}

在函数中先验证签名,再做IP校验,双重保障安全性。


内容的提问来源于stack exchange,提问作者Poklakni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:03:29