Operations for obtaining session tokens and federation tokens for temporary access. Includes support for MFA requirements, federated user sessions, and IAM user temporary credentials.
Returns temporary security credentials for IAM users, optionally requiring multi-factor authentication (MFA). These credentials can be used to access AWS resources for a limited time.
/**
* Command for obtaining session tokens for IAM users
* Returns temporary credentials that can be used with or without MFA
*/
class GetSessionTokenCommand {
constructor(input: GetSessionTokenCommandInput);
}
/**
* Input parameters for GetSessionToken operation
*/
interface GetSessionTokenCommandInput extends GetSessionTokenRequest {
/** Session duration in seconds (900-129600, default 3600) */
DurationSeconds?: number;
/** Serial number or ARN of MFA device */
SerialNumber?: string;
/** Value from MFA device (6 digits required if SerialNumber provided) */
TokenCode?: string;
}
/**
* Output from GetSessionToken operation
*/
interface GetSessionTokenCommandOutput extends GetSessionTokenResponse, MetadataBearer {
/** Temporary security credentials */
Credentials?: Credentials;
}Usage Examples:
import { STSClient, GetSessionTokenCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Basic session token (no MFA)
const basicCommand = new GetSessionTokenCommand({
DurationSeconds: 3600 // 1 hour
});
const basicResponse = await client.send(basicCommand);
console.log("Session token obtained:", basicResponse.Credentials?.SessionToken);
// Session token with MFA requirement
const mfaCommand = new GetSessionTokenCommand({
DurationSeconds: 7200, // 2 hours
SerialNumber: "arn:aws:iam::123456789012:mfa/alice",
TokenCode: "123456" // Code from MFA device
});
const mfaResponse = await client.send(mfaCommand);
console.log("MFA session credentials:", {
accessKeyId: mfaResponse.Credentials?.AccessKeyId,
expiration: mfaResponse.Credentials?.Expiration
});
// Long-duration session token (up to 36 hours)
const longCommand = new GetSessionTokenCommand({
DurationSeconds: 129600, // 36 hours maximum
SerialNumber: "123456789012", // Virtual MFA device
TokenCode: "789012"
});
const longResponse = await client.send(longCommand);
// Helper function for MFA session
const getMfaSession = async (mfaSerialNumber: string, mfaToken: string, duration: number = 3600) => {
const command = new GetSessionTokenCommand({
SerialNumber: mfaSerialNumber,
TokenCode: mfaToken,
DurationSeconds: duration
});
try {
const response = await client.send(command);
return {
success: true,
credentials: response.Credentials,
expiresAt: response.Credentials?.Expiration
};
} catch (error) {
return {
success: false,
error: error.message
};
}
};
const mfaSession = await getMfaSession("arn:aws:iam::123456789012:mfa/user", "123456", 7200);Returns temporary security credentials for federated users with IAM user-based session policies. These credentials enable temporary access for users who don't have AWS identities.
/**
* Command for obtaining federation tokens for temporary user access
* Creates temporary credentials for federated users with custom policies
*/
class GetFederationTokenCommand {
constructor(input: GetFederationTokenCommandInput);
}
/**
* Input parameters for GetFederationToken operation
*/
interface GetFederationTokenCommandInput extends GetFederationTokenRequest {
/** Name for the federated user (required, regex: alphanumeric, =,.@- */
Name: string;
/** Inline JSON policy defining permissions (max 2,048 characters) */
Policy?: string;
/** Managed policy ARNs for the federated user (max 10) */
PolicyArns?: PolicyDescriptorType[];
/** Session duration in seconds (900-129600, default 43200) */
DurationSeconds?: number;
/** Session tags for the federated user session (max 50) */
Tags?: Tag[];
}
/**
* Output from GetFederationToken operation
*/
interface GetFederationTokenCommandOutput extends GetFederationTokenResponse, MetadataBearer {
/** Temporary security credentials */
Credentials?: Credentials;
/** Information about the federated user */
FederatedUser?: FederatedUser;
/** Percentage of maximum allowed session policy size */
PackedPolicySize?: number;
}
/**
* Information about a federated user
*/
interface FederatedUser {
/** Federated user identifier */
FederatedUserId: string;
/** ARN of the federated user */
Arn: string;
}Usage Examples:
import { STSClient, GetFederationTokenCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Basic federation token with inline policy
const federationCommand = new GetFederationTokenCommand({
Name: "TempUser",
Policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: [
"s3:GetObject",
"s3:PutObject"
],
Resource: "arn:aws:s3:::my-bucket/*"
}]
}),
DurationSeconds: 7200 // 2 hours
});
const federationResponse = await client.send(federationCommand);
console.log("Federated user ARN:", federationResponse.FederatedUser?.Arn);
console.log("Credentials expire at:", federationResponse.Credentials?.Expiration);
// Federation token with managed policies and tags
const managedPolicyCommand = new GetFederationTokenCommand({
Name: "DataAnalyst",
PolicyArns: [
{ arn: "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" },
{ arn: "arn:aws:iam::123456789012:policy/CustomAnalyticsPolicy" }
],
DurationSeconds: 14400, // 4 hours
Tags: [
{ Key: "Department", Value: "Analytics" },
{ Key: "Project", Value: "DataPipeline" },
{ Key: "Temporary", Value: "true" }
]
});
const managedResponse = await client.send(managedPolicyCommand);
// Create federation token for external user
const createExternalUserToken = async (
userName: string,
allowedActions: string[],
resources: string[],
durationHours: number = 1
) => {
const policy = {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: allowedActions,
Resource: resources
}]
};
const command = new GetFederationTokenCommand({
Name: userName,
Policy: JSON.stringify(policy),
DurationSeconds: durationHours * 3600,
Tags: [
{ Key: "UserType", Value: "External" },
{ Key: "CreatedAt", Value: new Date().toISOString() }
]
});
try {
const response = await client.send(command);
return {
success: true,
credentials: response.Credentials,
userArn: response.FederatedUser?.Arn,
policySize: response.PackedPolicySize
};
} catch (error) {
return {
success: false,
error: error.message
};
}
};
// Create token for a contractor with S3 access
const contractorToken = await createExternalUserToken(
"Contractor-John",
["s3:ListBucket", "s3:GetObject", "s3:PutObject"],
["arn:aws:s3:::project-bucket", "arn:aws:s3:::project-bucket/*"],
8 // 8 hours
);
if (contractorToken.success) {
console.log("Contractor credentials created");
console.log("User ARN:", contractorToken.userArn);
console.log("Policy size:", contractorToken.policySize + "%");
}Different token operations have specific duration limits:
/**
* Duration limits for different token types
*/
interface TokenDurationLimits {
/** GetSessionToken duration range */
sessionToken: {
minimum: 900; // 15 minutes
maximum: 129600; // 36 hours
default: 3600; // 1 hour
};
/** GetFederationToken duration range */
federationToken: {
minimum: 900; // 15 minutes
maximum: 129600; // 36 hours
default: 43200; // 12 hours
};
}Common patterns for integrating MFA with token operations:
import { STSClient, GetSessionTokenCommand } from "@aws-sdk/client-sts";
// MFA token manager
class MFATokenManager {
private client: STSClient;
constructor(region: string = "us-east-1") {
this.client = new STSClient({ region });
}
/**
* Get MFA-authenticated session token
*/
async getMfaToken(mfaSerial: string, mfaCode: string, duration: number = 3600) {
const command = new GetSessionTokenCommand({
SerialNumber: mfaSerial,
TokenCode: mfaCode,
DurationSeconds: duration
});
const response = await this.client.send(command);
return response.Credentials;
}
/**
* Validate MFA token format
*/
validateMfaCode(code: string): boolean {
return /^\d{6}$/.test(code);
}
/**
* Check if credentials are close to expiring
*/
isNearExpiry(credentials: Credentials, bufferMinutes: number = 5): boolean {
if (!credentials.Expiration) return true;
const expiryTime = credentials.Expiration.getTime();
const bufferTime = bufferMinutes * 60 * 1000;
const now = Date.now();
return (expiryTime - now) <= bufferTime;
}
}
// Usage example
const mfaManager = new MFATokenManager("us-east-1");
// Get MFA session
const mfaCredentials = await mfaManager.getMfaToken(
"arn:aws:iam::123456789012:mfa/alice",
"123456",
7200
);
// Check if credentials need refresh
if (mfaManager.isNearExpiry(mfaCredentials, 10)) {
console.log("Credentials will expire soon, consider refreshing");
}Common scenarios for using federation tokens:
// Temporary access for external contractors
const grantTemporaryAccess = async (contractorName: string, projectBucket: string) => {
const command = new GetFederationTokenCommand({
Name: `Contractor-${contractorName}`,
Policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
Resource: [
`arn:aws:s3:::${projectBucket}`,
`arn:aws:s3:::${projectBucket}/*`
]
}]
}),
DurationSeconds: 28800, // 8 hours
Tags: [
{ Key: "UserType", Value: "Contractor" },
{ Key: "Project", Value: projectBucket }
]
});
const response = await client.send(command);
return response.Credentials;
};
// Cross-account data sharing
const createDataSharingToken = async (partnerName: string, sharedDataPath: string) => {
const command = new GetFederationTokenCommand({
Name: `Partner-${partnerName}`,
Policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: ["s3:GetObject"],
Resource: `arn:aws:s3:::shared-data/${sharedDataPath}/*`,
Condition: {
StringEquals: {
"s3:ExistingObjectTag/Partner": partnerName
}
}
}]
}),
DurationSeconds: 3600 // 1 hour
});
const response = await client.send(command);
return response.Credentials;
};Token operations can encounter specific error conditions:
import {
STSClient,
GetSessionTokenCommand,
GetFederationTokenCommand,
MalformedPolicyDocumentException,
PackedPolicyTooLargeException,
RegionDisabledException
} from "@aws-sdk/client-sts";
const safeTokenRequest = async (command: GetSessionTokenCommand | GetFederationTokenCommand) => {
try {
const response = await client.send(command);
return { success: true, data: response };
} catch (error) {
let errorMessage = "Unknown error";
if (error instanceof MalformedPolicyDocumentException) {
errorMessage = "Policy document is malformed";
} else if (error instanceof PackedPolicyTooLargeException) {
errorMessage = "Policy document is too large";
} else if (error instanceof RegionDisabledException) {
errorMessage = "STS is not activated in this region";
}
return { success: false, error: errorMessage };
}
};
const result = await safeTokenRequest(new GetSessionTokenCommand({ DurationSeconds: 3600 }));
if (result.success) {
console.log("Token obtained:", result.data.Credentials);
} else {
console.error("Failed to get token:", result.error);
}