[Lambda + Boto3] More secure STS authentication between AWS accounts

Posted in aws, blog on November 4, 2020 by Henk Verlinde ‐ 2 min read

[Lambda + Boto3] More secure STS authentication between AWS accounts


What is STS? You can use AWS Security Token Service (AWS STS) to create and provide trusted users with temporary security credentials that can control their access to your AWS resources. The difference from access key authentication information is as follows.

  1. Authentication information issued by STS is temporary and disappears after a certain period of time. (The time can be set from several minutes to several hours)
  2. Credentials issued by the STS are never stored with the user and are provided upon user request. Using access keys owned by IAM users can lead to unexpected security incidents. It is safer to create and use users with temporary access keys issued by STS.

Based on the above, create a Lambda that references the information of a more secure account.

Create AssumeRole with reference

Create reference table

AssumeRole is a role that allows the use of STS. Proceed to create an IAM role.

Enter the account ID of the destination AWS account in [Account ID]

Select the policy [AmazonDynamoDBFullAccess] because we want this role to have access to DynamoDB.

Please fill in if necessary. Not entered this time.

Enter an appropriate role name. This time, it will be [assumeRoleDynamoDB]. Now let’s create the role.

Create DynamoDB with referrer

Create a DynamoDB to reference for testing. Name it [sample_tbl].

Create Lambda function with reference

Enter the code below to run the Lambda function.

import boto3

def get_external_account_session():
   // Enter the Arn of the role created earlier
   role_arn = "arn:aws:iam::***********:role/assumeRoleDynamoDB"

   assume_role = boto3.client('sts').assume_role(
       RoleArn = role_arn,
       RoleSessionName = 'testSession'

   session = boto3.session.Session(
       aws_access_key_id = assume_role.get('Credentials').get('AccessKeyId'),
       aws_secret_access_key = assume_role.get('Credentials').get('SecretAccessKey'),
       aws_session_token = assume_role.get('Credentials').get('SessionToken'),
       region_name = "us-east-1"
   return session

def lambda_handler(event,context):
   external_session = get_external_account_session()
   external_dynamodb = external_session.client('dynamodb')
   external_table = external_dynamodb.scan(TableName = "sample_tbl")

   return external_table

that’s all.