AWS STS Temporary Credentials Explained
AWS Security Token Service (STS) issues temporary credentials that let users, applications, and services access AWS resources without long-lived access keys. If you have ever used an IAM role on EC2, run a Lambda function, or assumed a cross-account role, STS generated the credentials behind the scenes.
Simple explanation
Think of STS like a hotel front desk. You show your ID (your existing credentials or identity token), the clerk checks the reservation (the role’s trust policy), and if everything matches, you get a key card (temporary credentials). That key card opens specific doors (permissions) and stops working at checkout time (expiration). You never get a master key, and if you lose the card, it expires on its own.
STS is a global AWS service that hands out short-lived credentials on demand. Instead of giving a person or application a permanent password, STS creates a temporary badge that works for a set period and then stops working automatically.
The relationship between IAM users, IAM roles, and STS works like this:
- An IAM user has permanent credentials (an access key pair). These credentials identify a specific person or service account and do not expire on their own.
- An IAM role has no permanent credentials. A role defines what permissions are available, but nothing can use those permissions until someone assumes the role.
- STS is the bridge. When a user, service, or external identity assumes a role, STS checks the role’s trust policy, and if allowed, issues temporary credentials scoped to that role’s permissions.
The result is that the caller gets time-limited access without anyone storing long-term secrets.
Why STS matters
Temporary credentials are safer than long-lived access keys for one core reason: they expire. A leaked temporary credential is useful to an attacker only until the session ends. A leaked access key is useful until someone notices and revokes it, which could be hours, days, or months.
- No rotation required. Long-lived keys must be rotated on a schedule. Temporary credentials rotate themselves every time a new session starts.
- No revocation delay. If you suspect a compromise, the credential expires on its own. You can also revoke all sessions for a role immediately through IAM.
- Scoped permissions. Each STS session can be further restricted with session policies, limiting what the temporary credentials can do beyond the role’s base permissions.
- Audit trail. Every STS call is logged in CloudTrail, so you can trace exactly who assumed which role and when.
If you are still using long-lived access keys in production workloads, treat migrating to role-based temporary credentials as a high-priority security improvement. A single leaked access key can give an attacker persistent access to your account until you discover and delete it.
How STS works
The flow from request to API call follows these steps:
- A caller requests temporary credentials. The caller can be an IAM user, another role, or an external identity (like a GitHub Actions workflow). The request goes to the STS API with details about which role to assume.
- STS checks the trust policy. The target role has a trust policy that lists who is allowed to assume it. STS verifies the caller’s identity against that policy. If the caller is not listed, the request is denied.
- STS issues temporary credentials. If the trust check passes, STS generates a fresh set of credentials: an access key ID, a secret access key, and a session token. These credentials have a fixed expiration time.
- The caller uses the temporary credentials. The caller includes all three credential components when making AWS API calls. AWS validates the credentials and checks the role’s permissions policy for each request.
- The credentials expire. After the session duration elapses, the credentials stop working. The caller must request new credentials to continue.
For services like EC2 and Lambda, steps 1 through 3 happen automatically. The service calls STS on your behalf and delivers the credentials to your code through instance metadata or environment variables.
What temporary credentials contain
Every set of temporary credentials from STS contains three components:
- Access Key ID starts with
ASIA, which distinguishes it from long-lived user keys that start withAKIA. See access keys explained for more on key prefixes. - Secret Access Key is used to sign API requests, just like a permanent secret key.
- Session Token is a long string that must accompany every API request. AWS uses it to validate the temporary session and link it back to the assumed role.
All three components are required together. An API call that includes the access key ID and secret but omits the session token will fail with an authentication error. This is one of the most common mistakes when switching from long-lived keys to temporary credentials.
Main STS operations
AssumeRole
AssumeRole is the most commonly used STS API. It exchanges your current credentials for temporary credentials that belong to a different IAM role. AWS checks the target role’s trust policy, and if your identity is allowed, issues a new set of credentials scoped to that role’s permissions.
aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/DeployRole \
--role-session-name "deploy-session"The response includes the three credential components plus an expiration timestamp:
{
"Credentials": {
"AccessKeyId": "ASIAEXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/EXAMPLEKEY",
"SessionToken": "AQoDYXdzEJr...(truncated)",
"Expiration": "2026-01-15T12:00:00Z"
},
"AssumedRoleUser": {
"AssumedRoleId": "AROAEXAMPLE:deploy-session",
"Arn": "arn:aws:sts::123456789012:assumed-role/DeployRole/deploy-session"
}
}To use these credentials in your terminal, export them as environment variables:
export AWS_ACCESS_KEY_ID="ASIAEXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/EXAMPLEKEY"
export AWS_SESSION_TOKEN="AQoDYXdzEJr...(truncated)"
# Verify the assumed identity
aws sts get-caller-identityBy default, AssumeRole sessions last 1 hour. You can request up to the role’s MaxSessionDuration setting (configurable up to 12 hours) using the —duration-seconds flag. For the full mechanics of role assumption including trust policies and cross-account patterns, see role assumption in AWS.
GetSessionToken
GetSessionToken returns temporary credentials for your own IAM user identity, without switching to a different role. The main use case is satisfying MFA requirements.
When an IAM policy includes an MFA condition (aws:MultiFactorAuthPresent), regular access key calls fail because they carry no MFA proof. Calling GetSessionToken with your MFA code produces temporary credentials that include MFA context, satisfying the condition.
aws sts get-session-token \
--serial-number arn:aws:iam::123456789012:mfa/alice \
--token-code 123456 \
--duration-seconds 43200The —serial-number is the ARN of the user’s MFA device. The —token-code is the current 6-digit code from the authenticator app. The session above lasts 12 hours (43200 seconds).
Duration limits for GetSessionToken: IAM users can request up to 36 hours. The root user is capped at 1 hour.
GetCallerIdentity
GetCallerIdentity returns the account ID, ARN, and unique identifier for whichever credentials are currently active. It requires no specific permissions and always succeeds for any valid credential. Use it whenever you need to confirm which identity the CLI or SDK is using.
aws sts get-caller-identity{
"UserId": "AROAEXAMPLE:deploy-session",
"Account": "123456789012",
"Arn": "arn:aws:sts::123456789012:assumed-role/DeployRole/deploy-session"
}Think of GetCallerIdentity like asking “who am I right now?” When you are troubleshooting a permissions error, the first question to answer is whether you are even using the credentials you think you are. This command answers that instantly, and it never fails due to permissions.
This is the first command to run when debugging access denied errors. If the ARN is not what you expect, your credentials are pointing to the wrong identity. Check your environment variables, CLI profile, and credential file. See managing IAM with the AWS CLI for how profile resolution works.
AssumeRoleWithWebIdentity and AssumeRoleWithSAML
These two APIs work like AssumeRole but accept an external identity token instead of AWS credentials:
- AssumeRoleWithWebIdentity accepts an OIDC token from providers like GitHub Actions, Google, or Amazon Cognito. This is how CI/CD pipelines and Kubernetes pods get AWS credentials without storing access keys.
- AssumeRoleWithSAML accepts a SAML assertion from corporate identity providers (Okta, Azure AD, ADFS). This is how enterprise SSO users get AWS console and CLI access.
Both follow the same pattern: the role’s trust policy names the external identity provider, and STS verifies the token before issuing temporary credentials. Maximum session duration is 12 hours for both.
When to use STS
Most of the time, STS works behind the scenes without you calling it directly. Here are the common scenarios and how STS fits in.
You rarely talk to STS yourself. In most cases, AWS services and SDKs call STS for you. Just as you do not need to manually negotiate a TLS handshake to browse a website, you do not need to manually call STS to use temporary credentials on most AWS services.
EC2 instance profiles
When you attach an IAM role to an EC2 instance, AWS calls STS automatically and delivers temporary credentials through the Instance Metadata Service (IMDS). Your application code uses the SDK, which fetches and refreshes these credentials without any STS calls in your code.
Lambda execution roles
Each Lambda function has an execution role. When the function runs, Lambda calls STS to get temporary credentials and injects them as environment variables. Your function code picks them up through the SDK automatically.
ECS and EKS workloads
ECS tasks use task roles, and EKS pods can use IAM Roles for Service Accounts (IRSA). Both mechanisms call STS behind the scenes to deliver scoped temporary credentials to each container or pod.
For EC2, Lambda, ECS, and EKS workloads, you never need to call STS yourself. The service handles credential generation and refresh automatically. You only call STS directly for cross-account access, MFA flows, or federation from outside AWS.
Cross-account access
When an identity in Account A needs to access resources in Account B, it assumes a role in Account B using AssumeRole. The trust policy on the Account B role grants access to Account A. This is the standard pattern for multi-account setups in AWS Organizations.
GitHub Actions and OIDC federation
CI/CD pipelines can use AssumeRoleWithWebIdentity to get AWS credentials from a GitHub Actions OIDC token. This avoids storing long-lived access keys as repository secrets. The trust policy on the role restricts which repository, branch, or environment can assume it.
MFA-protected operations for IAM users
IAM users who need to perform sensitive operations protected by MFA conditions call GetSessionToken with their MFA code. The resulting temporary credentials carry MFA context, allowing the user to perform actions that require aws:MultiFactorAuthPresent.
STS vs IAM roles vs access keys
Access keys are like a house key that never changes. Anyone who copies it has permanent access. An IAM role is like a locked room with a sign on the door listing who is allowed in. STS is the security guard who checks the list, and if you qualify, hands you a visitor pass that expires at the end of the day.
| Concept | What it is | Credential lifetime | Best for |
|---|---|---|---|
| Access keys | Permanent credentials tied to an IAM user | Never expires (until manually revoked) | Local development only; avoid in production |
| IAM roles | A set of permissions with a trust policy, but no permanent credentials | N/A (roles themselves have no credentials) | Defining what permissions a workload or person should have |
| STS temporary credentials | Short-lived credentials issued when someone assumes a role | 1 to 12 hours (configurable) | All production workloads, cross-account access, federation |
The key insight: IAM roles define permissions, and STS provides the credentials to use those permissions. Access keys bypass this system entirely by giving permanent credentials to an IAM user. For why that is a problem in production, see why long-lived access keys are dangerous.
How SDKs find credentials
AWS SDKs (Python/Boto3, JavaScript, Go, Java, .NET, and others) each implement a credential provider chain that checks multiple sources in sequence until it finds valid credentials. The exact order varies by SDK and version, but the common sources across most SDKs include:
- Environment variables such as
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY, andAWS_SESSION_TOKEN - Shared credentials and config files at
~/.aws/credentialsand~/.aws/config - Container credentials used by ECS task roles and EKS pod roles
- Instance metadata on EC2, providing credentials from the instance profile via IMDS
Check the documentation for your specific SDK to confirm the exact resolution order. The important point is that when your code runs on an AWS compute service with an attached role, the SDK finds and refreshes temporary credentials automatically. You do not need to call STS in your application code.
Common mistakes
- Omitting the session token. Temporary credentials require all three components: access key ID, secret access key, and session token. Forgetting the session token causes authentication failures that look similar to invalid key errors.
- Not checking which identity is active. Credential resolution can be surprising when multiple sources are configured. Run
aws sts get-caller-identitybefore debugging permission errors to confirm you are using the identity you expect. - Letting sessions expire during long jobs. The default 1-hour session is too short for many batch jobs. Either increase
MaxSessionDurationon the role or ensure your code refreshes credentials before they expire. - Using generic session names. The role session name appears in CloudTrail logs as part of the assumed-role ARN. A name like “session1” makes it difficult to trace which job or user generated specific API calls. Use descriptive names.
- Confusing AssumeRole with GetSessionToken.
AssumeRolegives you credentials for a different role.GetSessionTokengives you temporary credentials for your current user identity with MFA context. They are not interchangeable. - Storing temporary credentials in code or config files. Temporary credentials should be obtained at runtime, not hardcoded. Use Secrets Manager for any secrets your application needs, and let the SDK handle STS credentials automatically.
Summary
- AWS STS issues temporary credentials (access key ID, secret access key, and session token) that expire automatically.
AssumeRolegets credentials for a different IAM role.GetSessionTokengets temporary credentials for your own identity with MFA context.GetCallerIdentitytells you which identity is active. It is the first debugging step for access errors.- EC2 instance profiles, Lambda execution roles, and ECS/EKS task roles all use STS automatically behind the scenes.
- Temporary credentials are safer than access keys because they expire, require no rotation, and leave a clear audit trail.
Frequently asked questions
How long do STS temporary credentials last?
AssumeRole credentials default to 1 hour and can be extended up to 12 hours by configuring MaxSessionDuration on the role. GetSessionToken credentials default to 12 hours for IAM users, with a maximum of 36 hours. For the root user, GetSessionToken is capped at 1 hour.
What are the three parts of AWS temporary credentials?
An access key ID (starting with ASIA), a secret access key, and a session token. All three must be included with every API request. If you omit the session token, the call fails with an authentication error.
What is the difference between AssumeRole and GetSessionToken?
AssumeRole gives you temporary credentials for a different IAM role with its own permissions. GetSessionToken gives you temporary credentials for your existing IAM user identity, typically to satisfy MFA requirements. They serve different purposes and are not interchangeable.
Can I extend STS credentials before they expire?
No. You cannot extend or renew existing credentials. You call AssumeRole or GetSessionToken again to get a fresh set before the current ones expire. AWS SDKs handle this refresh automatically when using role-based credential sources.
How do I check which AWS identity my CLI is using?
Run aws sts get-caller-identity. It returns the account ID, user or role ARN, and unique identifier for whatever credentials are currently active. This call always succeeds for any valid credential.