I am trying to assume a role in my typescript application. I have a User set up in AWS and defined as my default user on my machine. I have a Role defined in IAM with the permissions I want to have and the associated Trust Policy to allow my local user to assume it (as far as I can tell). Here is the Trust Policy for the Role (Note I am using 0123456789
as a substitute for my actual Account Id):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::0123456789:user/LocalUser"
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}
Here are the Permissions of the Role
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowIAM",
"Effect": "Allow",
"Action": [
"iam:*",
],
"Resource": "*"
}
]
}
The User also has the following in it's Permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AsssumeRole",
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Resource": [
"arn:aws:iam::0123456789:role/TestRole"
]
}
]
}
Finally here is an MWE of my index.ts
file:
import {STSClient,AssumeRoleCommand,GetCallerIdentityCommand} from "@aws-sdk/client-sts";
import { IAMClient, GetRoleCommand } from "@aws-sdk/client-iam";
const getCredentials = async (accountId: string, roleName: string) => {
const sts_client = new STSClient({ region: "us-east-1" });
const command = new AssumeRoleCommand({
RoleArn: `arn:aws:iam::${accountId}:role/${roleName}`,
RoleSessionName: "TestSession",
});
const response = await sts_client.send(command);
const creds = response.Credentials;
console.log(creds); // Returns AccessKeyId, SecretAccessKey, SessionToken and Expiration
return {
accessKeyId: creds?.AccessKeyId,
secretAccessKey: creds?.SecretAccessKey,
sessionToken: creds?.SessionToken,
region: "us-east-1",
};
};
export default async function run() {
const RoleName = "TestRole";
const AccountId = "0123456789";
const accessCreds = await getCredentials(AccountId, RoleName);
const sts_client_tester = new STSClient(accessCreds);
const sts_identity = await sts_client_tester.send(
new GetCallerIdentityCommand({})
);
console.log(sts_identity); // Returns Local Account, not Assumed Account!!
const iam_client = new IAMClient(accessCreds);
const iam_input = { RoleName: RoleName };
const iam_command = new GetRoleCommand(iam_input);
const iam_response = await iam_client.send(iam_command);
console.log(iam_response); // Permission Error because Local Account does not have permissions
}
Note that the AssumeRoleCommand
does not throw any error when I send()
it, and it is successful, but when I try to use these credentials, it is not working.