通过Amazon API Gateway转发请求时,FastAPI如何获取用户IP地址?
解决API Gateway转发后FastAPI获取用户IP的问题
问题原因
Amazon API Gateway转发请求时,默认发送标准Forwarded头而非常用的X-Forwarded-For头,这是你代码中x_forwarded_for为空的核心原因。从你打印的请求头能看到,用户真实IP已包含在Forwarded头的for字段中。
解决方案
方法1:手动解析Forwarded头
直接从请求头提取Forwarded字段,解析出for对应的值作为用户IP:
修改接口代码如下:
from fastapi import FastAPI, UploadFile, Request, Header import re @app.post("/upload") async def runUpload(file: UploadFile, request: Request, x_forwarded_for: str = Header(None), forwarded: str = Header(None)): user_ip = None # 优先解析Forwarded头的for字段 if forwarded: # 兼容IPv6带引号的格式(如for="[2001:db8:cafe::1]") match = re.search(r'for=([^;]+)', forwarded) if match: user_ip = match.group(1).strip('"') # 无Forwarded头时回退到X-Forwarded-For或客户端IP if not user_ip: user_ip = x_forwarded_for.split(',')[0].strip() if x_forwarded_for else request.client.host return {"user_ip": user_ip}
方法2:配置API Gateway添加X-Forwarded-For头
若更习惯使用X-Forwarded-For,可在API Gateway中配置集成请求手动添加该头:
- 进入API Gateway控制台,找到目标API及对应集成
- 在「集成请求」的「HTTP头」中新增配置:
- 名称:
X-Forwarded-For - 映射值:
$context.identity.sourceIp
- 名称:
- 重新部署API后,FastAPI即可通过
x_forwarded_for参数获取用户IP
注意事项
- 你的Uvicorn启动参数
proxy_headers=True和forwarded_allow_ips="*"配置正确,确保FastAPI信任代理发送的头信息 - 解析
Forwarded头时需兼容IPv6格式,这类地址通常会被引号包裹
内容的提问来源于stack exchange,提问作者AJ222
相关产品推荐
相关产品推荐

