Operations for assuming IAM roles to obtain temporary credentials with comprehensive support for cross-account access, federation, MFA, and session policies.
Returns a set of temporary security credentials for assuming an IAM role within your account or for cross-account access.
/**
* Command for assuming an IAM role
* Returns temporary credentials consisting of access key, secret key, and session token
*/
class AssumeRoleCommand {
constructor(input: AssumeRoleCommandInput);
}
/**
* Input parameters for AssumeRole operation
*/
interface AssumeRoleCommandInput extends AssumeRoleRequest {
/** The ARN of the role to assume (required) */
RoleArn: string;
/** Session identifier for the assumed role session (required) */
RoleSessionName: string;
/** Managed policy ARNs to use as session policies (max 10) */
PolicyArns?: PolicyDescriptorType[];
/** Inline JSON session policy (max 2,048 characters) */
Policy?: string;
/** Session duration in seconds (900-43200, default 3600) */
DurationSeconds?: number;
/** Session tags for the assumed role session (max 50) */
Tags?: Tag[];
/** Keys for transitive session tags */
TransitiveTagKeys?: string[];
/** Unique identifier for cross-account role assumption */
ExternalId?: string;
/** MFA device serial number or ARN */
SerialNumber?: string;
/** Value from MFA device (6 digits) */
TokenCode?: string;
/** Source identity for role chaining scenarios */
SourceIdentity?: string;
/** Trusted context assertions from context providers */
ProvidedContexts?: ProvidedContext[];
}
/**
* Output from AssumeRole operation
*/
interface AssumeRoleCommandOutput extends AssumeRoleResponse, MetadataBearer {
/** Temporary security credentials */
Credentials?: Credentials;
/** Information about the assumed role user */
AssumedRoleUser?: AssumedRoleUser;
/** Percentage of the maximum allowed session policy size */
PackedPolicySize?: number;
/** Source identity specified in the request */
SourceIdentity?: string;
}Usage Examples:
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Basic role assumption
const basicCommand = new AssumeRoleCommand({
RoleArn: "arn:aws:iam::123456789012:role/MyRole",
RoleSessionName: "MyAppSession"
});
const basicResponse = await client.send(basicCommand);
console.log("Access Key:", basicResponse.Credentials?.AccessKeyId);
// Role assumption with session policy and MFA
const mfaCommand = new AssumeRoleCommand({
RoleArn: "arn:aws:iam::123456789012:role/SecureRole",
RoleSessionName: "SecureSession",
DurationSeconds: 7200, // 2 hours
Policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::my-bucket/*"
}]
}),
SerialNumber: "arn:aws:iam::123456789012:mfa/user",
TokenCode: "123456"
});
const mfaResponse = await client.send(mfaCommand);
// Cross-account role assumption with external ID
const crossAccountCommand = new AssumeRoleCommand({
RoleArn: "arn:aws:iam::987654321098:role/CrossAccountRole",
RoleSessionName: "CrossAccountSession",
ExternalId: "unique-external-id",
Tags: [
{ Key: "Project", Value: "DataPipeline" },
{ Key: "Environment", Value: "Production" }
],
TransitiveTagKeys: ["Project"]
});
const crossAccountResponse = await client.send(crossAccountCommand);Assumes a role using SAML assertion for federated access from identity providers supporting SAML 2.0.
/**
* Command for assuming role with SAML assertion
* Enables federated access using SAML identity providers
*/
class AssumeRoleWithSAMLCommand {
constructor(input: AssumeRoleWithSAMLCommandInput);
}
/**
* Input parameters for AssumeRoleWithSAML operation
*/
interface AssumeRoleWithSAMLCommandInput extends AssumeRoleWithSAMLRequest {
/** ARN of the role to assume (required) */
RoleArn: string;
/** ARN of the SAML identity provider (required) */
PrincipalArn: string;
/** Base64-encoded SAML authentication response (required) */
SAMLAssertion: string;
/** Managed policy ARNs for session policies (max 10) */
PolicyArns?: PolicyDescriptorType[];
/** Inline JSON session policy (max 2,048 characters) */
Policy?: string;
/** Session duration in seconds (900-43200, default 3600) */
DurationSeconds?: number;
}
/**
* Output from AssumeRoleWithSAML operation
*/
interface AssumeRoleWithSAMLCommandOutput extends AssumeRoleWithSAMLResponse, MetadataBearer {
/** Temporary security credentials */
Credentials?: Credentials;
/** Information about the assumed role user */
AssumedRoleUser?: AssumedRoleUser;
/** Percentage of maximum session policy size */
PackedPolicySize?: number;
/** Subject of the SAML assertion */
Subject?: string;
/** Subject type from the SAML assertion */
SubjectType?: string;
/** Issuer of the SAML assertion */
Issuer?: string;
/** Audience of the SAML assertion */
Audience?: string;
/** Name qualifier from the SAML assertion */
NameQualifier?: string;
/** Source identity from the SAML assertion */
SourceIdentity?: string;
}Usage Examples:
import { STSClient, AssumeRoleWithSAMLCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// SAML federation
const samlCommand = new AssumeRoleWithSAMLCommand({
RoleArn: "arn:aws:iam::123456789012:role/SAMLRole",
PrincipalArn: "arn:aws:iam::123456789012:saml-provider/MyProvider",
SAMLAssertion: "base64-encoded-saml-assertion",
DurationSeconds: 3600
});
const samlResponse = await client.send(samlCommand);
console.log("SAML Subject:", samlResponse.Subject);Assumes a role using web identity tokens from OAuth 2.0 or OpenID Connect providers like Amazon Cognito, Google, Facebook.
/**
* Command for assuming role with web identity token
* Enables federated access using OAuth 2.0/OpenID Connect tokens
*/
class AssumeRoleWithWebIdentityCommand {
constructor(input: AssumeRoleWithWebIdentityCommandInput);
}
/**
* Input parameters for AssumeRoleWithWebIdentity operation
*/
interface AssumeRoleWithWebIdentityCommandInput extends AssumeRoleWithWebIdentityRequest {
/** ARN of the role to assume (required) */
RoleArn: string;
/** Session identifier for the assumed role session (required) */
RoleSessionName: string;
/** OAuth 2.0 or OpenID Connect token from identity provider (required) */
WebIdentityToken: string;
/** Identity provider domain (e.g., www.amazon.com, graph.facebook.com) */
ProviderId?: string;
/** Managed policy ARNs for session policies (max 10) */
PolicyArns?: PolicyDescriptorType[];
/** Inline JSON session policy (max 2,048 characters) */
Policy?: string;
/** Session duration in seconds (900-43200, default 3600) */
DurationSeconds?: number;
}
/**
* Output from AssumeRoleWithWebIdentity operation
*/
interface AssumeRoleWithWebIdentityCommandOutput extends AssumeRoleWithWebIdentityResponse, MetadataBearer {
/** Temporary security credentials */
Credentials?: Credentials;
/** Subject identifier from the web identity token */
SubjectFromWebIdentityToken?: string;
/** Information about the assumed role user */
AssumedRoleUser?: AssumedRoleUser;
/** Percentage of maximum session policy size */
PackedPolicySize?: number;
/** Identity provider that issued the token */
Provider?: string;
/** Token audience or client ID */
Audience?: string;
/** Source identity from the JWT */
SourceIdentity?: string;
}Usage Examples:
import { STSClient, AssumeRoleWithWebIdentityCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Web identity federation with Amazon Cognito
const webIdentityCommand = new AssumeRoleWithWebIdentityCommand({
RoleArn: "arn:aws:iam::123456789012:role/CognitoRole",
RoleSessionName: "CognitoSession",
WebIdentityToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", // JWT token
ProviderId: "cognito-identity.amazonaws.com",
DurationSeconds: 3600
});
const webIdentityResponse = await client.send(webIdentityCommand);
console.log("Provider:", webIdentityResponse.Provider);
// Web identity with session policy
const restrictedCommand = new AssumeRoleWithWebIdentityCommand({
RoleArn: "arn:aws:iam::123456789012:role/WebRole",
RoleSessionName: "RestrictedWebSession",
WebIdentityToken: "oauth-token-from-google",
ProviderId: "accounts.google.com",
Policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: ["s3:GetObject", "s3:PutObject"],
Resource: "arn:aws:s3:::user-bucket/${www.google.com:sub}/*"
}]
})
});
const restrictedResponse = await client.send(restrictedCommand);Assumes root privileges for privileged tasks with scoped permissions using managed policies.
/**
* Command for assuming root privileges with scoped permissions
* Enables elevated access for privileged administrative tasks
*/
class AssumeRootCommand {
constructor(input: AssumeRootCommandInput);
}
/**
* Input parameters for AssumeRoot operation
*/
interface AssumeRootCommandInput extends AssumeRootRequest {
/** ARN of the managed policy defining allowed actions (required) */
TaskPolicyArn: string;
/** Session duration in seconds (900-3600, default 900) */
DurationSeconds?: number;
/** Session identifier for the root session (required) */
RoleSessionName: string;
}
/**
* Output from AssumeRoot operation
*/
interface AssumeRootCommandOutput extends AssumeRootResponse, MetadataBearer {
/** Temporary security credentials with root privileges */
Credentials?: Credentials;
/** Source identity that assumed root privileges */
SourceIdentity?: string;
}Usage Examples:
import { STSClient, AssumeRootCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Assume root privileges for specific task
const rootCommand = new AssumeRootCommand({
TaskPolicyArn: "arn:aws:iam::123456789012:policy/BillingAccessPolicy",
RoleSessionName: "BillingAdminSession",
DurationSeconds: 1800 // 30 minutes
});
const rootResponse = await client.send(rootCommand);
console.log("Root credentials obtained:", rootResponse.Credentials?.AccessKeyId);Key data types used across role assumption operations:
/**
* Reference to IAM managed policy for session policies
*/
interface PolicyDescriptorType {
/** ARN of IAM managed policy */
arn?: string;
}
/**
* Session tag for role assumptions
*/
interface Tag {
/** Tag key (max 128 characters) */
Key: string;
/** Tag value (max 256 characters) */
Value: string;
}
/**
* Trusted context assertion from context providers
*/
interface ProvidedContext {
/** ARN of the context provider */
ProviderArn?: string;
/** Signed and encrypted context assertion */
ContextAssertion?: string;
}Role assumption operations can throw specific exceptions:
import {
STSClient,
AssumeRoleCommand,
ExpiredTokenException,
MalformedPolicyDocumentException,
PackedPolicyTooLargeException,
RegionDisabledException
} from "@aws-sdk/client-sts";
try {
const response = await client.send(command);
} catch (error) {
if (error instanceof ExpiredTokenException) {
console.error("Token has expired");
} else if (error instanceof MalformedPolicyDocumentException) {
console.error("Invalid policy document");
} else if (error instanceof PackedPolicyTooLargeException) {
console.error("Session policies are too large");
} else if (error instanceof RegionDisabledException) {
console.error("STS is not activated in this region");
}
}Factory functions for creating standardized role assumers used by credential providers. These functions provide pre-configured role assumption functionality for credential provider implementations.
Creates a default role assumer function for standard role assumption using the AssumeRole API.
/**
* Creates a default role assumer for credential providers
* Returns a function that can assume roles using source credentials
* @param stsOptions - Configuration options for the STS client
* @param stsPlugins - Optional middleware plugins for the STS client
* @returns RoleAssumer function for assuming roles
*/
function getDefaultRoleAssumer(
stsOptions?: STSRoleAssumerOptions,
stsPlugins?: Pluggable<ServiceInputTypes, ServiceOutputTypes>[]
): RoleAssumer;
/**
* Function type for role assumption operations
* Takes source credentials and role parameters, returns temporary credentials
*/
type RoleAssumer = (
sourceCreds: AwsCredentialIdentity,
params: AssumeRoleCommandInput
) => Promise<AwsCredentialIdentity>;Usage Examples:
import { getDefaultRoleAssumer, STSRoleAssumerOptions } from "@aws-sdk/client-sts";
// Basic role assumer configuration
const roleAssumer = getDefaultRoleAssumer({
region: "us-east-1",
logger: console
});
// Use with credential provider
const sourceCredentials = {
accessKeyId: "AKIA...",
secretAccessKey: "...",
sessionToken: "..."
};
const assumedCredentials = await roleAssumer(sourceCredentials, {
RoleArn: "arn:aws:iam::123456789012:role/MyRole",
RoleSessionName: "MySession"
});
console.log("Assumed Access Key:", assumedCredentials.accessKeyId);Creates a default role assumer function for web identity federation using the AssumeRoleWithWebIdentity API.
/**
* Creates a default role assumer for web identity federation
* Returns a function that can assume roles using web identity tokens
* @param stsOptions - Configuration options for the STS client
* @param stsPlugins - Optional middleware plugins for the STS client
* @returns RoleAssumerWithWebIdentity function for web identity federation
*/
function getDefaultRoleAssumerWithWebIdentity(
stsOptions?: STSRoleAssumerOptions,
stsPlugins?: Pluggable<ServiceInputTypes, ServiceOutputTypes>[]
): RoleAssumerWithWebIdentity;
/**
* Function type for web identity role assumption
* Takes web identity parameters and returns temporary credentials
*/
type RoleAssumerWithWebIdentity = (
params: AssumeRoleWithWebIdentityCommandInput
) => Promise<AwsCredentialIdentity>;Usage Examples:
import { getDefaultRoleAssumerWithWebIdentity } from "@aws-sdk/client-sts";
// Web identity role assumer configuration
const webIdentityAssumer = getDefaultRoleAssumerWithWebIdentity({
region: "us-east-1"
});
// Use with OIDC token
const credentials = await webIdentityAssumer({
RoleArn: "arn:aws:iam::123456789012:role/WebIdentityRole",
RoleSessionName: "WebSession",
WebIdentityToken: "eyJhbGciOiJSUzI1NiIs..." // JWT token from OIDC provider
});
console.log("Web Identity Access Key:", credentials.accessKeyId);Configuration options for role assumer functions, extending standard STS client configuration.
/**
* Configuration options for STS role assumers
* Includes core STS client options plus credential provider specific settings
*/
type STSRoleAssumerOptions = Pick<STSClientConfig, "logger" | "region" | "requestHandler"> & {
/** Logger instance for credential provider operations */
credentialProviderLogger?: Logger;
/** Parent client configuration for inheriting settings */
parentClientConfig?: CredentialProviderOptions["parentClientConfig"];
};