[Python] Why does AWS STS regional endpoint affect when calling an API Gateway in a different...

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple Python script that makes a GET request to a REST API hosted in AWS API Gateway. To authorize the request, I use the temporary credentials obtained by assuming a role (a role that is allowed to invoke the target API).

    According to the AWS documentation, session tokens from regional STS endpoints are valid in all AWS regions. However, I'm seeing different behavior:


    • If I use eu-west-1 as the region when calling assume_role (STS), and then sign the request for API Gateway in eu-south-2 (where the API is hosted), the request fails and I get the following error message {"message":"The security token included in the request is invalid"}


    • If I change the STS client region to eu-south-2, so that it matches the API region, the request succeeds.

    Here is the code:

    import boto3
    import requests
    from aws_requests_auth.aws_auth import AWSRequestsAuth
    from urllib.parse import urlparse

    ROLE_ARN = "..."
    SESSION_NAME = "..."
    API_GATEWAY_ENDPOINT = "..."

    def assume_role(role_arn, session_name, region):
    sts_client = boto3.client('sts', region_name=region)
    response = sts_client.assume_role(RoleArn=role_arn, RoleSessionName=session_name)
    credentials = response['Credentials']
    return credentials

    def call_api(api_url, credentials, region):
    auth = AWSRequestsAuth(aws_access_key=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_token=credentials['SessionToken'],
    aws_host=urlparse(API_GATEWAY_ENDPOINT).netloc,
    aws_region=region,
    aws_service='execute-api')
    response = requests.get(api_url, auth=auth)
    print("Status Code:", response.status_code)
    print("Response Body:", response.text)

    def main():
    creds = assume_role(ROLE_ARN, SESSION_NAME, "eu-west-1")
    call_api(API_GATEWAY_ENDPOINT, creds, "eu-south-2")

    if __name__ == "__main__":
    main()



    Any help clarifying this behavior would be appreciated.

    Continue reading...

Compartilhe esta Página