Aws

AWS IAM Temporary Credentials

Learn how AWS STS issues temporary credentials, how IAM roles and policies control them, and how to use them securely across workloads, CLI profiles, federation, MFA, and accounts.

AWS IAM temporary credentials are short-lived credentials used to authenticate requests to AWS services. They are commonly issued by the AWS Security Token Service (STS) when a user, application, workload, or federated identity assumes an IAM role.

This approach avoids embedding permanent secrets in applications and makes access easier to limit, audit, and refresh.

What Are Temporary Security Credentials?

Temporary security credentials consist of three values:

  • Access key ID: Identifies the temporary credential.
  • Secret access key: A secret used to sign AWS API requests.
  • Session token: An additional token required when using temporary credentials.

The credentials have an expiration time. After the session ends, AWS automatically invalidates them. A tool or SDK must obtain a new session before making further requests.

Temporary credentials are different from an IAM user password, a long-term IAM user access key, and root-user credentials. A password is generally used to sign in to the AWS Management Console. A long-term access key can remain valid until it is rotated or deactivated. Root credentials belong to the entire AWS account and should not be used for routine work. Temporary credentials are issued for a specific session and normally have a shorter lifetime.

Characteristic — Temporary credentials: Expire automatically after a configured session period; require an access key ID, secret access key, and session token; are normally obtained through STS, IAM Identity Center, federation, or a workload role; are suitable for users, applications, and AWS compute services; exposure is limited by session duration and policy scope.

Characteristic — Long-term access keys: Do not expire automatically on a short session schedule; use an access key ID and secret access key without an STS session token; require deliberate rotation or deactivation; are sometimes needed for constrained legacy or external integrations; exposure can provide continuing access until the key is disabled or removed.

Short-lived credentials reduce the risk of leaked, forgotten, or permanently embedded secrets. They do not eliminate risk: an attacker can use valid temporary credentials until they expire or are otherwise constrained. Least privilege, monitoring, and careful session durations remain necessary.

AWS Security Token Service

AWS Security Token Service, or STS, creates temporary security credentials and role sessions. The credentials can sign AWS API requests in the same general way as other AWS credentials, but requests must also include the session token.

STS is available through regional endpoints and a legacy global endpoint. Regional endpoints can reduce latency, support regional service behavior, and make the location used for STS calls explicit. Organizations should choose a regional endpoint strategy that matches their AWS Region, compliance requirements, and SDK or CLI configuration. The global endpoint may use a configured signing Region and can have different regional behavior depending on account settings. Standardize endpoint behavior rather than allowing different applications to make inconsistent assumptions.

AssumeRole: A principal obtains a session for an IAM role in the same account or another account. The caller needs permission to call sts:AssumeRole, and the target role trust policy must trust the caller.

AssumeRoleWithSAML: A SAML 2.0 identity provider authenticates a user and supplies an assertion used to obtain an AWS role session. This is common for workforce federation.

AssumeRoleWithWebIdentity: A workload or user authenticated by an OIDC-compatible identity provider obtains a role session. This supports web identity federation and several workload identity designs.

GetSessionToken: An existing IAM user or root identity obtains a temporary session. It is commonly used to create an MFA-backed session before accessing protected operations.

GetFederationToken: A federated identity obtains delegated, temporary access where this model is appropriate. The caller supplies a policy that limits the federated session.

For modern AWS workloads, IAM roles and federation are generally preferred over IAM user access keys. Roles allow AWS to deliver and rotate temporary credentials without storing a permanent secret in the workload.

IAM Roles and Role Assumption

An IAM role is an AWS identity with permissions that a trusted principal can assume. Assuming a role creates a temporary role session, which acts as a principal when it calls AWS services.

A role has two important policy areas:

  • Trust policy: A resource-based policy attached to the role. It controls which principals may assume the role and which conditions must be satisfied.
  • Permissions policy: An identity-based policy attached to the role. It defines the actions and resources available to the role session.

Both sides matter in cross-account access. The caller must be authorized to call sts:AssumeRole, and the target role must trust that caller. A successful trust decision does not automatically grant access to S3, DynamoDB, or other services; those permissions come from the role's permissions policies and the other applicable policy layers.

