使用AWS Java SDK为没有角色的基于角色的联合用户创建SQS

时间:2019-04-01 05:14:19

标签: java amazon-web-services aws-sdk amazon-sqs aws-java-sdk

我正在尝试使用AWS Java SDK创建SQS。我没有访问密钥和密钥ID,我通过公司提供的链接进入AWS控制台。这是基于角色的SAML访问(联合登录)。每当我尝试从Java代码创建SQS时,要么出现403错误(如果我不编写任何凭证代码),要么尝试在AWS博客中为联盟用户指定的代码时遇到更多错误。

我尝试了以下代码,但它不起作用:

AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder
                    .standard()
                    .withCredentials(new DefaultAWSCredentialsProviderChain())
                    .withRegion(Regions.EU_WEST_1)
                    .build();

GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
            getFederationTokenRequest.setDurationSeconds(7200);
            getFederationTokenRequest.setName("<username>@<company>.com");

// Define the policy and add it to the request.
            Policy policy = new Policy();
            policy.withStatements(new Statement(Statement.Effect.Allow)
                    .withActions(SQSActions.AllSQSActions)
                    .withResources(new Resource("arn:aws:sqs:::test-queue")));
            getFederationTokenRequest.setPolicy(policy.toJson());

// Get the temporary security credentials.
            GetFederationTokenResult federationTokenResult = stsClient.getFederationToken(getFederationTokenRequest);

Credentials sessionCredentials = federationTokenResult.getCredentials();

// Package the session credentials as a BasicSessionCredentials BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(
                    sessionCredentials.getAccessKeyId(),
                    sessionCredentials.getSecretAccessKey(),
                    sessionCredentials.getSessionToken());

AmazonSQSAsync amazonSQS = AmazonSQSAsyncClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(basicSessionCredentials))
                    .withRegion(Regions.EU_WEST_1)
                    .build();

CreateQueueRequest request = new CreateQueueRequest("wifi-test-queue");

String result = amazonSQS.createQueue(request).getQueueUrl();

不幸的是,以上代码无法正常工作。 我确信我的帐户具有创建/访问SQS的权限,因为我可以使用Terraform达到类似的目的。

有人可以帮助我如何使用该帐户创建资源吗?

1 个答案:

答案 0 :(得分:0)

您需要包括AWS区域和帐号的通配符

new Resource("arn:aws:sqs:*:*:test-queue")

您可以使用IAM simulator

测试等效的IAM策略
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sqs:CreateQueue",
            "Resource": "arn:aws:sqs:*:*:test-queue"
        }
    ]
}