Operations for retrieving information about the current caller identity and access keys. Essential for authentication verification, debugging credential issues, and account management.
Returns details about the IAM identity whose credentials are used to call the operation. No permissions are required to perform this operation.
/**
* Command for retrieving current caller identity information
* Returns details about the IAM user or role making the request
*/
class GetCallerIdentityCommand {
constructor(input: GetCallerIdentityCommandInput);
}
/**
* Input parameters for GetCallerIdentity operation
* No input parameters are required for this operation
*/
interface GetCallerIdentityCommandInput extends GetCallerIdentityRequest {}
/**
* Empty request interface - no parameters needed
*/
interface GetCallerIdentityRequest {}
/**
* Output from GetCallerIdentity operation
*/
interface GetCallerIdentityCommandOutput extends GetCallerIdentityResponse, MetadataBearer {
/** Unique identifier of the calling entity */
UserId?: string;
/** AWS account ID number of the account that owns the entity */
Account?: string;
/** AWS ARN associated with the calling entity */
Arn?: string;
}Usage Examples:
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Basic caller identity check
const command = new GetCallerIdentityCommand({});
const response = await client.send(command);
console.log(`Account: ${response.Account}`);
console.log(`User ID: ${response.UserId}`);
console.log(`ARN: ${response.Arn}`);
// Using with error handling
try {
const identity = await client.send(new GetCallerIdentityCommand({}));
// Determine the type of principal
if (identity.Arn?.includes(':user/')) {
console.log('Called by IAM user:', identity.Arn);
} else if (identity.Arn?.includes(':assumed-role/')) {
console.log('Called by assumed role:', identity.Arn);
} else if (identity.Arn?.includes(':federated-user/')) {
console.log('Called by federated user:', identity.Arn);
} else if (identity.Arn?.includes(':root')) {
console.log('Called by root user:', identity.Arn);
}
} catch (error) {
console.error('Failed to get caller identity:', error);
}
// Verify account ownership
const checkAccount = async (expectedAccountId: string) => {
const identity = await client.send(new GetCallerIdentityCommand({}));
if (identity.Account === expectedAccountId) {
console.log('Account verified successfully');
return true;
} else {
console.error(`Account mismatch: expected ${expectedAccountId}, got ${identity.Account}`);
return false;
}
};
await checkAccount('123456789012');Returns information about the specified access key ID, including the account ID that owns the access key.
/**
* Command for retrieving information about an access key
* Returns the account ID that owns the specified access key
*/
class GetAccessKeyInfoCommand {
constructor(input: GetAccessKeyInfoCommandInput);
}
/**
* Input parameters for GetAccessKeyInfo operation
*/
interface GetAccessKeyInfoCommandInput extends GetAccessKeyInfoRequest {
/** The identifier of an access key (required) */
AccessKeyId: string;
}
/**
* Output from GetAccessKeyInfo operation
*/
interface GetAccessKeyInfoCommandOutput extends GetAccessKeyInfoResponse, MetadataBearer {
/** AWS account ID that the access key belongs to */
Account?: string;
}Usage Examples:
import { STSClient, GetAccessKeyInfoCommand } from "@aws-sdk/client-sts";
const client = new STSClient({ region: "us-east-1" });
// Get account info for an access key
const command = new GetAccessKeyInfoCommand({
AccessKeyId: "AKIAIOSFODNN7EXAMPLE"
});
const response = await client.send(command);
console.log(`Access key belongs to account: ${response.Account}`);
// Batch check multiple access keys
const checkAccessKeys = async (accessKeyIds: string[]) => {
const results = await Promise.allSettled(
accessKeyIds.map(async (keyId) => {
const command = new GetAccessKeyInfoCommand({ AccessKeyId: keyId });
const response = await client.send(command);
return { keyId, account: response.Account };
})
);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Key ${accessKeyIds[index]} belongs to account: ${result.value.account}`);
} else {
console.error(`Failed to check key ${accessKeyIds[index]}:`, result.reason);
}
});
};
await checkAccessKeys([
"AKIAIOSFODNN7EXAMPLE",
"AKIAI44QH8DHBEXAMPLE"
]);
// Validate access key ownership
const validateKeyOwnership = async (accessKeyId: string, expectedAccount: string) => {
try {
const command = new GetAccessKeyInfoCommand({ AccessKeyId: accessKeyId });
const response = await client.send(command);
if (response.Account === expectedAccount) {
console.log('Access key ownership validated');
return true;
} else {
console.warn(`Key belongs to ${response.Account}, expected ${expectedAccount}`);
return false;
}
} catch (error) {
console.error('Failed to validate key ownership:', error);
return false;
}
};
await validateKeyOwnership("AKIAIOSFODNN7EXAMPLE", "123456789012");Response formats vary based on the type of principal making the request:
IAM User Response:
// Example response for IAM user
{
UserId: "AIDACKCEVSQ6C2EXAMPLE",
Account: "123456789012",
Arn: "arn:aws:iam::123456789012:user/Alice"
}Assumed Role Response:
// Example response for assumed role
{
UserId: "AROA12345678901234567:MyRoleSession",
Account: "123456789012",
Arn: "arn:aws:sts::123456789012:assumed-role/MyRole/MyRoleSession"
}Federated User Response:
// Example response for federated user
{
UserId: "123456789012:Alice",
Account: "123456789012",
Arn: "arn:aws:sts::123456789012:federated-user/Alice"
}Root User Response:
// Example response for root user
{
UserId: "123456789012",
Account: "123456789012",
Arn: "arn:aws:iam::123456789012:root"
}Authentication Verification:
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
const verifyAuthentication = async () => {
const client = new STSClient({ region: "us-east-1" });
try {
const identity = await client.send(new GetCallerIdentityCommand({}));
console.log('Authentication successful');
console.log(`Authenticated as: ${identity.Arn}`);
return { authenticated: true, identity };
} catch (error) {
console.error('Authentication failed:', error);
return { authenticated: false, error };
}
};
const authResult = await verifyAuthentication();Cross-Account Validation:
const validateCrossAccountAccess = async (trustedAccounts: string[]) => {
const client = new STSClient({ region: "us-east-1" });
const identity = await client.send(new GetCallerIdentityCommand({}));
if (identity.Account && trustedAccounts.includes(identity.Account)) {
console.log(`Access granted from trusted account: ${identity.Account}`);
return true;
} else {
console.warn(`Access denied from untrusted account: ${identity.Account}`);
return false;
}
};
await validateCrossAccountAccess(['123456789012', '987654321098']);Role Session Information:
const getRoleSessionInfo = async () => {
const client = new STSClient({ region: "us-east-1" });
const identity = await client.send(new GetCallerIdentityCommand({}));
if (identity.Arn?.includes('assumed-role')) {
const parts = identity.Arn.split('/');
const roleName = parts[1];
const sessionName = parts[2];
console.log(`Role: ${roleName}`);
console.log(`Session: ${sessionName}`);
return { roleName, sessionName };
} else {
console.log('Not an assumed role session');
return null;
}
};
const sessionInfo = await getRoleSessionInfo();Identity operations have minimal error scenarios but should still be handled:
import { STSClient, GetCallerIdentityCommand, STSServiceException } from "@aws-sdk/client-sts";
const safeIdentityCheck = async () => {
const client = new STSClient({ region: "us-east-1" });
try {
const identity = await client.send(new GetCallerIdentityCommand({}));
return { success: true, data: identity };
} catch (error) {
if (error instanceof STSServiceException) {
console.error(`STS Error: ${error.name} - ${error.message}`);
} else {
console.error('Unexpected error:', error);
}
return { success: false, error };
}
};
const result = await safeIdentityCheck();
if (result.success) {
console.log('Identity:', result.data);
} else {
console.log('Failed to get identity');
}