简体   繁体   中英

AWS Lambda: How to access other account's bucket using IAM Roles in Java

I have 2 accounts

Account A and Account B

In account AI have deployed (Amazon S3) my Lambda function.

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class LambdaFunctionHandler implements RequestHandler<Request, Response> {

    public Response handleRequest(Request request, Context context) {
        String greetingString = String.format("Hello %s %s.",
                request.firstName, request.lastName);
        //Here I need to get the Account B's bucket info
        return new Response(greetingString);
    }

}

In account AI am creating the IAM Role 'my-lambda' and same is mapped to the user X

In Account BI have created the policy to grant user permission with role 'my-lambda' How to get the bucket info of the Account B by using user X's IAM Role???

Note: I am able to get the bucket info of Account B if I give the credentials directly

AWSCredentials longTermCredentials_ = new PropertiesCredentials(LambdaFunctionHandler .class.getResourceAsStream("/resources/"+"AwsCredentials.properties"));
AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(longTermCredentials_);
GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
GetSessionTokenResult sessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest);
Credentials sessionCredentials = sessionTokenResult.getCredentials();
BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(sessionCredentials.getAccessKeyId(),sessionCredentials.getSecretAccessKey(),sessionCredentials.getSessionToken());
AmazonS3Client s3Client = new AmazonS3Client(basicSessionCredentials);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName("bucketName");
ObjectListing objectListing;
 do {
            objectListing = s3.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing
                    .getObjectSummaries()) {
                String key = objectSummary.getKey();

            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());

You can use the STSAssumeRoleSessionCredentialsProvider class to help assume the role based on your long-term credentials and getting temporary credentials to the S3 Client.

AWSCredentials longTermCredentials_ =  ...
STSAssumeRoleSessionCredentialsProvider roleCredsProvider = 
    new STSAssumeRoleSessionCredentialsProvider(
        longTermCredentials_, 
        "my_lambda", 
        "BucketListSession");
AmazonS3Client s3Client = new AmazonS3Client(roleCredsProvider);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM