Temporary Credentials with AWS STS

5 minutes 5 Questions

AWS Security Token Service (STS) issues short-lived, limited-privilege credentials made up of an access key ID, a secret access key, and a session token. For the SCS-C03 exam, STS is central to Domain 4 because AWS best practice favors temporary credentials over long-term IAM user access keys. Short-lived credentials limit the damage if they leak. Key API operations include: - AssumeRole: cross-account access, privilege elevation, and service roles. - AssumeRoleWithSAML: federation with corporate identity providers such as Active Directory through AD FS. - AssumeRoleWithWebIdentity: OIDC providers such as Amazon Cognito, Google, or GitHub Actions. - GetSessionToken: MFA-protected API access for IAM users. - GetFederationToken: custom identity broker federation. Role sessions last from 15 minutes up to 12 hours, with a default of 1 hour. Role chaining caps sessions at 1 hour. GetSessionToken credentials can last up to 36 hours. A role's trust policy defines who may assume it, while its permissions policies define what the session can do. Session policies passed during AssumeRole can only restrict effective permissions, because the result is the intersection of the policies and never an expansion. When granting third parties access, use the sts:ExternalId condition to prevent the confused deputy problem. Use the aws:MultiFactorAuthPresent condition to enforce MFA. Source identity and session tags support attribute-based access control (ABAC) and improve traceability in CloudTrail. Revocation is a frequent exam topic. Issued temporary credentials cannot be individually canceled before they expire. Instead, the IAM console's "Revoke active sessions" feature attaches an inline deny policy that uses the aws:TokenIssueTime condition. This blocks every session issued before a chosen time. Changing or removing the role's permissions policies also affects existing sessions. Many AWS services consume STS credentials automatically: - EC2 instance profiles deliver rotating credentials through the Instance Metadata Service, where IMDSv2 is preferred. - Lambda execution roles and ECS task roles supply credentials to workloads. - IAM Identity Center issues temporary credentials to workforce users. For lower latency and better resilience, use regional STS endpoints. Monitor AssumeRole events in CloudTrail to detect anomalous access patterns.

Temporary Credentials with AWS STS: A Complete Guide for the AWS Certified Security Specialty Exam

Introduction
AWS Security Token Service (AWS STS) is the service that issues temporary, limited-privilege security credentials to IAM users, federated users, AWS services, and applications. It sits at the core of nearly every secure access pattern in AWS. Roles, federation, cross-account access, EC2 instance profiles, Lambda execution roles, IAM Identity Center, and Amazon Cognito all depend on STS. For the AWS Certified Security - Specialty exam, you must understand how STS works, when to use each API, how to control and limit sessions, and how to respond when temporary credentials are compromised.

Why Temporary Credentials Are Important
1. Reduced blast radius: Long-term access keys (prefix AKIA) stay valid until someone rotates or deletes them. Temporary credentials (prefix ASIA) expire on their own, often within minutes or hours, so a leaked credential has a short useful life.
2. No secrets embedded in code: Applications on EC2, ECS, EKS, and Lambda receive credentials from the platform at runtime. Developers never need to store access keys in source code, configuration files, or AMIs.
3. Least privilege and separation of duties: Users can work with minimal everyday permissions and assume a privileged role only when needed, often with MFA required.
4. Centralized identity: Federation (SAML 2.0, OIDC, IAM Identity Center) lets organizations keep identities in a corporate IdP rather than creating IAM users in every account.
5. Cross-account access: Roles let principals in one account work in another account in a controlled, auditable way, which is the foundation of multi-account strategies with AWS Organizations.
6. Auditability: Every STS call and every action taken with a role session is logged in AWS CloudTrail, including the role session name and optional source identity.

What AWS STS Is
AWS STS is a global web service with a global endpoint (sts.amazonaws.com) and regional endpoints (for example, sts.eu-west-1.amazonaws.com). AWS recommends regional endpoints to reduce latency, add redundancy, and keep tokens valid in all Regions. Every set of temporary credentials contains four parts:
- Access Key ID (begins with ASIA)
- Secret Access Key
- Session Token (must be sent with every request)
- Expiration timestamp