Role session attributes

  • Role session name: A caller-supplied identifier that distinguishes sessions in assumed-role ARNs and audit records.
  • Source identity: An identity value associated with a session to improve traceability, including across role assumptions.
  • Session tags: Attributes attached to a session. Policies can use them for attribute-based access control, and CloudTrail can record them.

Role session names and source identity should identify a person, application, job, or ticket where practical. Do not put secrets in these values because they may appear in logs.

Session duration and role chaining

A role administrator sets the role's maximum session duration. A caller can request a shorter duration, but cannot request more than the role and service limits permit. Shorter sessions reduce the useful lifetime of exposed credentials.

Role chaining means assuming a role with credentials that were themselves created by assuming another role. Chained sessions have a shorter maximum duration than a direct role assumption, commonly limited to one hour. Design automation to avoid unnecessary chains or to refresh from an appropriate long-lived source such as an identity provider or workload identity.

External IDs for third parties

An external ID is a value required by a trust policy for a third-party role assumption. It helps prevent the confused deputy problem, where a service provider could accidentally use its authority to access the wrong customer account. Use a unique external ID for each customer relationship and require it in the trust policy.

How Authorization Works for Temporary Credentials

Authentication establishes who is using the credentials. Authorization evaluates whether that principal may perform a requested action on a requested resource.

Role trust policy: Controls who may assume the role. It normally cannot grant access to unrelated AWS service actions, but it can allow the role session to be created.

Role permissions policy: Defines actions and resources the role session may use. It can grant permissions subject to all other policy controls.

Session policy: An optional policy supplied during session creation. It can restrict the resulting session but cannot expand the role's permissions.

Permissions boundary: A maximum-permissions boundary for an IAM identity. It can restrict permissions but does not grant permissions by itself.

Service control policy: An AWS Organizations control applied to an account or organizational unit. It can restrict available permissions across the account but does not grant permissions.

Resource-based policy: A policy on a resource such as an S3 bucket or KMS key. It can allow or deny access to a principal, subject to AWS policy evaluation rules.

Explicit denies override allows. The final result can therefore be limited by the role policy, session policy, permissions boundary, SCP, resource policy, identity policy, or a condition-based deny. Region, resource ARN, encryption requirements, organization membership, network location, MFA context, principal tags, and session tags can all affect the result.

Attribute-based access control

Attribute-based access control, or ABAC, uses attributes instead of writing a separate policy for every identity. For example, a policy can compare a session tag such as Project=Payments with a resource tag of the same name. Principal tags and session tags must be controlled carefully: the trust policy should restrict who may pass or tag sessions, and policies should prevent untrusted callers from selecting privileged attribute values.

Common Temporary Credential Scenarios

Amazon EC2: Attach an instance profile containing an application role. The SDK obtains and refreshes credentials through the instance metadata mechanism. Avoid access keys in AMIs, user data, or application files.

AWS Lambda: Assign an execution role with only the required service permissions. Lambda and the SDK provide temporary credentials; do not place static credentials in environment variables.

Amazon ECS: Use an ECS task role for application calls to AWS services. Keep the task role separate from the task execution role, which is used for operations such as image or log handling.

Amazon EKS: Use IAM roles for service accounts or EKS Pod Identity as appropriate for the cluster and workload. Give each workload only the permissions it needs.

Local development: Use IAM Identity Center profiles or a limited source identity that assumes a role. Avoid personal long-term access keys where possible.

CI/CD: Prefer OIDC or another workload federation method to obtain a narrowly scoped deployment role. Avoid storing permanent AWS keys in pipeline variables.

  • IAM Identity Center users authenticate through a workforce identity system, select an authorized account and permission set, and receive a time-limited role-based session.
  • Cross-account roles support administration, deployment, auditing, and data access without sharing IAM users between accounts.
  • Federated employees can use SAML or another supported identity system to access the AWS Management Console through role sessions.
  • Third-party vendors should use a dedicated constrained role with an external ID and, where practical, MFA or additional conditions.
  • Mobile, browser, and external identity-provider workloads can use web identity federation instead of embedding AWS keys in distributed software.

Using Temporary Credentials with the AWS CLI and SDKs

