如何在我的 Java 应用程序中使用 Amazon Web Services 政策声明?

How can I use Amazon Web Services policy statement in my Java application?

我想从后端 Java 应用程序发送 Amazon SNS 消息Amazon SQS 队列。根据 SNS 开发人员指南 (http://docs.aws.amazon.com/sns/latest/dg/sns-dg.pdf),在 "Sending Amazon SNS Messages to Amazon SQS Queues" 部分的主题下 - "Step 2. Give permission to the Amazon SNS topic to send messages to the Amazon SQS queue",写成,

If you wanted to create the policy document yourself, you would create a policy like the following. The policy allows MyTopic to send messages to MyQueue.

{
  "Version":"2012-10-17",
  "Statement":[
  {
    "Sid":"MySQSPolicy001",
    "Effect":"Allow",
    "Principal":"*",
    "Action":"sqs:SendMessage",
    "Resource":"arn:aws:sqs:us-east-1:123456789012:MyQueue",
    "Condition":{
                  "ArnEquals":{
                     "aws:SourceArn":"arn:aws:sns:us-east-1:123456789012:MyTopic"
                   }
              }
         }
    ]
}

我的疑惑是如何在我的 java 应用程序中使用此策略文档(.json 文件,如果我没记错的话)以及在哪里使用它?因为我必须在队列上设置允许 Amazon SNS 主题执行 sqs:SendMessage 操作的策略。 TIA.

您不必在 Java 应用程序中执行此操作。

转到 AWS 控制台,select IAM service,选择一个用户(或创建一个),然后在权限下附加策略。

这是它的样子:

策略(JSON 文档)可以从列表中选择、使用向导生成或手动输入(这就是您想要的)。

这里有一个Java示例,用于创建SNS主题和SQS队列,将SQS队列订阅到SNS主题,授予SNS向队列发送消息的权限,向SNS发送消息,以及从队列中读取它。

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.policy.Condition;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.auth.policy.Resource;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.auth.policy.actions.SQSActions;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;

import java.util.Arrays;
import java.util.Optional;

public class CreateSnsAndSqs {
    private static final String SNS_TOPIC = "my-sns-topic";
    private static final String SQS_NAME = "my-sqs-queue";

    public static void main(String... argv) {
        String regionName = Optional.ofNullable(System.getenv("AWS_DEFAULT_REGION")).orElse("us-east-1");
        Region region = RegionUtils.getRegion(regionName);
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
        DefaultAWSCredentialsProviderChain credentialsChain = new DefaultAWSCredentialsProviderChain();
        AmazonSNS sns = region.createClient(AmazonSNSClient.class, credentialsChain, clientConfiguration);
        AmazonSQS sqs = region.createClient(AmazonSQSClient.class, credentialsChain, clientConfiguration);
        String sqsUrl = sqs.createQueue(new CreateQueueRequest(SQS_NAME)).getQueueUrl();
        String snsTopicArn = sns.createTopic(SNS_TOPIC).getTopicArn();
        String sqsArn = sqs.getQueueAttributes(sqsUrl, Arrays.asList("QueueArn")).getAttributes().get("QueueArn");
        String sqsSubscriptionArn = sns.subscribe(snsTopicArn, "sqs", sqsArn).getSubscriptionArn();
        Policy allowSnsToPostToSqsPolicy = new Policy("allow sns " + snsTopicArn + " to send to queue", Arrays.asList(
                new Statement(Statement.Effect.Allow)
                        .withPrincipals(Principal.All)
                        .withActions(SQSActions.SendMessage)
                        .withResources(new Resource(sqsArn))
                        .withConditions(new Condition().withType("ArnEquals").withConditionKey("aws:SourceArn").withValues(snsTopicArn))
        ));
        sqs.setQueueAttributes(new SetQueueAttributesRequest().withQueueUrl(sqsUrl).addAttributesEntry("Policy", allowSnsToPostToSqsPolicy.toJson()));
        String sqsSubscriptionArn = sns.subscribe(snsTopicArn, "sqs", sqsArn).getSubscriptionArn();
        sns.publish(snsTopicArn, "Hello world");
        ReceiveMessageResult receiveResp = sqs.receiveMessage(new ReceiveMessageRequest(sqsUrl).withWaitTimeSeconds(10));
        for (Message message: receiveResp.getMessages()) {
            System.out.println("Received message " + message.getBody());
            sqs.deleteMessage(sqsUrl, message.getReceiptHandle());
        }
        System.out.println("Deleting");
        sns.deleteTopic(snsTopicArn);
        sqs.deleteQueue(sqsUrl);
    }
}

它像这样将消息打印到控制台:

Received message {
  "Type" : "Notification",
  "MessageId" : "add8d56a-19e6-5806-9424-9a2a796f8f94",
  "TopicArn" : "arn:aws:sns:us-east-1:111111111111:my-sns-topic",
  "Message" : "Hello world",
  "Timestamp" : "2016-02-19T00:14:01.973Z",
  "SignatureVersion" : "1",
  "Signature" : "XXXaLONGSIGNATUREXXX",
  "SigningCertURL" : "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem",
  "UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:111111111111:my-sns-topic:5e4d08a2-bcdb-4943-afef-5b7b02e30d5a"
}
Deleting