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

如何在AWS API Gateway中获取客户端源IP地址?(SDK与Lambda场景)

正确获取AWS API Gateway下的客户端原始IP地址

你的代码思路方向正确,但需要注意API Gateway的集成配置和代码中的细节调整,才能准确拿到真实客户端IP,以下是针对Lambda和ASP.NET Core后端的修正方案:

一、AWS Lambda函数的正确实现

默认情况下,API Gateway会将客户端真实IP填充到APIGatewayProxyRequest.RequestContext.Identity.SourceIp中。如果存在多层代理(如CloudFront+API Gateway),则需要解析X-Forwarded-For头获取最原始的客户端IP:

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using System.Collections.Generic;

public class Function
{
    public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {
        // 优先从RequestContext获取IP(API Gateway默认填充)
        string clientIp = request.RequestContext.Identity.SourceIp;

        // 处理多层代理场景:解析X-Forwarded-For头,取第一个IP即为客户端真实IP
        if (request.Headers.TryGetValue("X-Forwarded-For", out var forwardedFor))
        {
            clientIp = forwardedFor.Split(',')[0].Trim();
        }

        context.Logger.LogInformation($"客户端IP地址: {clientIp}");

        return new APIGatewayProxyResponse
        {
            StatusCode = 200,
            Body = clientIp,
            Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
        };
    }
}

二、ASP.NET Core后端的正确实现

如果你的后端是基于ASP.NET Core并通过Amazon.Lambda.AspNetCoreServer集成API Gateway,不要手动从Query绑定APIGatewayProxyRequest,可以通过以下两种方式获取IP:

方式1:通过Lambda请求上下文获取

using Amazon.Lambda.APIGatewayEvents;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/v1/ip")]
public class IpController : ControllerBase
{
    [HttpGet]
    public IActionResult GetClientIp()
    {
        // 从HttpContext中获取Lambda转发的API Gateway请求对象
        var apiGatewayRequest = HttpContext.Items["LambdaRequest"] as APIGatewayProxyRequest;
        string clientIp = apiGatewayRequest?.RequestContext.Identity.SourceIp;

        // 处理多层代理场景
        if (Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedFor))
        {
            clientIp = forwardedFor.ToString().Split(',')[0].Trim();
        }

        return Ok(new { ClientIp = clientIp });
    }
}

方式2:直接通过HttpContext.Connection获取

Amazon.Lambda.AspNetCoreServer会自动将API Gateway传递的IP映射到HttpContext.Connection,可以直接读取:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/v1/ip")]
public class IpController : ControllerBase
{
    [HttpGet]
    public IActionResult GetClientIp()
    {
        var remoteIp = HttpContext.Connection.RemoteIpAddress;
        if (remoteIp == null)
        {
            return BadRequest("无法获取客户端IP");
        }

        // 转换IPv6格式到IPv4(如果需要)
        string clientIp = remoteIp.IsIPv6LinkLocal ? remoteIp.MapToIPv4().ToString() : remoteIp.ToString();

        return Ok(new { ClientIp = clientIp });
    }
}

关键注意事项

  • 必须开启Lambda Proxy集成:在API Gateway的集成设置中,确保选择"Lambda Proxy integration",否则RequestContext不会填充完整的IP信息。
  • 多层代理配置:如果使用CloudFront作为前置代理,需要在CloudFront的缓存行为设置中,将X-Forwarded-For头添加到"Forward Headers"列表,确保真实IP能传递到API Gateway。
  • 避免IP覆盖:不要在API Gateway中配置额外的代理转发规则,防止客户端IP被中间代理IP替换。

内容的提问来源于stack exchange,提问作者Hein Wai Yan Htet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 19:07:07