The AWS CLI and AWS SDKs use a credential provider chain: an ordered process that checks possible credential sources. Depending on the tool and configuration, sources can include explicitly supplied values, environment variables, named profiles, IAM Identity Center, role assumption, container credentials, and EC2 instance metadata.

Environment variables commonly include:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_SESSION_TOKEN
  • AWS_PROFILE
  • AWS_REGION

When temporary credentials are supplied through environment variables, all three credential values are required. Environment variables can override a profile unexpectedly, so inspect them when the CLI or SDK uses the wrong identity.

Assume a role with the AWS CLI

aws sts assume-role --role-arn arn:aws:iam::123456789012:role/ReadOnlyAuditRole --role-session-name audit-review

The caller needs sts:AssumeRole, and the target trust policy must trust the caller. Use the returned access key ID, secret access key, and session token together.

Use a named profile

[profile audit]
role_arn = arn:aws:iam::123456789012:role/ReadOnlyAuditRole
source_profile = base
role_session_name = audit-review
region = us-east-1

The base profile supplies source credentials. The CLI obtains and refreshes the assumed-role credentials as needed. Profiles can also use credential_source for supported workload sources or IAM Identity Center configuration for workforce access.

Manually export a short-lived session

export AWS_ACCESS_KEY_ID="ASIA..."
export AWS_SECRET_ACCESS_KEY="..."
export AWS_SESSION_TOKEN="..."
export AWS_REGION="us-east-1"

Manual exports are appropriate for short-lived testing or constrained workflows. Do not place them in persistent shell profiles, source code, shared scripts, container images, or logs. Unset them after use.

SDKs can refresh credentials automatically when they use a supported role, metadata, container, OIDC, or Identity Center provider. Do not cache the three credential values indefinitely. Applications should use the SDK's refreshable provider and handle expiration errors by reacquiring credentials.

Multi-Factor Authentication and Temporary Credentials

Multi-factor authentication, or MFA, combines a password or other identity factor with a device-generated code. A trust policy or permissions policy can require MFA before a sensitive role assumption or action.

aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/alex --token-code 123456

The resulting session is MFA-backed and can be used where policy conditions require MFA before further role assumption. The MFA context is an authorization attribute; it is not the same thing as the temporary credentials. The session credentials authenticate requests, while the MFA context records that an MFA requirement was satisfied.

Common conditions include aws:MultiFactorAuthPresent, which tests whether MFA was used, and aws:MultiFactorAuthAge, which limits how long ago MFA was satisfied. Apply these conditions carefully to the relevant identity or trust policy.

Credential Lifecycle and Revocation

  1. A user, workload, or identity provider authenticates to an allowed source.
  2. The source calls an STS operation or uses an AWS-managed role delivery mechanism.
  3. STS returns an access key ID, secret access key, session token, and expiration time.
  4. The caller signs AWS API requests with the temporary values.
  5. The CLI or SDK refreshes the session before expiration when its provider supports refresh.
  6. After expiration, the credentials no longer authenticate requests.

Issued temporary credentials normally remain valid until expiration. Changing a trust policy affects future role assumptions, but does not necessarily invalidate an already issued session. To limit future or active access, administrators can change role permissions, attach explicit deny controls, change the trust policy, disable the source identity, or use supported STS session revocation capabilities. These controls have different scope and propagation behavior.

Because immediate invalidation is not always the primary control model, choose a session duration appropriate to the task. Privileged, interactive, and high-risk sessions generally deserve shorter durations than stable service sessions, while applications need enough time to refresh reliably.

Security Best Practices

  • Prefer IAM roles, IAM Identity Center, and federation over long-term IAM user access keys.
  • Apply least privilege separately to each workload, team, environment, and cross-account role.
  • Use the shortest practical session duration.
  • Require MFA for privileged human access and sensitive role assumption.
  • Use a unique external ID for each third-party access relationship.
  • Never place credentials in source code, AMIs, container images, configuration files, user data, or logs.
  • Use Secrets Manager or Systems Manager Parameter Store only when a genuine secret is required. A secret store is not a substitute for a workload role.
  • Monitor role assumptions and API activity with AWS CloudTrail.
  • Use IAM Access Analyzer and policy validation to review cross-account trust and permissions.
  • Deactivate and remove unnecessary IAM user access keys.