Temporary credentials cannot be extended after issue. When they expire, the caller must request new ones. AWS SDKs and the CLI handle this refresh for roles automatically.

The Key STS API Operations
AssumeRole
- Used by an IAM user or role (already authenticated with AWS) to assume another role, in the same or a different account.
- Default session: 1 hour. Range: 15 minutes up to the role's maximum session duration, which can be set from 1 to 12 hours.
- Supports MFA (SerialNumber and TokenCode parameters), session policies, session tags, external ID, and source identity.
- Role chaining (using role credentials to assume another role) is limited to a 1-hour maximum session.

AssumeRoleWithSAML
- Used for federation with a SAML 2.0 IdP such as Active Directory Federation Services, Okta, or Azure AD (Microsoft Entra ID).
- The caller presents a SAML assertion; no AWS credentials are needed to call it.
- Session length is controlled by the SAML attribute SessionDuration and the role maximum session duration (up to 12 hours).
- Trust policy uses the condition key SAML:aud and a SAML identity provider principal.

AssumeRoleWithWebIdentity
- Used for OIDC federation with providers such as Amazon Cognito, Google, Facebook, Login with Amazon, GitHub Actions, or EKS service accounts (IRSA).
- No AWS credentials are needed to call it; the caller presents a JWT token.
- AWS recommends Amazon Cognito identity pools for mobile and web apps rather than calling this API in client code.

GetSessionToken
- Used by an IAM user (or root) to get temporary credentials, most commonly to satisfy MFA requirements for CLI or API access.
- Duration: 15 minutes to 36 hours for IAM users (default 12 hours); root user sessions are limited to 1 hour.
- The resulting credentials carry the same permissions as the calling user. They cannot call IAM APIs unless MFA is included, and they can call only AssumeRole and GetCallerIdentity among STS APIs.

GetFederationToken
- Used by a long-term IAM user credential (for example, a custom identity broker) to issue credentials to a federated user.
- Duration: 15 minutes to 36 hours (root limited to 1 hour).
- Permissions are the intersection of the calling user's policies and the session policy passed in the call. Supports no MFA in the call.
- Largely replaced by roles and IAM Identity Center in modern designs, but still tested as the custom identity broker pattern.

Supporting operations
- GetCallerIdentity: returns the account, ARN, and user ID of the caller. It needs no permissions and cannot be denied by policy.
- DecodeAuthorizationMessage: decodes encoded authorization failure messages (common with EC2) to show why a request was denied. Requires the sts:DecodeAuthorizationMessage permission.
- GetAccessKeyInfo: returns the account ID that owns a given access key ID, useful in incident response when a key is found exposed.

How It Works: The Role Assumption Flow
1. A principal calls sts:AssumeRole with the role ARN and a role session name.
2. STS evaluates two things: the trust policy on the role (who may assume it) and the identity-based policy of the caller (whether the caller is allowed sts:AssumeRole on that role ARN). For cross-account access, both sides must allow it.
3. STS checks any conditions, such as aws:MultiFactorAuthPresent, sts:ExternalId, aws:SourceIp, aws:PrincipalOrgID, or session tags.
4. STS returns temporary credentials. The effective permissions are the role's permissions policies, intersected with any session policies passed in the call and bounded by any permissions boundary on the role and any SCPs or RCPs applied in AWS Organizations.
5. The caller signs requests with the temporary credentials and session token until expiration.

Trust policies vs. permissions policies
- The trust policy is a resource-based policy on the role. It names the Principal (an account, user, role, service such as ec2.amazonaws.com, or a federated IdP) allowed to call the assume action.
- The permissions policy defines what the session can do once the role is assumed.
- A common exam trap: trusting the account root ARN (arn:aws:iam::111122223333:root) means the role trusts the account, and that account's administrators then delegate access through IAM policies. It does not mean only the root user can assume the role.

