Eloy Ruiz
Eloy Ruiz

Reputation: 767

Configure AWS for assuming role with web identity in EC2

I'm trying to run this command from an EC2 instance:

aws sts assume-role-with-web-identity --role-arn "arn:aws:iam::123456789012:role/EC2-Role" --role-session-name "test-session" --web-identity-token file:///home/ubuntu/utils/web-identity-token.jwt

But all I get is "Not authorized to perform sts:AssumeRoleWithWebIdentity".

My EC2 Instance has the role EC2-Role attached.

I get the web-identity-token.jwt using that script:

#! /bin/bash
SERVICE_ACCOUNT="just-a-service-account@test-20240702122400.iam.gserviceaccount.com"
AUDICENCES="example-audience.apps.googleusercontent.com"
OUTPUT_FILE_PATH="/home/ubuntu/utils/web-identity-token.jwt"
gcloud auth print-identity-token --impersonate-service-account $SERVICE_ACCOUNT --audiences=$AUDIENCES  > $OUTPUT_FILE_PATH

I created a user called Server-User with AdministratorAccess policy in order to let him do anything just for test purposes. Then I runned:

$ aws configure
AWS Access Key ID [****************H6ZT]: 
AWS Secret Access Key [****************UmLI]: 
Default region name [us-west-2]: 
Default output format [json]:

My AWS caller identity is this:

{
    "UserId": "****TDWA",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/Server-User"
}

The EC2-Role has AdministratorAccess permissions and this Trust relationship:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Federated": "accounts.google.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
                "StringEquals": {
                    "accounts.google.com:aud": "googleaudienceexample"
                }
            }
        }
    ]
}

What am I doing wrong?

Upvotes: 0

Views: 59

Answers (1)

Eloy Ruiz
Eloy Ruiz

Reputation: 767

I was having an error mislead by the field names in the JWT. There is a field called "aud" which can make you think this is the aud-ience but actually you need the value in the field "sub".

Here's an example of what I'm telling:

{
  "aud": "xxxxxxxxxxx.apps.googleusercontent.com",
  "azp": "yyyyyyyyyyyyyyyyyyyyy",
  "exp": 1725271410,
  "iat": 1725267810,
  "iss": "https://accounts.google.com",
  "sub": "--this is the data you need--"
}

Then use this value into the corresponding field of the Trust Relationship.

Upvotes: 0

Related Questions