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

在FastAPI中使用aioboto3访问AWS Cognito遇连接超时问题求助

在FastAPI中使用aioboto3访问AWS Cognito的超时问题解决

你在FastAPI应用中使用aioboto3调用AWS Cognito的initiate_auth接口时遇到连接超时错误,错误指向EC2元数据服务地址http://169.254.169.254/latest/api/token,但同步boto3代码可以正常工作。

问题原因分析

  • 异步凭证获取逻辑差异:同步boto3获取AWS凭证时,默认重试机制和超时策略更宽松,且本地环境会优先读取~/.aws/credentials等本地配置文件。而aioboto3基于异步HTTP客户端(aiohttp),凭证获取流程中会优先尝试访问EC2元数据服务,在非EC2环境(如本地开发机)下,这个请求会因无法连接而超时。
  • 凭证来源优先级配置问题:aioboto3的Session可能未正确识别本地凭证配置,导致强制走元数据服务路径。
  • 依赖版本兼容性问题:旧版本的aioboto3或其依赖(如botocore、aiohttp)可能存在异步请求处理bug,引发元数据服务请求超时。

解决建议

1. 显式指定AWS凭证

初始化aioboto3 Session时直接传入凭证信息,跳过元数据服务自动检测:

import os
import aioboto3

session = aioboto3.Session(
    aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
    aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
    region_name=os.getenv("REGION")
)

async def authenticate(username, password):
    async with session.client("cognito-idp") as cognito_client:
        response = await cognito_client.initiate_auth(
            ClientId=os.getenv("APP_CLIENT_ID"),
            AuthFlow="USER_PASSWORD_AUTH",
            AuthParameters={"USERNAME": username, "PASSWORD": password},
        )
        return response

2. 调整元数据服务超时或禁用它

通过botocore配置修改元数据服务超时设置,或者直接禁用:

from botocore.config import Config

# 配置更长的超时与重试次数
config = Config(
    connect_timeout=10,
    read_timeout=10,
    retries={"max_attempts": 3}
)

async def authenticate(username, password):
    async with session.client("cognito-idp", region_name=os.getenv("REGION"), config=config) as cognito_client:
        # 后续代码不变
        response = await cognito_client.initiate_auth(
            ClientId=os.getenv("APP_CLIENT_ID"),
            AuthFlow="USER_PASSWORD_AUTH",
            AuthParameters={"USERNAME": username, "PASSWORD": password},
        )
        return response

本地开发环境可直接禁用元数据服务:

os.environ["AWS_EC2_METADATA_DISABLED"] = "true"

3. 升级依赖版本

确保aioboto3及相关依赖为最新稳定版:

pip install --upgrade aioboto3 botocore aiohttp

4. 检查环境变量配置

确认以下环境变量已正确设置,让aioboto3优先使用本地凭证:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_REGION

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:10:48