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

跨AWS账户跨区域调用STS AssumeRole后访问S3报InvalidToken错误

问题

从AWS账户A的eu-west-1区域调用sts:AssumeRole接口获取AWS账户B中角色的临时凭证,使用该凭证访问位于eu-south-1区域的S3存储桶ListObjectsV2接口时,触发如下错误:

botocore.exceptions.ClientError: An error occurred (InvalidToken) when calling the ListObjectsV2 operation: The provided token is malformed or otherwise invalid.

代码示例

import boto3

role_arn = "..."
bucket_name = "..."

sts_client = boto3.client(
    "sts",
    region_name="eu-west-1",
)
sts_response = sts_client.assume_role(
    RoleArn=role_arn,
    RoleSessionName="test-session-name",
)

credentials = sts_response["Credentials"]
session = boto3.session.Session(
    aws_access_key_id=credentials["AccessKeyId"],
    aws_secret_access_key=credentials["SecretAccessKey"],
    aws_session_token=credentials["SessionToken"],
)

s3_client = session.client(
    "s3",
    region_name="eu-south-1",
)

res = s3_client.list_objects_v2(Bucket=bucket_name)
# botocore.exceptions.ClientError
解决方案

这个错误的核心原因是STS临时凭证的区域与目标服务调用区域不匹配。在eu-west-1区域调用AssumeRole获取的凭证,默认绑定该区域的STS终端节点,而S3在eu-south-1区域调用时会使用本地STS终端节点验证凭证,导致凭证失效。

有两种直接的解决方法:

  • 使用全局STS终端节点获取凭证
    将STS客户端的region_name设置为us-east-1(AWS STS全局终端节点所属区域),这样生成的临时凭证可跨区域通用:

    sts_client = boto3.client(
        "sts",
        region_name="us-east-1",  # 切换到全局STS终端节点区域
    )
    
  • 匹配目标区域的STS终端节点
    调用AssumeRole时,直接指定目标服务所在区域(eu-south-1)的STS终端节点,确保凭证与目标区域适配:

    sts_client = boto3.client(
        "sts",
        region_name="eu-south-1",
        endpoint_url="https://sts.eu-south-1.amazonaws.com"
    )
    

额外检查项:

  1. 确认AWS账户B中的角色已配置允许访问目标S3桶的ListObjectsV2权限
  2. 确认临时凭证未过期(STS临时凭证默认有效期1小时)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:59:57