Session policies
Inline or managed policies passed in AssumeRole, AssumeRoleWithSAML, AssumeRoleWithWebIdentity, or GetFederationToken. They can only restrict permissions further; they never grant more than the role or user already has.

Session tags and ABAC
Session tags are key-value pairs passed during role assumption (or by a SAML/OIDC IdP). They appear as aws:PrincipalTag and support attribute-based access control. Transitive tags persist through role chaining. The caller needs the sts:TagSession permission in the trust policy.

Source identity
The sts:SourceIdentity value is set when the role is first assumed and persists across role chaining. It cannot be changed in later sessions, giving a reliable way to trace actions back to the original human identity in CloudTrail.

External ID and the confused deputy problem
When granting a third party (such as a SaaS monitoring vendor) access to your account, add a condition requiring sts:ExternalId in the role trust policy. The vendor supplies a unique ID per customer, which prevents another customer of the vendor from tricking it into accessing your account. For AWS service principals, the equivalent protections are the aws:SourceArn and aws:SourceAccount condition keys.

Requiring MFA
- Add Condition: Bool aws:MultiFactorAuthPresent true to the trust policy of sensitive roles.
- Use NumericLessThan aws:MultiFactorAuthAge to require recent MFA.
- For CLI users, MFA is supplied through GetSessionToken or the mfa_serial setting in the CLI profile for AssumeRole.
- Note that aws:MultiFactorAuthPresent is absent (not false) for requests signed with long-term keys, so prefer BoolIfExists with a Deny, or Bool true with an Allow.

Service integrations that use STS
- EC2 instance profiles: credentials delivered through the Instance Metadata Service. Enforce IMDSv2 (session-oriented, token-based) to defend against SSRF attacks. Credentials rotate automatically before expiry.
- Lambda execution roles and ECS task roles: credentials injected into the runtime environment.
- EKS: IAM Roles for Service Accounts (IRSA, using AssumeRoleWithWebIdentity) and EKS Pod Identity.
- IAM Identity Center: permission sets create roles in member accounts; users receive short-term credentials through the portal or CLI.
- Amazon Cognito identity pools: exchange user pool or social tokens for AWS credentials mapped to authenticated or unauthenticated roles.
- IAM Roles Anywhere: workloads outside AWS (on-premises servers) use X.509 certificates from a trusted CA to obtain temporary credentials rather than long-term access keys.

