Sub topic 7
Working with Temporary Credentials and Session Duration
This chapter assumes you can already assume a cross-account role with aws sts assume-role. It also assumes you are comfortable with JSON policies and the AWS CLI. Here you will look at what comes back from that call, how long it stays valid, and how to use it correctly.
What AssumeRole returns
A successful AssumeRole call returns two objects. The first is Credentials, which holds four values:
| Field | Purpose |
|---|---|
| `AccessKeyId` | Identifies the session. It starts with `ASIA`, which marks it as temporary. Long-term user keys start with `AKIA`. |
| `SecretAccessKey` | Signs requests, as with any access key. |
| `SessionToken` | A required third value. AWS rejects requests signed with temporary keys if it is missing. |
| `Expiration` | A UTC timestamp after which the credentials stop working. |
The second object is AssumedRoleUser, which holds an AssumedRoleId and an Arn. The ARN has this shape:
arn:aws:sts::222222222222:assumed-role/ReadOnlyAuditor/audit-sessionThe last segment is the role session name you passed with --role-session-name. It appears in CloudTrail records and in sts get-caller-identity output, so choose a value that identifies the person or system, such as an email prefix or a job ID. A session name must be 2 to 64 characters long. It may contain letters, digits, and the characters =,.@_-.
Using the credentials in a shell
The AWS CLI and SDKs read three environment variables. The following script assumes the role and exports them. It needs jq installed.
#!/usr/bin/env bash
set -euo pipefail
creds=$(aws sts assume-role \
--role-arn arn:aws:iam::222222222222:role/ReadOnlyAuditor \
--role-session-name audit-session \
--output json)
export AWS_ACCESS_KEY_ID=$(echo "$creds" | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo "$creds" | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo "$creds" | jq -r '.Credentials.SessionToken')
echo "Expires at: $(echo "$creds" | jq -r '.Credentials.Expiration')"
aws sts get-caller-identityRun this with source script.sh if you want the exports to stay in your current shell. In a normal subprocess they disappear when the script ends.
Environment variables take precedence over profiles in the CLI's credential chain. If a stale AWS_SESSION_TOKEN is left in your shell, it can break later commands that use a profile. Clear the variables when you finish:
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKENSession duration
Three numbers control how long a session lasts.
| Setting | Where it is set | Allowed values |
|---|---|---|
| Role maximum session duration | The role, in the account that owns it | 1 to 12 hours. The default is 1 hour. |
| `DurationSeconds` | The `AssumeRole` call | 900 seconds (15 minutes) up to the role maximum. The default is 3600 seconds. |
| Role chaining limit | AWS, fixed | 1 hour, whatever the role maximum is |
The caller can ask for less than the role maximum but never more. If you request a duration above the maximum, the call fails with a ValidationError that says the requested DurationSeconds exceeds the MaxSessionDuration set for the role.
An administrator in the role's account raises the maximum like this:
aws iam update-role \
--role-name ReadOnlyAuditor \
--max-session-duration 14400The value is in seconds, so 14400 is 4 hours. A caller can then request a longer session:
aws sts assume-role \
--role-arn arn:aws:iam::222222222222:role/ReadOnlyAuditor \
--role-session-name long-audit \
--duration-seconds 14400Set the maximum to the longest period a legitimate task needs, not to 12 hours by default. A shorter lifetime limits how long a leaked credential is useful.
The lifecycle of a session
The sequence below shows who talks to whom and where the expiry check happens.
Automatic refresh with CLI profiles
Running the script by hand every hour is tedious. A profile with role_arn and source_profile makes the CLI assume the role for you. It caches the credentials under ~/.aws/cli/cache/ and calls AssumeRole again when they are close to expiring. You can set the duration and session name in the same profile:
[profile auditor]
role_arn = arn:aws:iam::222222222222:role/ReadOnlyAuditor
source_profile = default
role_session_name = audit-cli
duration_seconds = 7200
region = us-east-1duration_seconds is subject to the same limits as DurationSeconds. If the role maximum is 1 hour and the profile asks for 7200 seconds, every command with this profile fails.
Verify that the profile works:
aws sts get-caller-identity --profile auditorThe Arn in the output should be an assumed-role/ReadOnlyAuditor/audit-cli ARN in account 222222222222. Most AWS SDKs implement the same refresh logic, so long-running programs that use a profile or the default credential chain keep working without extra code.
Narrowing a session with a session policy
You can pass an inline policy when you assume a role. The session's effective permissions are then the intersection of the role's permissions policy and the session policy. A session policy can only remove access. It can never add access the role does not already have.
aws sts assume-role \
--role-arn arn:aws:iam::222222222222:role/ReadOnlyAuditor \
--role-session-name s3-only \
--policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}'This is useful when a program needs only a small slice of a broad role. For example, a service can give each customer-facing task a session limited to one job.
Expiry, revocation, and common errors
You cannot shorten or extend an existing session. To continue past Expiration, call AssumeRole again and replace the old values. The new call returns new keys.
You also cannot delete a single temporary credential. If a session is compromised, an administrator in the role's account can choose Revoke active sessions on the role in the IAM console. IAM then attaches an inline policy to the role that denies all actions for any session issued before that moment. It uses the aws:TokenIssueTime condition key. New sessions made after that time work normally. Note that if the attacker can still assume the role, they can get a fresh session, so also fix the trust policy or the caller's credentials.
| Symptom | Likely cause |
|---|---|
| `ExpiredToken` | The `Expiration` time has passed. Call `AssumeRole` again. |
| `InvalidClientTokenId` or "security token included in the request is invalid" | `AWS_SESSION_TOKEN` is missing, truncated, or from a different session than the key pair. |
| `ValidationError` about `DurationSeconds` | The request is under 900 seconds, above the role maximum, or above one hour on a chained call. |
| Commands act as the wrong identity | Old `AWS_*` variables override your profile. Run `unset` on them. |
| `AccessDenied` after the role works | A session policy removed the permission, or the role's permissions policy never allowed it. |
Quick checklist
- Export all three values, not only the key pair.
- Pick a session name that identifies the caller.
- Set the role maximum to what the task needs.
- Prefer a CLI profile so refresh is automatic.
- Use a session policy when a task needs less than the whole role.
Exercise
A role has the default maximum session duration. A script runs aws sts assume-role --duration-seconds 7200 against it and fails. Give the cause and two ways to fix it.
Show answer
The default role maximum is 3600 seconds, so a request for 7200 seconds exceeds it and returns a ValidationError. Fix 1: lower the request to 3600 seconds or less. Fix 2: have an administrator in the role's account run aws iam update-role --role-name <name> --max-session-duration 7200 (or higher), then repeat the call. If the call is a chained assume-role, neither fix extends it beyond one hour.
Exercise
You exported AWSACCESSKEYID and AWSSECRETACCESSKEY from an AssumeRole response but not the session token. What happens when you run a command, and why?
Show answer
The request fails with an error such as InvalidClientTokenId. Keys that start with ASIA are temporary, and AWS accepts them only when the matching session token is sent with the request. Export AWSSESSIONTOKEN as well.
Exercise
A session policy allows only s3:ListAllMyBuckets. The role's permissions policy allows s3: and ec2:Describe. Which actions can the session perform?
Show answer
Only s3:ListAllMyBuckets. The effective permissions are the intersection of the role's permissions policy and the session policy, and ec2:Describe* is not in the session policy.