Auditing and Monitoring

AWS CloudTrail records role assumptions and activity performed with assumed-role credentials. Useful fields include userIdentity.type, the principal ARN, principal ID, session issuer, role session name, source identity, and session tags.

For an assumed role, the session issuer identifies the IAM role that issued the session, while the role session name helps distinguish the particular caller or job. Review both the original caller and the resulting role session when investigating activity.

Monitor for unusual AssumeRole activity, repeated failed assumptions, abnormal session durations, unexpected source locations, unfamiliar principals, and unexpected use of privileged roles. CloudTrail event history supports point-in-time investigation. CloudWatch Logs, EventBridge rules, and AWS security services can provide centralized analysis, alerting, and automated response.

Practical Configurations

EC2 role trust relationship

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "ec2.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }]
}

This is a trust policy, not the policy that grants S3, DynamoDB, or other service permissions. Attach a separate, narrowly scoped permissions policy to the role and make the role available through an instance profile.

Cross-account trust with an external ID

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"AWS": "arn:aws:iam::210987654321:role/VendorAccessRole"},
    "Action": "sts:AssumeRole",
    "Condition": {"StringEquals": {"sts:ExternalId": "customer-unique-value"}}
  }]
}

The vendor must supply the matching external ID during role assumption. The role should also restrict actions, resources, regions, and session duration.

Troubleshooting Temporary Credentials

AccessDenied when calling sts:AssumeRole

  • Confirm that the caller has sts:AssumeRole.
  • Confirm that the target role trust policy trusts the caller's account, role, user, or service principal.
  • Check external ID, MFA, source IP, principal tag, organization, and other conditions.
  • Check SCPs, permissions boundaries, and explicit denies.
  • Review the denied STS event in CloudTrail and compare its request context with the trust policy.

Expired-token errors

  • Check whether the session duration elapsed.
  • Use an SDK-supported refreshable provider instead of hard-coded values.
  • Remove stale AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN variables when they override a refreshable profile.

EC2 cannot retrieve role credentials

  • Confirm that an instance profile is attached.
  • Inspect instance metadata configuration and application access to the metadata service.
  • Check proxies and network rules that may block metadata access.
  • Check whether static environment credentials take precedence.
  • Verify the role permissions for the intended AWS actions.

Cross-account access is denied

  • Validate account IDs and principal ARNs in the trust policy.
  • Confirm the source principal has sts:AssumeRole.
  • Compare the external ID and other request parameters with trust-policy conditions.
  • Check MFA, tags, organization, and network conditions.
  • Test with a minimally scoped known-good principal and review CloudTrail.

The role session has fewer permissions than expected

  • Evaluate session policies, permissions boundaries, SCPs, and resource policies.
  • Look for explicit denies.
  • Use IAM policy simulation and IAM Access Analyzer policy validation where appropriate.
  • Verify the resource ARN, account, Region, and request conditions.

The CLI uses the wrong identity

aws sts get-caller-identity
  • Inspect environment variables and the value of AWS_PROFILE.
  • Inspect the selected profile's source profile or credential source.
  • Check cached IAM Identity Center or role credentials.
  • Explicitly select the intended profile and verify the account and role.

Exam- and Design-Relevant Notes

  • Temporary credentials always include a session token in addition to the access key ID and secret access key.
  • A role trust policy answers “who may assume this role?” A permissions policy answers “what may the role session do?”
  • A session policy can reduce permissions but cannot expand the role's permissions.
  • Cross-account access requires authorization by the caller and trust by the target role.
  • Role chaining has a shorter session-duration limit than a direct role assumption.
  • Temporary credentials expire, but expiration alone is not a replacement for least privilege, MFA, monitoring, or revocation planning.
  • For EC2, ECS, EKS, and Lambda, use workload roles rather than storing IAM user keys.

Summary

AWS temporary credentials are time-limited access key credentials issued through STS or AWS-managed identity integrations. They provide a safer foundation for human access, federation, automation, and workloads than permanently embedded IAM user keys. Secure designs combine trusted role assumption, least-privilege permissions, short sessions, MFA where needed, careful policy evaluation, automatic refresh, and CloudTrail monitoring.

For related credential concepts, see Security Credentials, Task Credentials, and Credentials.