This article highlights the preliminary steps of performing AWS API calls in Javascript for a cross account role.

Setting up for cross account roles is outside the scope of this, so if you need more information on that, visit AWS policies and groups for cross account access.

There are a multitude of reasons and benefits for taking the cross account approach. At the end of the day, they usually boil down to security, billing and access to customer accounts.

In the AWS Console, you can easily switch roles by using a link specific to switching to the cross account role. In code we will need to do something slightly different.

API calls relating to assuming roles can be found in the AWS.STS API here. Essentially you need to use it to generate temporary credentials(access key and secret key) to use for the cross account. These are short lived credentials, so don’t expect it to be valid once it has passed its expiry date.

You should also know the cross account policy role ARN. Unless you already have it, follow the steps below:

  1. Go into the AWS console

  2. Navigate to IAM section

  3. Click on the Users tab

  4. Click on your username (i.e. joe.bloggs) AWS Username

  5. Click on Permissions AWS Permissions Tab

  6. Click on the policy drop down arrow that corresponds to the Cross Account you intend to get access AWS Role View

  7. Copy the role ARN (see Resources field i.e. arn:aws:iam:666666:role/BlahRole) within the JSON policy document

  8. Substitute it as the RoleArn parameter (see code below)

In code once you have imported the AWS SDK in JS, we can specify something like below:

new AWS.STS().assumeRole({
   RoleArn: arn:aws:iam:666666:role/BlahRole,
   RoleSessionName: Freds Session
   DurationSeconds: 1000
},(err, data) => {
    let credentials = new AWS.Credentials()

     credentials.accessKeyId = data.Credentials.AccessKeyId
     credentials.secretAccessKey = data.Credentials.SecretAccessKey
     credentials.sessionToken = data.Credentials.SessionToken
     credentials.expiryTime = data.Credentials.Expiration

     let s3Svc = new AWS.S3({
        credentials: credentials
     })

     let snsSvc = new AWS.SNS({
        credentials: credentials
     })
})

At some point in time you will want to check if the credentials has expired and refresh it otherwise. You can easily achieve this as specified below:

if(credentials.needsRefresh()) {
    credentials.refresh()
}

Thats about it!

The next step you will need to consider is how you choose to manage the temporary credentials so they are refreshed (when expired) as and when needed again.

Regardless of it being short lived credentials, security is still top priority and you should ensure that at no point in time they are exposed publicly.