This chapter covers AWS Security Token Service (STS) and the AssumeRole API, which is fundamental for managing temporary credentials in AWS. You will learn how STS works internally, how to configure cross-account access and federation, and the exact parameters and limits tested on the DVA-C02 exam. Approximately 10-15% of exam questions touch on STS, IAM roles, and temporary credentials, making this a critical topic for the Security domain (Objective 2.1).
Jump to a section
Imagine a secure office building where employees have permanent badges that grant access to all floors. However, the company also has contractors and partners who need temporary access. Instead of giving them permanent badges, the company issues guest passes at the front desk. The guest pass is valid for a limited time (e.g., 8 hours) and only grants access to specific floors needed for their work. To get a guest pass, a contractor must present a valid ID (like an external identity) and be sponsored by an employee with authority (like an IAM role). The front desk (like AWS STS) creates the guest pass, which includes a photo and expiration time. The contractor uses this pass to enter the building and access only the permitted areas. When the pass expires, it becomes worthless—even if someone finds it later. Similarly, AWS STS issues temporary credentials that expire and have limited permissions. The key mechanism: the front desk does not store the guest pass; it just issues it. The contractor holds the pass and presents it for entry. If the contractor tries to access a restricted area, the door lock checks the pass's permissions and denies entry. The building manager can also revoke passes early by invalidating a session. This mirrors how AWS STS works: you call AssumeRole to get temporary credentials, which include an access key ID, secret access key, and session token. The session token is like the photo on the pass—it must be presented with the credentials to verify they are still valid. Without the session token, the credentials are rejected, just like a guest pass without a photo would be rejected by security.
What is AWS STS and Why It Exists
AWS Security Token Service (STS) is a web service that enables you to request temporary, limited-privilege credentials for IAM users or federated users. Temporary credentials are critical for security because they reduce the risk of long-term credential exposure. Instead of embedding long-term access keys in applications, you request temporary credentials that automatically expire. STS is the backbone of cross-account access, role-based access for EC2 instances, and identity federation with external identity providers.
How AssumeRole Works Internally
The AssumeRole API is the primary mechanism to obtain temporary credentials for a role. The caller must have permissions to call sts:AssumeRole on the target role. The target role's trust policy must grant the caller (or the caller's account) permission to assume the role. The flow:
The caller sends an AssumeRole request to STS, specifying:
RoleArn: The ARN of the role to assume.
RoleSessionName: A unique identifier for the session (used in CloudTrail logs).
DurationSeconds: How long the credentials are valid (default 3600 seconds, max 43200 seconds for roles).
Policy: An optional inline session policy to further restrict permissions.
ExternalId: A unique identifier required by the role's trust policy (for cross-account access).
SerialNumber and TokenCode: For MFA-protected role assumption.
STS validates the caller's permissions (via the caller's IAM policy) and the role's trust policy. If both allow, STS generates temporary credentials:
AccessKeyId: A temporary access key ID (starts with ASIA).
SecretAccessKey: A temporary secret key.
SessionToken: A token that must be included in all subsequent requests.
Expiration: The timestamp when the credentials expire.
The caller receives the credentials and uses them to make AWS API calls. Each request must include the session token, which STS uses to verify the credentials are still valid and have not been revoked.
When the expiration time is reached, the credentials become invalid. The caller must request new credentials before expiration to maintain access. There is no automatic renewal; the application must handle refreshing.
Key Components, Values, Defaults, and Timers
Default session duration: 1 hour (3600 seconds).
Maximum session duration: 12 hours (43200 seconds) for IAM roles; 1 hour (3600 seconds) for federated users via GetFederationToken.
Minimum session duration: 900 seconds (15 minutes).
Session token length: Approximately 200-400 characters (base64-encoded).
Expiration format: ISO 8601 timestamp (e.g., 2025-12-31T23:59:59Z).
AssumeRole API rate limits: 100 requests per second per account (soft limit).
Configuration and Verification Commands
To create a role that can be assumed:
Role trust policy (example allowing an AWS account to assume the role):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:root"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "my-external-id"
}
}
}
]
}IAM policy attached to the role (example granting S3 read access):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-bucket/*"
}
]
}CLI command to assume the role:
aws sts assume-role --role-arn "arn:aws:iam::123456789012:role/MyRole" --role-session-name "TestSession"Sample output:
{
"Credentials": {
"AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"SessionToken": "IQoJb3JpZ2luX2VjEHcaCXVzLWVhc3QtMSJHMEUCIQEXAMPLE...",
"Expiration": "2025-12-31T23:59:59Z"
},
"AssumedRoleUser": {
"AssumedRoleId": "AROA1234567890EXAMPLE:TestSession",
"Arn": "arn:aws:sts::123456789012:assumed-role/MyRole/TestSession"
},
"PackedPolicySize": 6
}How STS Interacts with Related Technologies
IAM Roles for EC2: An EC2 instance profile allows the instance to assume a role automatically. The instance calls the EC2 metadata service (169.254.169.254/latest/meta-data/iam/security-credentials/) to get temporary credentials. The credentials are rotated automatically before expiration. This eliminates the need to store long-term credentials on the instance.
AWS Lambda: Lambda functions can assume a role via the function's execution role. The Lambda service STS internally to get credentials for the function. The credentials are available via environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) and are rotated automatically.
Cross-account access: A user in Account A can assume a role in Account B if Account B's role trust policy allows Account A. The user's IAM policy must also allow sts:AssumeRole on the target role. This enables centralized management of resources across accounts.
Federation: STS supports SAML 2.0 and OpenID Connect (OIDC) federation. External identity providers (e.g., Active Directory, Google, Facebook) can authenticate users and receive STS tokens via AssumeRoleWithSAML or AssumeRoleWithWebIdentity. This allows users to access AWS resources without having IAM users.
Session Tags: When assuming a role, you can pass session tags that are propagated to the session. These tags can be used in IAM policies for fine-grained access control. For example, you can tag sessions with the user's cost center and restrict access based on that tag.
Important Considerations for the Exam
The session token is mandatory for all requests made with temporary credentials. Without it, requests fail with an AccessDenied error.
Temporary credentials cannot be used to sign requests for some services that require long-term credentials (e.g., IAM service operations like CreateUser). However, most AWS services support temporary credentials.
When using AssumeRole, the resulting role session has the permissions of the role plus any session policy passed in the request. The effective permissions are the intersection of the role's permissions and the session policy.
The ExternalId is a security measure for cross-account access. It prevents the confused deputy problem where a malicious account tricks a role into granting access. The role's trust policy requires the ExternalId to match a specific value, and the caller must provide that value.
STS is a global service with a single endpoint (sts.amazonaws.com) but can also be used regionally (sts.us-east-1.amazonaws.com) to reduce latency. Regional endpoints are recommended for production workloads.
CloudTrail logs all AssumeRole calls, including the source IP, user agent, and session details. This is useful for auditing.
Troubleshooting Common Issues
Access Denied when assuming role: Check the caller's IAM policy (must allow sts:AssumeRole on the role ARN) and the role's trust policy (must allow the caller principal). Also verify the ExternalId if required.
Session token not included: If you make API calls with temporary credentials but forget to include the session token, you get an AccessDenied error. The SDKs automatically include the session token if you configure the credentials properly.
Credentials expired: The application must handle credential expiration and refresh. The AWS SDKs automatically refresh credentials for roles assumed via instance profiles or Lambda execution roles. For custom AssumeRole calls, you must implement refresh logic.
Maximum session duration exceeded: If you request a duration longer than the maximum (12 hours for roles), STS returns a ValidationError. You must request a shorter duration.
Security Best Practices
Use the minimum duration necessary for the task.
Use session policies to further restrict permissions for each session.
Require MFA for sensitive role assumptions (using SerialNumber and TokenCode parameters).
Use ExternalId for cross-account role trust policies.
Regularly audit assumed roles via CloudTrail and IAM Access Analyzer.
Avoid hardcoding any credentials; use IAM roles for EC2, Lambda, and other services.
Initiate AssumeRole Request
The caller (user, application, or service) initiates an AssumeRole API call to STS. The request includes required parameters: RoleArn (the ARN of the role to assume), RoleSessionName (a unique session identifier), and optionally DurationSeconds (default 3600), Policy (inline session policy), ExternalId, and MFA details. The caller must have IAM permissions to call sts:AssumeRole on the target role. The request is sent to the STS endpoint, either global or regional.
STS Validates Authorization
STS receives the request and performs authorization checks. First, it verifies that the caller has an IAM policy allowing sts:AssumeRole on the specified role ARN. Second, it checks the target role's trust policy to ensure the caller (or the caller's account) is allowed to assume the role. If the trust policy includes conditions (e.g., ExternalId, MFA, or source IP), STS evaluates them. If any check fails, STS returns an AccessDenied or ValidationError.
STS Generates Temporary Credentials
If authorization succeeds, STS generates a new set of temporary credentials. It creates a unique access key ID (starting with ASIA), a secret access key, and a session token. The session token is a base64-encoded string that encodes the session's metadata, including expiration time and permissions. STS also sets the expiration timestamp (ISO 8601 format). The credentials are scoped to the permissions of the role combined with any session policy.
STS Returns Credentials to Caller
STS returns the temporary credentials in the API response. The response includes the Credentials object (AccessKeyId, SecretAccessKey, SessionToken, Expiration) and the AssumedRoleUser object (AssumedRoleId, Arn). The caller's application receives these credentials and stores them in memory or in a credentials provider. The credentials are never stored by STS; the caller is responsible for secure handling.
Caller Uses Credentials for API Calls
The caller uses the temporary credentials to make subsequent AWS API calls. Every request must include the session token, usually via the X-Amz-Security-Token header (for REST) or the AWS.SessionToken property (for SDKs). AWS services validate the session token against STS to ensure the credentials are still valid and have not been revoked. If the session token is missing or expired, the request fails with an AccessDenied error.
Credentials Expire or Are Refreshed
The temporary credentials remain valid until the expiration time. The caller's application must monitor the expiration and request new credentials before they expire. For IAM roles for EC2 and Lambda, the AWS SDK automatically refreshes credentials before expiration. For custom applications, developers must implement refresh logic, typically by calling AssumeRole again and updating the credentials provider. If the credentials expire, any subsequent API calls fail.
Enterprise Scenario 1: Cross-Account Access for Centralized Logging
A large enterprise has multiple AWS accounts for different departments (e.g., Development, Staging, Production). They want to centralize all CloudTrail logs into a single logging account. The logging account has an S3 bucket with a bucket policy that grants access only to a specific IAM role in the logging account. Each department account has an IAM role that can be assumed by users in the department. The logging account role's trust policy allows the department accounts to assume it, and the role has permissions to write to the S3 bucket. Users in the department accounts assume the logging role using STS AssumeRole and then use the temporary credentials to copy logs. The ExternalId is used to prevent the confused deputy problem: each department account uses a unique ExternalId shared out-of-band. Common issues: misconfigured trust policies (e.g., missing account ARN), expired ExternalId, and users forgetting to include the session token in S3 PUT requests. Performance is not a concern because log delivery is batch-oriented. The solution scales to hundreds of accounts.
Enterprise Scenario 2: Federated Access for Mobile App Users
A company builds a mobile app that allows users to upload photos to an S3 bucket. The app uses Amazon Cognito for user authentication. After authentication, Cognito exchanges the user's identity token for temporary AWS credentials via STS AssumeRoleWithWebIdentity. The role has a policy that restricts each user to their own folder in S3 (using ${cognito-identity.amazonaws.com:sub} condition). The app receives temporary credentials valid for 1 hour. The app uses the AWS SDK for mobile, which automatically refreshes credentials when they expire. Common problems: users who remain active for longer than 1 hour experience credential expiration if the SDK refresh fails due to network issues. The solution is to implement a pre-signed URL for uploads to avoid relying on temporary credentials for large files. The federation setup requires configuring the identity provider (Cognito) in IAM as an OIDC provider and creating the role with the appropriate trust policy.
Enterprise Scenario 3: Lambda Function Accessing RDS Database
A serverless application uses AWS Lambda to process events and write to an RDS MySQL database. The Lambda function has an execution role that grants permissions to RDS (e.g., rds-db:connect) and to other services. The Lambda service uses STS to obtain temporary credentials for the execution role. The credentials are automatically rotated every time the Lambda function is invoked (or more precisely, the Lambda service manages the credentials lifecycle). The database password is stored in AWS Secrets Manager, and the Lambda role has permission to retrieve it. The temporary credentials from STS are used for AWS API calls, not for database authentication. The database uses IAM database authentication (requires an auth token generated using RDS generate-db-auth-token, which also uses STS). Common misconfiguration: the Lambda function's VPC configuration prevents it from reaching the STS endpoint, causing credential retrieval failure. The fix is to add a VPC endpoint for STS or ensure the Lambda function has internet access via a NAT gateway.
What DVA-C02 Tests on STS and AssumeRole
The DVA-C02 exam tests your understanding of how to use STS to grant temporary access without hardcoding long-term credentials. Key objective codes: Domain 2.1 (Design and implement secure access to AWS resources). Specific topics:
AssumeRole API parameters: Know the default and maximum session durations (1 hour default, 12 hours max for roles).
Session token requirement: Every request with temporary credentials must include the session token.
Cross-account access: Understand the role trust policy and the ExternalId to prevent confused deputy.
IAM roles for EC2 and Lambda: How services automatically obtain credentials via STS.
Federation: AssumeRoleWithSAML and AssumeRoleWithWebIdentity for external identity providers.
Session policies: How they intersect with role permissions.
Common Wrong Answers and Traps
"Temporary credentials can be used indefinitely as long as they are refreshed before expiry." This is false because there is a maximum session duration (12 hours for roles). After that, you must re-authenticate. The exam may ask about the maximum duration.
"You can use temporary credentials to create IAM users." False. Some IAM actions (e.g., CreateUser, CreateRole) require long-term credentials. The exam tests which actions are restricted.
"The session token is optional if you use the access key and secret key from AssumeRole." False. The session token is mandatory. Without it, requests fail.
"You can pass any duration to AssumeRole." False. The minimum is 900 seconds, maximum is 43200 seconds for roles (3600 for GetFederationToken). The exam may ask for specific numbers.
"The ExternalId is used to authenticate the caller." False. ExternalId is used to prevent confused deputy, not for authentication. It is a string that must match the role's trust policy condition.
Specific Numbers and Terms to Memorize
Default session duration: 3600 seconds (1 hour)
Maximum session duration for IAM roles: 43200 seconds (12 hours)
Maximum session duration for federated users: 3600 seconds (1 hour)
Minimum session duration: 900 seconds (15 minutes)
Temporary access key ID prefix: ASIA
Role session ID prefix: AROA
STS endpoints: sts.amazonaws.com (global), sts.<region>.amazonaws.com (regional)
Session token header: X-Amz-Security-Token
Edge Cases the Exam Loves
MFA-protected role assumption: You must include SerialNumber (MFA device ARN) and TokenCode (one-time password). The role's trust policy must have a condition requiring MFA.
Session policies: If you pass a session policy, the effective permissions are the intersection of the role's permissions and the session policy. The exam may ask about this intersection.
Revoking temporary credentials: You cannot delete or invalidate temporary credentials individually, but you can attach a permissions boundary or change the role's policy. For immediate revocation, you can use AWS Organizations SCPs or IAM policy changes.
Regional STS endpoints: Using regional endpoints improves performance and avoids cross-region data transfer. The exam may ask about when to use regional vs global.
How to Eliminate Wrong Answers
If the question involves temporary credentials and the answer does not mention a session token, it is likely wrong.
If the answer suggests that temporary credentials can be used for IAM management actions, it is wrong.
If the answer mentions that you can set the duration to more than 12 hours for roles, it is wrong.
If the question is about cross-account access and the answer does not include ExternalId or trust policy, it is likely incomplete.
Default session duration for AssumeRole is 3600 seconds (1 hour); maximum is 43200 seconds (12 hours).
Every request with temporary credentials must include the session token (X-Amz-Security-Token).
Temporary credentials cannot be used for IAM management actions (e.g., CreateUser, CreateRole).
ExternalId prevents the confused deputy problem in cross-account role assumption.
Session policies restrict permissions further; effective permissions are the intersection of role and session policies.
Regional STS endpoints (e.g., sts.us-east-1.amazonaws.com) improve performance and reduce latency.
MFA can be enforced for role assumption by including SerialNumber and TokenCode in the request.
These come up on the exam all the time. Here's how to tell them apart.
AssumeRole
Used for IAM roles and cross-account access.
Returns temporary credentials for a specified role.
Maximum session duration is 12 hours (43200 seconds).
Requires the caller to have sts:AssumeRole permission on the role.
Supports session policies and MFA.
GetFederationToken
Used for federated users (not IAM roles).
Returns temporary credentials for a user with a custom policy.
Maximum session duration is 1 hour (3600 seconds).
Does not require a role; the caller must have sts:GetFederationToken permission.
Does not support MFA; session policies are required.
Mistake
Temporary credentials from AssumeRole never expire if you keep refreshing them.
Correct
Each session has a maximum duration of 12 hours (43200 seconds). After that, you must call AssumeRole again to get a new session. There is no way to extend a session beyond 12 hours.
Mistake
The session token is optional when using temporary credentials.
Correct
The session token is mandatory for all API requests made with temporary credentials. Without it, AWS returns an AccessDenied error. The SDKs automatically include it, but if you use raw HTTP requests, you must add the X-Amz-Security-Token header.
Mistake
You can use temporary credentials to perform any AWS API action.
Correct
Some IAM actions (e.g., CreateUser, CreateRole, CreatePolicy) require long-term credentials. Temporary credentials cannot be used for these actions. The exam tests this limitation.
Mistake
The ExternalId is used for authentication of the caller.
Correct
The ExternalId is a security measure to prevent the confused deputy problem. It is not used for authentication. It is a string that must match the role's trust policy condition. The caller provides it in the AssumeRole request.
Mistake
AssumeRole can be called without any permissions if you have the role ARN.
Correct
The caller must have an IAM policy that allows sts:AssumeRole on the target role ARN. Additionally, the role's trust policy must allow the caller. Both policies are required.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
AssumeRole is used to assume an IAM role, which has its own permissions. GetFederationToken is used for federated users who do not have an IAM role; you must pass a session policy that defines permissions. AssumeRole allows a maximum duration of 12 hours, while GetFederationToken allows only 1 hour. AssumeRole supports MFA, GetFederationToken does not. Both return temporary credentials with a session token.
You must call AssumeRole again before the current credentials expire. The AWS SDKs for EC2 and Lambda automatically refresh credentials. For custom applications, you can check the Expiration field and initiate a new AssumeRole call when the remaining time is low (e.g., 5 minutes). Then update your credentials provider with the new values.
Yes, you can use the AWS STS AssumeRole API to get temporary credentials and then use the AWS Federation Endpoint to generate a sign-in URL for the console. Alternatively, you can use IAM Identity Center (successor to AWS SSO) for console access.
RoleSessionName is a unique identifier for the session. It appears in CloudTrail logs and in the ARN of the assumed role (e.g., arn:aws:sts::123456789012:assumed-role/MyRole/MySessionName). It helps with auditing and tracking who assumed the role.
STS does not provide a direct API to revoke individual sessions. However, you can revoke access by modifying the role's permissions policy (e.g., deny all actions) or by attaching a permissions boundary. For immediate revocation, you can change the role's trust policy to deny the caller. Note that existing sessions may continue until expiration unless the role's policy is changed to deny all actions.
The confused deputy problem occurs when a malicious account tricks a role into granting access to resources it should not have. For example, a service in Account A asks Account B to assume a role, but Account A is malicious and uses the role to access Account B's resources. ExternalId is a unique string that the legitimate service provides in the AssumeRole request. The role's trust policy requires the ExternalId to match a specific value, ensuring that only the intended service can assume the role.
Most AWS services support temporary credentials, but some IAM actions (e.g., CreateUser, CreateRole, CreatePolicy, UpdateUser) do not. Additionally, some services like Amazon RDS for IAM database authentication require a separate auth token generated via RDS API (which itself uses STS). Always check the service documentation.
You've just covered AWS STS: AssumeRole and Temporary Credentials — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?