gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:58 25 4
gpt4 key购买 nike

我有2个帐户

账户A和账户B

在账户 A 中,我已部署 (Amazon S3) 我的 Lambda 函数。

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);
}

}

在账户 A 中,我正在创建 IAM 角色“my-lambda”,并将其映射到用户 X

在账户 B 中,我创建了策略来授予角色“my-lambda”的用户权限如何利用用户X的IAM角色获取账户B的bucket信息???

注意:如果我直接提供凭据,我可以获取帐户 B 的存储桶信息

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());

最佳答案

您可以使用STSAssumeRoleSessionCredentialsProvider类来帮助根据您的长期凭据承担角色并获取 S3 客户端的临时凭据。

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

关于java - AWS Lambda : How to access other account's bucket using IAM Roles in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com