AWS Security Token Service API Guide

Use AWS Security Token Service (STS) with Chilkat to obtain temporary credentials, assume roles, exchange identity-provider tokens, and identify the caller of an AWS request. This guide connects 19 complete examples covering the STS API and practical credential use with Chilkat.Rest and Chilkat.Http.

Choose the credential flow

Start with the identity your application already has
Starting pointOperationResult
An IAM user's long-term credentials, optionally with MFAGetSessionTokenTemporary credentials based on that user.
An authorized AWS principal and a trusted target roleAssumeRoleA role session with the target role's effective permissions.
An OIDC token or a SAML response from an identity providerAssumeRoleWithWebIdentity or AssumeRoleWithSAMLRole credentials from an unsigned token exchange.
An IAM user acting as a protected server-side brokerGetFederationTokenA federated user session constrained by session policies and applicable authorization rules.
A calling AWS identity that must authenticate to an external serviceGetWebIdentityTokenAn AWS-signed JWT for the intended audience.
A valid trade-in token from a supported delegation workflowGetDelegatedAccessTokenTemporary credentials for the assumed principal.

Before making requests

The examples require Chilkat 11.6.0 or later and an unlocked library. Most direct calls use Chilkat.Rest with a verified TLS connection to sts.us-west-2.amazonaws.com. Use the matching signing region and choose the documented endpoint for your AWS partition. AWS recommends regional STS endpoints; some operations require them. The region issuing credentials does not choose the signing region of subsequent S3 or other service requests. See regional STS endpoint guidance.

Signed examples load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. Temporary source credentials also need session_token and ISO 8601 expiration. Each example lists its operation-specific inputs. SAML and OIDC exchange examples require their identity-provider inputs without AWS signing keys. These samples read explicit files; they do not discover AWS profiles or instance-role credentials.

How STS requests map to Chilkat

Query requests, signing, and XML responses
StepImplementation
Build the formCall Rest.ClearAllQueryParams, then AddQueryParam for Action, Version=2011-06-15, and operation parameters. Pass raw values and let Chilkat URL-encode them. The API version date remains current.
Sign an authenticated requestConfigure AuthAws with the credentials, region, ServiceName="sts", and SignatureVersion=4; attach it with Rest.SetAuthAws.
Include a source session tokenThe signed Rest examples add X-Amz-Security-Token to the form body on each request. Rebuild the form when retrying or changing operations.
Exchange an external identityAssumeRoleWithWebIdentity and AssumeRoleWithSAML omit AuthAws. Their OIDC token or SAML response authenticates the exchange. GetDelegatedAccessToken uses a signed request.
Send and validateUse FullRequestFormUrlEncoded("POST", "/"). Check transport completion, HTTP status, strict XML parsing, the response root and required result fields before consuming credentials.

Use the STS API reference, Rest reference, and AuthAws reference for operation and library details.

Identity and Diagnostics

Start with GetCallerIdentity to inspect the account, ARN and principal ID associated with the credentials being used. It needs no permission grant, but success does not prove access to another AWS service. GetAccessKeyInfo identifies the account associated with a supplied access key ID; it does not establish that the key is active or determine its permissions.

DecodeAuthorizationMessage handles encoded failures returned by certain AWS operations and requires sts:DecodeAuthorizationMessage. The example parses the JSON inside the XML response and accepts boolean flags or the string forms "true" and "false". Keep other decoded details private. An ordinary access-denied message is not an encoded authorization message. See GetCallerIdentity, GetAccessKeyInfo, and DecodeAuthorizationMessage.

IAM User Sessions and MFA

GetSessionToken uses a long-term IAM user's credentials; the example rejects an existing session token. It requests one hour. IAM user sessions support 15 minutes to 36 hours, with a 12-hour default when DurationSeconds is omitted. Do not use root credentials for this flow. GetSessionToken is an authentication operation and needs no permission grant for that operation.

Supply mfa_serial and mfa_code together when MFA is needed. Keep the six-digit code as a string to preserve a leading zero. Returned credentials inherit the user's permissions, with additional restrictions: IAM requests require MFA information, and the supported STS calls are AssumeRole and GetCallerIdentity. See GetSessionToken.

AssumeRole and Cross-Account Access

Set role_arn and role_session_name, and configure both the caller's authorization and the target role's trust. The introductory example restricts its session to s3:ListAllMyBuckets for the companion bucket-listing example. That session does not authorize downloading S3 objects merely because the role allows it. Session policies cannot add permissions beyond the role's applicable permissions.

The cross-account example supplies the agreed external_id and MFA information. ExternalId is a trust condition, not a password. It reads a current MFA code from private qa_data/aws/sts_mfa_input.json; replace that read with your application's input prompt when appropriate. Do not retain or reuse the code for unattended refresh. Requests use a one-hour duration. See AssumeRole.

Session Policies, Tags, and Role Chaining

The policy example sends an inline policy plus an existing managed policy ARN from the role's account. Their permissions combine and are then constrained by role permissions and other applicable authorization rules. The inline policy is not a separate ceiling over the managed policy. Keep their combined plaintext within the API limit, preserve the entire returned token, and inspect optional token size/utilization metrics when present.

Session tags support attribute-based access control. The example sends Project and Environment and makes Project transitive. Grant the required sts:TagSession permissions. Do not pass a tag again when it conflicts with an inherited transitive tag; session tags can also override role tags. See session tags and chaining.

Role chaining uses one role session to assume another and has a one-hour duration ceiling. SourceIdentity requires the relevant sts:SetSourceIdentity permissions, persists through the chain, and cannot be changed after it is set. The chaining example supplies temporary source credentials and checks the returned source identity. See source identity propagation.

OIDC, SAML, and Federated Users

AssumeRoleWithWebIdentity exchanges an OIDC token for role credentials. Configure the IAM identity provider and trust for the expected issuer, audience and subject. The SAML example sends the complete base64-encoded response from the IdP with RoleArn and PrincipalArn; do not encode it twice. STS verifies these external inputs. The samples do not implement an IdP login or treat decoded token contents as proof of authenticity.

SAML session lifetime can be shortened by SessionNotOnOrAfter, and AssumeRoleWithSAML does not support IAM Identity Center roles whose names start with AWSReservedSSO_. GetFederationToken is a separate signed flow for a protected IAM user acting as a broker. Its example supplies a focused session policy; the resulting credentials have IAM and STS API restrictions. See AssumeRoleWithWebIdentity, AssumeRoleWithSAML, and GetFederationToken.

Use Temporary Credentials with Rest and Http

Keep the access key ID, secret access key, session token and expiration together. The normalization example accepts all seven credential-producing STS response roots and builds one in-memory object with access_key, secret_key, session_token and expiration. It uses that set to call GetCallerIdentity with Rest. A JWT from GetWebIdentityToken is a different kind of token and is not accepted as an AWS credential set.

The S3 bucket-listing example reads either the GetSessionToken or AssumeRole XML handoff, includes the token in every signed query, and follows ListBuckets continuation tokens. It lists owned general purpose buckets and handles empty intermediate pages. The Http example uses AwsAccessKey, AwsSecretKey and AwsSessionToken with S3_DownloadBd to retrieve a small object into memory. Configure the bucket's region and give the session s3:GetObject access; the introductory bucket-listing policy is insufficient. See ListBuckets and GetObject.

Know where the credentials live. The original GetSessionToken and AssumeRole examples save qa_data/tokens/aws_session_token.xml, which contains plaintext credentials. Protect the directory and file. The newer producers keep their complete session object in memory; they do not automatically update that XML file. Connect the producer and consumer deliberately. A failed request can leave an older file unchanged.

The XML consumers check expiration with a 60-second margin. The Http download also reads qa_data/aws/sts_download.json for bucket and a raw object_key. Keep input files, full responses, signed URLs and diagnostic dumps outside public content and shared logs.

Expiration and Credential Refresh

The refresh example reuses a complete cached session with more than five minutes remaining; otherwise it requests a new AssumeRole session. Its optional private qa_data/tokens/sts_session.json cache must belong to the exact role and workload. It checks source credentials, validates the full response, and publishes one complete serialized snapshot in memory. It does not extend an existing session or overwrite a cache file.

Throttling and selected transient HTTP failures receive at most three attempts, separated by one- and two-second waits. Each attempt rebuilds the form and checks source expiration. Transport, authorization and invalid-response failures stop without publishing a replacement. This is a single-threaded example for a role that does not require interactive MFA; concurrent applications need synchronization, and production retry behavior should include jitter. Repeat the decision before each unit of work.

Outbound Identity and Delegated Access

GetWebIdentityToken creates an AWS-signed JWT for an external service. Outbound federation must be enabled for the AWS account. The example selects a regional endpoint, one audience, RS256 and a five-minute lifetime. AWSIdentity is the default subject mode; OriginIdentity requires trusted identity propagation context. Optional Scope is limited to OriginIdentity with one audience and requires sts:SetWebIdentityTokenScope as well as sts:GetWebIdentityToken. The recipient must verify the trusted issuer, signature, audience and expiration. See GetWebIdentityToken.

GetDelegatedAccessToken exchanges an existing, valid trade-in token for credentials and an AssumedPrincipal. The sample signs the request and starts with a token supplied by a supported delegation workflow; it does not create the token or implement its issuer. Obtain a fresh input when the token expires. PackedPolicySize is deprecated and not populated for this operation. See GetDelegatedAccessToken.

Organization Root Audit Sessions

AssumeRoot requires centralized root access for the organization and an authorized principal in its management account or IAM delegated administrator account. Do not sign the call with root user credentials. Set the member account's target_account_id. The example uses a regional endpoint, the fixed IAMAuditRootUserCredentials task policy, and the 15-minute maximum.

The example obtains a task-scoped session in memory. It does not delete credentials, change passwords or modify resource policies. Use it only for audit actions allowed by the task policy and monitor the session through CloudTrail. See AssumeRoot.

Troubleshooting

Checks for common STS integration failures
SymptomWhat to check
Signature or authentication failureMatch endpoint, region and service name. Supply all three components for temporary credentials. Check clock accuracy and pass raw values before URL encoding. Leave SAML and OIDC role exchanges unsigned.
Access denied while assuming a roleReview caller permissions and the target trust policy, including MFA, ExternalId, source identity and tagging conditions. Check organization policies and explicit denies.
Expired token or expired trade-in tokenIdentify whether the source credentials, identity-provider input, trade-in token or returned session expired. Obtain a fresh complete set from the correct provider.
Session duration rejectedCheck the operation's range and role configuration. Role chaining is limited to one hour; root audit sessions to 15 minutes. Identity-provider assertions may shorten federation sessions.
Throttling or service failureUse bounded backoff where appropriate. The refresh sample retries selected responses; the other examples stop for the caller to handle the failure.
Unexpected XML or missing fieldsCheck transport and HTTP status before using the result. Validate the response root and complete credential set. Retain request IDs for troubleshooting, without dumping token-bearing bodies or diagnostics.