Revoking Temporary Credentials
Temporary credentials cannot be deleted or invalidated once issued; they remain valid until expiry. To respond to compromise:
- For a role, use Revoke active sessions in the IAM console. This attaches an inline policy named AWSRevokeOlderSessions that denies all actions when aws:TokenIssueTime is older than the current time. New sessions continue to work.
- Alternatively, write a deny policy with an aws:TokenIssueTime condition yourself, or remove permissions from the role.
- For credentials from GetSessionToken or GetFederationToken, deny or remove permissions on the IAM user who created them (deleting the user's access key does not invalidate already-issued session credentials).
- For EC2 instance credentials, also consider the condition keys aws:EC2InstanceSourceVPC and aws:EC2InstanceSourcePrivateIPv4 to block use of stolen instance credentials from outside the instance's network. Amazon GuardDuty detects instance credential exfiltration (finding type UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration).

Regional endpoints and token validity
Session tokens from the global endpoint are valid by default only in Regions enabled by default. To use them in opt-in Regions, either use a regional STS endpoint or change the global endpoint token setting to version 2 tokens (valid in all Regions, but longer). STS regional endpoints can be deactivated per Region in account settings.

Logging and Monitoring
- CloudTrail records AssumeRole, AssumeRoleWithSAML, AssumeRoleWithWebIdentity, GetSessionToken, and GetFederationToken events.
- For cross-account role assumption, the AssumeRole event is logged in both the calling account and the role-owning account.
- The userIdentity element of later events shows type AssumedRole, the session name, and the sessionIssuer, letting you trace actions back to the original identity. Use a meaningful role session name (for example, the username) and enforce it with the sts:RoleSessionName condition key.
- CloudTrail Lake and Amazon Athena queries can correlate the accessKeyId of temporary credentials across events.

Exam Tips: Answering Questions on Temporary Credentials with AWS STS
1. Prefer roles over access keys. When an answer choice embeds IAM user access keys in an application, on an EC2 instance, or in a third-party tool, it is almost always wrong. Choose instance profiles, task roles, execution roles, IAM Roles Anywhere, or cross-account roles.
2. Match the API to the scenario. SAML corporate IdP = AssumeRoleWithSAML. Mobile or web app with social login = Amazon Cognito (AssumeRoleWithWebIdentity behind the scenes). MFA for CLI using an IAM user = GetSessionToken. Custom identity broker with an IAM user = GetFederationToken. Cross-account or privilege elevation = AssumeRole.
3. Third-party access means External ID. Any question about a vendor or SaaS provider accessing your account, or about the confused deputy, points to sts:ExternalId in the trust policy.
4. Know the durations. AssumeRole: 15 minutes to 12 hours (default 1 hour). Role chaining: maximum 1 hour. GetSessionToken and GetFederationToken: up to 36 hours (root: 1 hour). If a question says sessions end after 1 hour despite a 12-hour maximum, suspect role chaining or a DurationSeconds value not set in the request.
5. Revocation questions. If temporary credentials are leaked, the correct answer is to revoke active sessions (the aws:TokenIssueTime deny policy) or deny permissions, not to delete the role or rotate a key and wait. Remember that deleting an IAM user's access key does not end sessions already created from it.
6. Access denied when assuming a role. Check both the trust policy of the target role and the identity policy of the caller. For cross-account, both accounts must allow it. Also check SCPs, permissions boundaries, MFA conditions, and sts:TagSession if tags are passed.
7. Session policies only restrict. If an answer claims a session policy grants additional permissions beyond the role, it is incorrect.
8. Tracing actions to a person. Look for answers that use role session names, sts:SourceIdentity, or session tags plus CloudTrail. Source identity is the best choice when tracing must survive role chaining and cannot be altered.
9. EC2 credential theft. Answers involving IMDSv2 enforcement, the hop limit, GuardDuty InstanceCredentialExfiltration findings, and the aws:EC2InstanceSourceVPC condition key are strong choices.
10. Opt-in Region errors. If temporary credentials fail with an invalid token error in a newly enabled Region, the fix is to use regional STS endpoints or switch the global endpoint to version 2 tokens.
11. Unknown leaked key. To identify which account owns an exposed access key, use sts:GetAccessKeyInfo. To identify the current caller, use sts:GetCallerIdentity, which cannot be blocked by IAM policies.
12. Encoded error messages. When a question shows an encoded authorization failure message, the answer is sts:DecodeAuthorizationMessage.
13. Watch the keywords. Phrases such as least operational overhead, no long-term credentials, short-lived, federated, cross-account, and corporate directory all signal an STS-based solution, most often with IAM Identity Center or IAM roles.
14. Eliminate distractors. Remove options that create an IAM user per external person, share root credentials, store keys in Parameter Store for EC2 use, or extend credential lifetime after issue. These conflict with AWS best practice and are typical wrong answers.

Summary
AWS STS issues short-lived credentials that underpin roles, federation, and service access throughout AWS. Master the trust policy and permissions policy relationship, the purpose and limits of each STS API, protections such as MFA, External ID, session policies, source identity, and session tags, and the methods to revoke and investigate compromised sessions. With these concepts, you will be able to identify the most secure, least-privilege answer in exam scenarios involving temporary credentials.
Test mode:
More Temporary Credentials with AWS STS questions
23 questions (total)