Sns DG
Sns DG
Notification Service
Developer Guide
API Version 2010-03-31
Amazon Simple Notification Service Developer Guide
Table of Contents
What is Amazon SNS? ........................................................................................................................ 1
Are You a First-Time Amazon Simple Notification Service User? ........................................................ 2
Beyond the Getting Started Section ............................................................................................. 2
Accessing Amazon SNS ............................................................................................................... 2
Getting Started .................................................................................................................................. 4
Before You Begin ....................................................................................................................... 4
Create a Topic ........................................................................................................................... 5
Subscribe to a Topic ................................................................................................................... 5
Publish to a Topic ...................................................................................................................... 6
Create Different Messages for Each Protocol .......................................................................... 7
Clean Up ................................................................................................................................... 8
Using the SDK for Java ............................................................................................................... 9
Using the AWS SDK for .NET ...................................................................................................... 10
How Amazon SNS Works ................................................................................................................... 13
Common Scenarios ................................................................................................................... 13
Fanout ............................................................................................................................ 13
Application and System Alerts ........................................................................................... 13
Push Email and Text Messaging ......................................................................................... 14
Mobile Push Notifications .................................................................................................. 14
Message Durability ........................................................................................................... 14
Amazon SNS Topic Attributes .................................................................................................... 14
Configuring Message Delivery Status Attributes with the AWS Management Console ................. 15
Configuring Message Delivery Status Attributes for Topics Subscribed to Amazon SNS
Endpoints with the AWS SDKs ........................................................................................... 15
Message Attributes ................................................................................................................... 17
Message Attribute Items and Validation .............................................................................. 17
Data Types ...................................................................................................................... 18
Reserved Message Attributes for Mobile Push Notifications .................................................... 18
Applying Message Attributes ............................................................................................. 19
Message Filtering ..................................................................................................................... 24
Subscription Filter Policies ................................................................................................. 24
Applying .......................................................................................................................... 28
Removing ........................................................................................................................ 31
Example: Filter Policy as a Java Collection ........................................................................... 33
Message and JSON Formats ....................................................................................................... 35
HTTP/HTTPS Headers ....................................................................................................... 36
HTTP/HTTPS Subscription Confirmation JSON Format .......................................................... 36
HTTP/HTTPS Notification JSON Format .............................................................................. 38
HTTP/HTTPS Unsubscribe Confirmation JSON Format ........................................................... 39
SetSubscriptionAttributes Delivery Policy JSON Format ......................................................... 40
SetTopicAttributes Delivery Policy JSON Format ................................................................... 41
Large Payload and Raw Message Delivery .................................................................................... 42
Enabling Raw Message Delivery with the AWS Management Console ....................................... 42
System-to-System Messaging ............................................................................................................. 43
With Lambda Function as Subscriber .......................................................................................... 43
Prerequisites .................................................................................................................... 43
Configuring Amazon SNS with Lambda Endpoints with the AWS Management Console .............. 43
With Amazon SQS Queue as Subscriber ...................................................................................... 44
Step 1: Get the ARN of the Queue and Topic ....................................................................... 45
Step 2: Give Permission to the Amazon SNS Topic to Send Messages to the Amazon SQS Queue .. 46
Step 3: Subscribe the Queue to the Amazon SNS Topic ......................................................... 46
Step 4: Give Users Permissions to the Appropriate Topic and Queue Actions ............................. 47
Step 5: Test the Topic's Queue Subscriptions ....................................................................... 49
Sending Messages to a Queue in a Different Account ............................................................ 50
Using an AWS CloudFormation Template to Create a Topic that Sends Messages to Amazon
SQS Queues .................................................................................................................... 53
With HTTP/S Endpoint as Subscriber .......................................................................................... 57
Step 1: Make Sure Your Endpoint is Ready to Process Amazon SNS Messages ............................ 58
Step 2: Subscribe the HTTP/HTTPS endpoint to the Amazon SNS topic ................................... 61
Step 3: Confirm the subscription ........................................................................................ 61
Step 4: Set the delivery retry policy for the subscription (optional) ......................................... 62
Step 5: Give users permissions to publish to the topic (optional) ............................................. 62
Step 6: Send messages to the HTTP/HTTPS endpoint ........................................................... 63
Setting Amazon SNS Delivery Retry Policies for HTTP/HTTPS Endpoints .................................. 63
Certificate Authorities for HTTPS Endpoints ......................................................................... 69
Verifying Message Signatures ............................................................................................. 81
Example Code for an Endpoint Java Servlet ......................................................................... 83
User Notifications ............................................................................................................................. 87
With Mobile Application as Subscriber (Mobile Push) .................................................................... 87
Overview ......................................................................................................................... 87
Prerequisites .................................................................................................................... 88
Mobile Push High‐Level Steps ............................................................................................ 89
Getting Started with ADM ................................................................................................. 90
Getting Started with APNS ................................................................................................ 94
Getting Started with Baidu .............................................................................................. 100
Getting Started with GCM ............................................................................................... 116
Getting Started with MPNS ............................................................................................. 120
Getting Started with WNS ............................................................................................... 123
Using Amazon SNS Mobile Push ....................................................................................... 126
Application Attributes for Message Delivery Status ............................................................. 139
Application Event Notifications ......................................................................................... 142
Amazon SNS TTL ............................................................................................................ 144
Amazon SNS Mobile Push APIs ......................................................................................... 146
API Errors ...................................................................................................................... 147
With Mobile Phone Number as Subscriber (Send SMS) ................................................................. 153
Setting Preferences ......................................................................................................... 154
Sending a Message ......................................................................................................... 157
Sending a Message to Multiple Phone Numbers ................................................................. 161
Monitoring SMS Activity .................................................................................................. 167
Managing Subscriptions ................................................................................................... 172
Reserving a Short Code ................................................................................................... 177
Supported Regions and Countries ..................................................................................... 178
Monitoring and Logging .................................................................................................................. 186
Monitoring Topics Using CloudWatch ........................................................................................ 186
Access CloudWatch Metrics for Amazon SNS ...................................................................... 186
Set CloudWatch Alarms for Amazon SNS Metrics ................................................................ 187
Amazon SNS Metrics ....................................................................................................... 188
Dimensions for Amazon Simple Notification Service Metrics ................................................. 190
Logging API Calls Using CloudTrail ........................................................................................... 191
Amazon SNS Information in CloudTrail .............................................................................. 191
Example: Amazon SNS Log File Entries .............................................................................. 192
Security ......................................................................................................................................... 195
Authentication and Access Control ............................................................................................ 195
Overview of Managing Access .......................................................................................... 195
Special Information for Amazon SNS Policies ..................................................................... 209
Controlling User Access to Your AWS Account .................................................................... 210
Publishing to a Topic from a VPC ............................................................................................. 216
Tutorial: Publishing Messages Privately from a VPC ............................................................. 217
Creating a VPC Endpoint for Amazon SNS ......................................................................... 226
Server-Side Encryption ............................................................................................................ 227
Encryption Scope ............................................................................................................ 228
When using Amazon SNS, you (as the owner) create a topic and control access to it by defining policies
that determine which publishers and subscribers can communicate with the topic. A publisher sends
messages to topics that they have created or to topics they have permission to publish to. Instead of
including a specific destination address in each message, a publisher sends a message to the topic.
Amazon SNS matches the topic to a list of subscribers who have subscribed to that topic, and delivers
the message to each of those subscribers. Each topic has a unique name that identifies the Amazon SNS
endpoint for publishers to post messages and subscribers to register for notifications. Subscribers receive
all messages published to the topics to which they subscribe, and all subscribers to a topic receive the
same messages.
Topics
• Are You a First-Time Amazon Simple Notification Service User? (p. 2)
• Beyond the Getting Started Section (p. 2)
• Accessing Amazon SNS (p. 2)
You have detailed control over which endpoints a topic allows, who is able to publish to a topic, and
under what conditions. This section shows you how to control access through the use of access control
policies.
• Monitoring Amazon SNS Topics Using CloudWatch (p. 186)
Amazon SNS and CloudWatch are integrated so you can collect, view, and analyze metrics for every
active Amazon SNS topic.
• With an Amazon SQS Queue as a Subscriber (p. 44)
You can use Amazon SNS to send messages to one or more Amazon SQS queues.
• Using Amazon SNS for User Notifications with a Mobile Phone Number as a Subscriber (Send
SMS) (p. 153)
You can use Amazon Simple Notification Service (Amazon SNS) to send SMS notifications to SMS-
enabled mobile phones and smart phones.
• With an HTTP/S Endpoint as a Subscriber (p. 57)
You can use Amazon SNS to send notification messages to one or more HTTP or HTTPS endpoints.
The AWS Management Console provides a web interface where you can manage your compute,
storage, and other cloud resources. Within the AWS Management Console, individual services have
their own console. To open the Amazon SNS console, log in to https://console.aws.amazon.com/
and choose SNS from the console home page, or use the SNS console direct URL: https://
console.aws.amazon.com/sns/. For a tutorial that helps you complete common SNS tasks in the
console, see Getting Started with Amazon Simple Notification Service (p. 4).
AWS Command Line Interface (CLI)
Provides commands for a broad set of AWS products, and is supported on Windows, Mac, and Linux.
To get started, see AWS Command Line Interface User Guide. For more information about the
commands for Amazon SNS, see sns in the AWS CLI Command Reference.
Provides commands for a broad set of AWS products for those who script in the PowerShell
environment. To get started, see the AWS Tools for Windows PowerShell User Guide. For more
information about the cmdlets for Amazon SNS, see Amazon Simple Notification Service in the AWS
Tools for PowerShell Cmdlet Reference.
AWS SDKs
AWS provides SDKs (software development kits) that consist of libraries and sample code for various
programming languages and platforms (Java, Python, Ruby, .NET, iOS, Android, etc.). The SDKs
provide a convenient way to create programmatic access to Amazon SNS and AWS. For example, the
SDKs take care of tasks such as cryptographically signing requests, managing errors, and retrying
requests automatically. For information about the AWS SDKs, including how to download and install
them, see the Tools for Amazon Web Services page.
Amazon SNS Query API
You can access Amazon SNS and AWS programmatically by using the Amazon SNS Query API,
which lets you issue requests directly to the service. For more information, see the Amazon Simple
Notification Service API Reference.
Topics
• Before You Begin (p. 4)
• Create a Topic (p. 5)
• Subscribe to a Topic (p. 5)
• Publish to a Topic (p. 6)
• Clean Up (p. 8)
• Using the AWS SDK for Java with Amazon SNS (p. 9)
• Using the AWS SDK for .NET with Amazon SNS (p. 10)
Part of the sign-up procedure involves receiving a phone call and entering a verification code using
the phone keypad.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. Choose the Get Started button.
Create a Topic
Now that you're signed up for Amazon SNS, you're ready to create a topic. A topic is a communication
channel to send messages and subscribe to notifications. It provides an access point for publishers and
subscribers to communicate with each other. In this section you create a topic named MyTopic.
To create a topic
arn:aws:sns:us-west-2:111122223333:MyTopic
Subscribe to a Topic
To receive messages published to a topic, you have to subscribe an endpoint to that topic. An endpoint is
a mobile app, web server, email address, or an Amazon SQS queue that can receive notification messages
from Amazon SNS. Once you subscribe an endpoint to a topic and the subscription is confirmed, the
endpoint will receive all messages published to that topic.
In this section you subscribe an endpoint to the topic you just created in the previous section. You
configure the subscription to send the topic messages to your email account.
To subscribe to a topic
7. Go to your email application and open the message from AWS Notifications, and then choose the
link to confirm your subscription.
Publish to a Topic
Publishers send messages to topics. Once a new message is published, Amazon SNS attempts to deliver
that message to every endpoint that is subscribed to the topic. In this section you publish a message to
the email address you defined in the previous task.
To publish to a topic
In the left navigation pane, choose Topics and then select the topic you want to publish to.
2. Choose the Publish to topic button.
You can now use your email application to open the message from AWS Notifications and read the
message.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select a topic.
3. Choose the Publish to topic button.
You can now modify the message text so that it is tailored to each type of client.
The SMS message can contain up to 160 ASCII (or 70 Unicode) characters. If the message exceeds
this length, Amazon SNS sends it as multiple messages, each fitting within the character limit.
Messages are not cut off in the middle of a word but on whole-word boundaries.
In the following example, messages are specified for the default, email, and SMS protocols.
{
"default": "Message body text here.",
"email": "Message body text here.",
"sms": "Message body text here."
}
Clean Up
You have created a topic, subscribed to it, and published a message to the topic. Now you clean up your
environment by unsubscribing from the topic and then deleting the topic.
The subscription is deleted, unless it is a pending subscription, meaning it has not yet been confirmed.
You cannot delete a pending subscription, but if it remains pending for 3 days, Amazon SNS
automatically deletes it.
To delete a topic
Open the Amazon SNS console at https://console.aws.amazon.com/sns/v2/home.
1. In the left navigation pane, choose Topics, and then select the topic you want to delete.
2. Choose the Actions drop-down list and select Delete topics.
3. Choose Delete.
When you delete a topic, you also delete all subscriptions to that topic.
The AmazonSNSClient class defines methods that map to underlying Amazon SNS Query API actions.
(These actions are described in the Amazon SNS API Reference). When you call a method, you must
create a corresponding request object and response object. The request object includes information that
you must pass with the actual request. The response object includes information returned from Amazon
SNS in response to the request.
For example, the AmazonSNSClient class provides the createTopic method to create a topic to which
notifications can be published. This method maps to the underlying CreateTopic API action. You create a
CreateTopicRequest object to pass information with the createTopic method.
The following import statements are used with the provided Java samples.
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import com.amazonaws.services.sns.model.DeleteTopicRequest;
The following example shows how to create a new Amazon SNS client, set the Amazon SNS endpoint to
use, and then create a new topic.
Note
In some of the following examples, the getCachedResponseMetadata method is used to
show how to programmatically retrieve the request ID for a previously executed successful
Amazon SNS request. This is typically used for debugging issues and is helpful when requesting
assistance from Amazon Web Services.
Create a Topic
When you run this example, the following is displayed in the console output window of your IDE, such as
Eclipse:
{TopicArn: arn:aws:sns:us-east-1:123456789012:MyNewTopic}
CreateTopicRequest - {AWS_REQUEST_ID=93f7fc90-f131-5ca3-ab18-b741fef918b5}
The following examples show how to subscribe to, publish to, and delete a topic.
Subscribe to a Topic
When you run this example, the following is displayed in the console output window of your IDE:
SubscribeRequest - {AWS_REQUEST_ID=9b7ff59a-f917-533a-a6bd-be4bf6df0acf}
Check your email and confirm subscription.
Publish to a Topic
When you run this example, the following is displayed in the console output window of your IDE:
MessageId - 9b888f80-15f7-5c30-81a2-c4511a3f5229
Delete a Topic
When you run this example, the following is displayed in the console output window of your IDE:
DeleteTopicRequest - {AWS_REQUEST_ID=067a4980-4e93-5bfc-b88c-0251415bc852}
The following import statements are used with the provided C# samples.
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
The following example shows how to create a new Amazon SNS client, set the Amazon SNS endpoint to
use, and then create a new topic.
Note
In some of the following examples, the GetCachedResponseMetadata method is used to
show how to programmatically retrieve the request ID for a previously executed successful
Amazon SNS request. This is typically used for debugging issues and is helpful when requesting
assistance from Amazon Web Services.
Create a Topic
When you run this example, the following is displayed in the console output window:
arn:aws:sns:us-east-1:123456789012:MyNewTopic
CreateTopicRequest - 93f7fc90-f131-5ca3-ab18-b741fef918b5
The following examples show how to subscribe to, publish to, and delete a topic.
Subscribe to a Topic
When you run this example, the following is displayed in the console output window of your IDE:
SubscribeRequest - 9b7ff59a-f917-533a-a6bd-be4bf6df0acf
Check your email and confirm subscription.
Publish to a Topic
When you run this example, the following is displayed in the console output window of your IDE:
MessageId - 9b888f80-15f7-5c30-81a2-c4511a3f5229
Delete a Topic
When you run this example, the following is displayed in the console output window of your IDE:
DeleteTopicRequest - 067a4980-4e93-5bfc-b88c-0251415bc852
For more information about .NET and AWS, see AWS Guide for .NET Developers.
For more information about the AWS SDK for .NET;, see Getting Started with the AWS SDK for .NET.
Topics
• Common Amazon SNS Scenarios (p. 13)
• Amazon SNS Topic Attributes for Message Delivery Status (p. 14)
• Amazon SNS Message Attributes (p. 17)
• Amazon SNS Message Filtering (p. 24)
• Amazon SNS Message and JSON Formats (p. 35)
• Amazon SNS Large Payload and Raw Message Delivery (p. 42)
Another way to use "fanout" is to replicate data sent to your production environment with your
development environment. Expanding upon the previous example, you could subscribe yet another
queue to the same topic for new incoming orders. Then, by attaching this new queue to your
development environment, you could continue to improve and test your application using data received
from your production environment. For more information about sending Amazon SNS messages to
Amazon SQS queues, see With an Amazon SQS Queue as a Subscriber (p. 44). For more information
about sending Amazon SNS messages to HTTP/S endpoints, see With an HTTP/S Endpoint as a
Subscriber (p. 57).
Message Durability
Amazon SNS provides durable storage of all messages that it receives. When Amazon SNS receives your
Publish request, it stores multiple copies of your message to disk. Before Amazon SNS confirms to you
that it received your request, it stores the message in multiple isolated locations known as Availability
Zones. The message is stored in Availability Zones that are located within your chosen AWS Region, such
as the US East (N. Virginia) Region. Although rare, should a failure occur in one Availability Zone, Amazon
SNS remains operational, and the durability of your messages persists.
• Application
• HTTP
• Lambda
• SQS
After you configure the message delivery status attributes, log entries will be sent to CloudWatch Logs
for messages sent to a topic subscribed to an Amazon SNS endpoint. Logging message delivery status
helps provide better operational insight, such as the following:
To configure topic attributes for message delivery status, you can use the AWS Management Console,
AWS software development kits (SDKs), or query API.
Topics
• Configuring Message Delivery Status Attributes with the AWS Management Console (p. 15)
• Configuring Message Delivery Status Attributes for Topics Subscribed to Amazon SNS Endpoints with
the AWS SDKs (p. 15)
To configure message delivery status for notifications from Amazon SNS to a Lambda
endpoint:
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left Navigation pane, choose Topics, and then choose the topic to which you want to receive
message delivery status information.
3. Choose Actions and then choose Delivery status.
4. Choose the Lambda check box.
5. On the Delivery Status dialog box, choose Create IAM Roles.
You will now be able to view and parse the CloudWatch Logs containing the message delivery status.
For more information about using CloudWatch, see the CloudWatch Documentation.
Topic Attributes
You can use the following topic attribute name values for message delivery status:
Application
• ApplicationSuccessFeedbackRoleArn
• ApplicationSuccessFeedbackSampleRate
• ApplicationFailureFeedbackRoleArn
Note
In addition to being able to configure topic attributes for message delivery status of
notification messages sent to Amazon SNS application endpoints, you can also configure
application attributes for the delivery status of push notification messages sent to push
notification services. For more information, see Using Amazon SNS Application Attributes for
Message Delivery Status.
HTTP
• HTTPSuccessFeedbackRoleArn
• HTTPSuccessFeedbackSampleRate
• HTTPFailureFeedbackRoleArn
Lambda
• LambdaSuccessFeedbackRoleArn
• LambdaSuccessFeedbackSampleRate
• LambdaFailureFeedbackRoleArn
SQS
• SQSSuccessFeedbackRoleArn
• SQSSuccessFeedbackSampleRate
• SQSFailureFeedbackRoleArn
The following Java example shows how to use the SetTopicAttributes API to configure topic
attributes for message delivery status of notification messages sent to topics subscribed to Amazon
SNS endpoints. In this example, it is assumed that string values have been set for topicArn,
attribName, and attribValue.
setTopicAttributesRequest.setAttributeValue(attribValue);
For more information about the SDK for Java, see Getting Started with the AWS SDK for Java.
AWS SDK for .NET
The following .NET example shows how to use the SetTopicAttributes API to configure topic
attributes for message delivery status of notification messages sent to topics subscribed to Amazon
SNS endpoints. In this example, it is assumed that string values have been set for topicArn,
attribName, and attribValue.
For more information about the AWS SDK for .NET, see Getting Started with the AWS SDK for .NET.
You can also use message attributes to help structure the push notification message for mobile
endpoints. In this scenario, the message attributes are only used to help structure the push notification
message. The attributes are not delivered to the endpoint, as they are when sending messages with
message attributes to Amazon SQS endpoints.
You can also use message attributes to make your messages filterable with subscription filter policies.
You apply filter policies to topic subscriptions. With a filter policy applied, a subscription receives
only those messages that have attributes that are accepted by the policy. For more information, see
??? (p. 24).
• Name – The message attribute name can contain the following characters: A-Z, a-z, 0-9, underscore(_),
hyphen(-), and period (.). The name must not start or end with a period, and it should not have
successive periods. The name is case-sensitive and must be unique among all attribute names for
the message. The name can be up to 256 characters long. The name cannot start with "AWS." or
"Amazon." (or any variations in casing) because these prefixes are reserved for use by Amazon Web
Services.
• Type – The supported message attribute data types are String, String.Array, Number, and
Binary. The data type has the same restrictions on the content as the message body. The data type
is case-sensitive, and it can be up to 256 bytes long. For more information, see the Message Attribute
Data Types and Validation (p. 18) section.
• Value – The user-specified message attribute value. For string data types, the value attribute has the
same restrictions on the content as the message body. For more information, see the Publish action in
the Amazon Simple Notification Service API Reference.
Name, type, and value must not be empty or null. In addition, the message body should not be empty or
null. All parts of the message attribute, including name, type, and value, are included in the message size
restriction, which is 256 KB.
• String – Strings are Unicode with UTF-8 binary encoding. For a list of code values, see http://
en.wikipedia.org/wiki/ASCII#ASCII_printable_characters.
• String.Array – An array, formatted as a string, that can contain multiple values. The values can be
strings, numbers, or the keywords true, false, and null.
• Number – Numbers are positive or negative integers or floating-point numbers. Numbers have
sufficient range and precision to encompass most of the possible values that integers, floats, and
9 9
doubles typically support. A number can have a value from -10 to 10 , with 5 digits of accuracy after
the decimal point. Leading and trailing zeroes are trimmed.
• Binary – Binary type attributes can store any binary data; for example, compressed data, encrypted
data, or images.
AWS.SNS.MOBILE.WNS.Tag (optional)
For more information about using message attributes with Baidu, see Using Message Attributes for
Structuring the Message (p. 115).
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, choose Topics. The Topics page provides all of the Amazon SNS topics that
you have in the selected region.
3. If you don't have a topic, choose Create a new topic, and provide a value for Topic name. If you
want to use the topic to send SMS messages, provide a value for Display name. Then, choose Create
topic.
4. If you have one or more topics, select the topic to which you want to publish the message. Then,
choose Publish to topic.
5. On the Publish a message page, provide a Subject and Message.
6. For Message Attributes, specify the key, attribute type, and value. For example, the following entry
creates an attribute named customer_interests. The attribute type is String.Array, and the
value is an array of values.
If the attribute type is String, String.Array, or Number, Amazon SNS evaluates the message
attribute against a subscription's filter policy, if present, before sending the message to that
subscription.
Remember
If the attribute type is String.Array, enclose the array in brackets ([ ]). Within the array,
enclose string values in double quotes. You don't need quotes for numbers or for the
keywords true, false, and null.
To publish a message with attributes using the AWS SDK for Java, use the publish method of the
AmazonSNS client. Provide a PublishRequest object as the argument. When you initialize the
PublishRequest object, use its withMessageAttributes method, which accepts a map of type
Map<String,MessageAttributeValue>.
To simplify the process of publishing messages with attributes, you can add the following example
class to your application and modify it as needed:
import com.amazonaws.services.sns.*;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
This class stores a messageAttributes field as a map. You use the overloaded addAttribute
methods to add attributes to your message. These methods can add attributes with the data type
String, String.Array, or Number. When you're ready to publish your message, use the publish
method, and provide an AmazonSNS client and topic ARN.
The following code shows how to initialize and use the example SNSMessage class:
// Publish message
message.publish(snsClient, topicArn);
To publish a message with attributes using the AWS SDK for .NET, use the Publish method of the
AmazonSimpleNotificationServiceClient client. Provide a PublishRequest object as the
argument. When you initialize the PublishRequest object, use its MessageAttributes method,
which accepts a Dictionary of type Map<String,MessageAttributeValue>.
To simplify the process of publishing messages with attributes, you can add the following example
class to your application and modify it as needed:
using System;
using System.Collections.Generic;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
namespace SNSCreatePlatformEndpoint
{
class SNSMessage
{
private String message;
private Dictionary<String, MessageAttributeValue> messageAttributes;
public string Message { get => this.message; set => this.message = value; }
}
}
}
This class stores a MessageAttributes field as a dictionary. You use the overloaded
AddAttribute methods to add attributes to your message. These methods can add attributes with
the data type String, String.Array, or Number. When you're ready to publish your message, use
the publish method, and provide an AmazonSimpleNotificationServiceClient client and
topic ARN.
The following code shows how to initialize and use the example SNSMessage class:
encryptedVal.Add(false);
message.AddAttribute("encrypted", encryptedVal);
// Publish message
message.Publish(snsClient, topicArn);
A filter policy is a simple JSON object. The policy contains attributes that define which messages
the subscriber receives. When you publish a message to a topic, Amazon SNS compares the message
attributes to the attributes in the filter policy for each of the topic's subscriptions. If there is a match
between the attributes, Amazon SNS sends the message to the subscriber. Otherwise, Amazon SNS skips
the subscriber without sending the message to it. If a subscription lacks a filter policy, the subscription
receives every message published to its topic.
With filter policies, you can simplify your usage of Amazon SNS by consolidating your message filtering
criteria into your topic subscriptions. With this consolidation, you can offload the message filtering logic
from subscribers and the message routing logic from publishers. Therefore, you don't need to filter
messages by creating a separate topic for each filtering condition. Instead, you can use a single topic, and
you can differentiate your messages with attributes. Each subscriber receives and processes only those
messages accepted by its filter policy.
For example, you could use a single topic to publish all messages generated by transactions from your
online retail site. To each message, you could assign an attribute that indicates the type of transaction,
such as order_placed, order_cancelled, or order_declined. By creating subscriptions with filter
policies, you can route each message to the queue that is meant to process the message's transaction
type.
For a tutorial demonstrating how to implement message filtering with the AWS Management Console,
see Filter Messages Published to Topics. This tutorial shows how to apply filter policies to route messages
to separate Amazon SQS queues.
a. Each attribute name in the filter policy matches an attribute name assigned to the message.
b. For each matching attribute name, at least one match exists between the values that are assigned to
that name in the filter policy and the message.
When Amazon SNS evaluates the message attributes against the policy, it ignores message attributes
that are not specified in the policy.
The following examples show how filter policies might accept or reject a message published to a topic.
{
"Type" : "Notification",
"MessageId" : "e3c4e17a-819b-5d95-a0e8-b306c25afda0",
"TopicArn" : "arn:aws:sns:us-east-1:111122223333:MySnsTopic",
"Message" : message body with transaction details . . .
"Timestamp" : "2017-11-07T23:28:01.631Z",
"SignatureVersion" : "1",
"Signature" : signature . . .
"UnsubscribeURL" : unsubscribe URL . . .
"MessageAttributes" : {
"customer_interests" : {"Type":"String.Array","Value":"[\"soccer\", \"rugby\", \"hockey
\"]"},
"store" : {"Type":"String","Value":"example_corp"},
"event" : {"Type":"String","Value":"order_placed"},
"price_usd" : {"Type":"Number","Value":210.75}
}
}
For information about applying attributes to a message, see Amazon SNS Message Attributes (p. 17).
Because this message includes attributes, any topic subscription that includes a filter policy can
selectively accept or reject the message.
The attributes in the following policy match the attributes that are assigned to the example message:
{
"store": ["example_corp"],
"event": [{"anything-but":"order_cancelled"}],
"customer_interests": ["rugby", "football", "baseball"],
"price_usd": [{"numeric":[">=", 100]}]
}
If any single attribute in this policy doesn't match one that's assigned to the message, the policy rejects
the message.
The following policy has multiple mismatches between its attributes and the attributes that are assigned
to the example message:
{
"store": ["example_corp"],
"event": ["order_cancelled"],
"encrypted": [false],
"customer_interests": ["basketball", "baseball"]
}
Because the encrypted attribute name isn't present in the message attributes, that policy attribute
rejects the message, regardless of the value that's assigned to it.
Filter policy attributes can have string or numeric values. With string and numeric values, you can use the
following operations to match message attributes and filter messages.
This matching occurs when a policy attribute value matches one or more message attribute values.
For example, the policy attribute:
"customer_interests": ["rugby"]
"customer_interests" : {"Type":"String","Value":"rugby"}
When a policy attribute value includes the anything-but keyword, it matches any message
attribute that doesn't include the policy attribute value. For example, the policy attribute:
"customer_interests": [{"anything-but":"rugby"}]
"customer_interests" : {"Type":"String","Value":"baseball"}
And:
"customer_interests" : {"Type":"String","Value":"football"}
But not:
"customer_interests" : {"Type":"String","Value":"rugby"}
Prefix matching
When a policy attribute includes the prefix keyword, its value matches any message attribute
value that begins with the specified characters. For example, the policy attribute:
"customer_interests": [{"prefix":"bas"}]
"customer_interests" : {"Type":"String","Value":"baseball"}
And:
"customer_interests" : {"Type":"String","Value":"basketball"}
But not:
"customer_interests" : {"Type":"String","Value":"rugby"}
Exact matching
When a policy attribute value includes the numeric keyword and the = operator, it matches any
message attribute that has the same name and an equal numeric value. For example, the policy
attribute:
"price_usd": [{"numeric":["=",301.5]}]
"price_usd" : {"Type":"Number","Value":301.5}
And:
"price_usd" : {"Type":"Number","Value":3.015e2}
Range matching
In addition to the = operator, a numeric policy attribute can include <, <=, >, and >=. For example,
the policy attribute:
AND/OR Logic
Apply AND/OR logic to your filter policies as follows.
AND logic
Apply AND logic by using multiple attribute names (keys). For example, the policy:
{
"customer_interests": ["rugby"],
"price_usd": [{"numeric":[">", 100]}]
}
Matches messages with a customer_interests value of rugby and a price_usd value that's
over 100.
OR logic
Apply OR logic by assigning multiple values to an attribute name. For example, the policy attribute:
Constraints
When you create a filter policy, remember the following constraints:
• Amazon SNS compares the policy attributes only to message attributes that have a data type of
String, String.Array, or Number. Message attributes with the Binary data type are ignored.
• The attribute comparison between policy and message is case sensitive for strings.
• As a JSON object, the filter policy can contain strings enclosed in quotes, numbers, and the unquoted
keywords true, false, and null.
• A filter policy can have up to 10 attribute names.
9 9
• A numeric policy attribute can have a value from -10 to 10 , with 5 digits of accuracy after the
decimal point.
• The maximum size of a policy is 256 KB.
• When you're using the Amazon SNS API, the policy JSON must be passed as a valid UTF-8 string.
• By default, you can have up to 200 filter policies per AWS account per region. To increase this limit,
submit an SNS Limit Increase case.
• The total combination of values must not exceed 100. Calculate the total combination by multiplying
the number of values in each array. For example, in the following policy, the first array has three
values, the second has one value, and the third has two values. The total combination is calculated as 3
x 1 x 2 = 6.
{
"key_a": ["value_one", "value_two", "value_three"],
"key_b": ["value_one"],
"key_c": ["value_one", "value_two"]
}
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, choose Subscriptions. The Subscriptions page provides all of the Amazon
SNS subscriptions that you have in the chosen region.
3. If you don't have a subscription, choose Create subscription, and provide values for Topic ARN,
Protocol, and Endpoint.
4. If you have one or more subscriptions, select the subscription to which you want to apply a filter
policy.
5. Choose Actions, and choose Edit subscription filter policy in the menu.
6. In the Edit subscription filter policy window, provide the JSON body of your filter policy.
7. Choose Set subscription filter policy. Amazon SNS applies your filter policy to the subscription.
For the --attribute-name option, specify FilterPolicy. For --attribute-value, specify your
JSON policy.
To provide valid JSON for your policy, enclose the attribute names and values in double quotes. You
must also enclose the entire policy argument in quotes. To avoid escaping quotes, you can use single
quotes to enclose the policy and double quotes to enclose the JSON names and values, as shown in the
example.
To verify that your filter policy was applied, use the get-subscription-attributes command. The
attributes in the terminal output should show your filter policy for the FilterPolicy key, as shown in
the following example:
To apply a filter policy with the AWS SDK for Java, use the setSubscriptionAttributes
method of the AmazonSNS client. Provide a SetSubscriptionAttributesRequest object as the
argument, as shown in the following example:
• subscriptionArn – The Amazon Resource Name (ARN) of the subscription to which the policy is
applied.
• attributeName – Must be "FilterPolicy".
• attributeValue – Your JSON filter policy as a string. Because you must enclose the string policy
in double quotes, remember to escape the double quotes that enclose the attribute names and
values, as in \"store\".
The SetSubscriptionAttributesRequest class accepts the filter policy as a string. If you want
to define your policy as a Java collection, create a map that associates each attribute name with a
list of values. To assign the policy to a subscription, you first produce a string version of the policy
from the contents of the map. You then pass the string as the attributeValue argument to
SetSubscriptionAttributesRequest.
AWS SDK for .NET
To apply a filter policy with the AWS SDK for .NET, use the SetSubscriptionAttributes
method of the AmazonSNS client. Provide a SetSubscriptionAttributesRequest object as the
argument, as shown in the following example:
• subscriptionArn – The Amazon Resource Name (ARN) of the subscription to which the policy is
applied.
• attributeName – Must be "FilterPolicy".
• attributeValue – Your JSON filter policy as a string. Because you must enclose the string policy
in double quotes, remember to escape the double quotes that enclose the attribute names and
values, as in \"store\".
The SetSubscriptionAttributesRequest class accepts the filter policy as a string. If you want
to define your policy as a C# collection, create a dictionary that associates each attribute name with
a list of values. To assign the policy to a subscription, you first produce a string version of the policy
from the contents of the dictionary. You then pass the string as the attributeValue argument to
SetSubscriptionAttributesRequest.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, choose Subscriptions. The Subscriptions page provides all of the Amazon
SNS subscriptions that you have in the chosen region.
3. Select the subscription that you want to remove the filter policy from.
4. Choose Actions, and choose Edit subscription filter policy in the menu.
5. In the Edit subscription filter policy window, provide an empty JSON body for your filter policy: {}.
6. Choose Set subscription filter policy. Amazon SNS applies your empty filter policy to the
subscription.
To remove a filter policy with the AWS SDK for Java, use the setSubscriptionAttributes
method of the AmazonSNS client. Provide a string that contains an empty JSON body as your filter
policy:
To remove a filter policy with the AWS SDK for .NET, use the SetSubscriptionAttributes
method of the AmazonSNS client. Provide a string that contains an empty JSON body as your filter
policy:
AWS CloudFormation begins to delete the MyFilterPolicyStack stack and displays the
DELETE_IN_PROGRESS status. When the process is complete, the stack is removed from the list.
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public <T extends Number> void addAttribute(String attributeName, String op, T value)
{
filterPolicy.put(attributeName, new Attribute(AttributeType.Numeric, new
NumericValue(op, value)));
}
This class stores a filterPolicy field as a map. You use the different addAttribute methods to add
attributes to your policy. These methods accept the attribute name as a string, and they are specialized
to accept different types of values. You can pass values as strings, lists of strings, numbers, or number
ranges. You can add anything-but and prefix attributes. When you're ready to apply your policy to
a subscription, use the apply method, and provide an AmazonSNS client and subscription ARN. This
method produces a policy string from the contents of the filterPolicy map, and it applies the policy
to the specified subscription.
The following code shows how to initialize and use the example SNSMessageFilterPolicy class:
Topics
• HTTP/HTTPS Headers (p. 36)
• HTTP/HTTPS Subscription Confirmation JSON Format (p. 36)
• HTTP/HTTPS Notification JSON Format (p. 38)
• HTTP/HTTPS Unsubscribe Confirmation JSON Format (p. 39)
• SetSubscriptionAttributes Delivery Policy JSON Format (p. 40)
• SetTopicAttributes Delivery Policy JSON Format (p. 41)
HTTP/HTTPS Headers
When Amazon SNS sends a subscription confirmation, notification, or unsubscribe confirmation message
to HTTP/HTTPS endpoints, it sends a POST message with a number of Amazon SNS-specific header
values. You can use these header values to do things such as identify the type of message without having
to parse the JSON message body to read the Type value.
x-amz-sns-message-type
The type of message. The possible values are SubscriptionConfirmation, Notification, and
UnsubscribeConfirmation.
x-amz-sns-message-id
A Universally Unique Identifier, unique for each message published. For a notification that Amazon
SNS resends during a retry, the message ID of the original message is used.
x-amz-sns-topic-arn
The Amazon Resource Name (ARN) for the topic that this message was published to.
x-amz-sns-subscription-arn
The following HTTP POST header is an example of a header for a Notification message to an HTTP
endpoint.
POST / HTTP/1.1
x-amz-sns-message-type: Notification
x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-
beaa-fcfcc21c8f55
Content-Length: 1336
Content-Type: text/plain; charset=UTF-8
Host: myhost.example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
The subscription confirmation message is a POST message with a message body that contains a JSON
document with the following name/value pairs.
Message
A string that describes the message. For subscription confirmation, this string looks like this:
MessageId
A Universally Unique Identifier, unique for each message published. For a message that Amazon SNS
resends during a retry, the message ID of the original message is used.
Signature
The URL to the certificate that was used to sign the message.
SubscribeURL
The URL that you must visit in order to confirm the subscription. Alternatively, you can instead use
the Token with the ConfirmSubscription action to confirm the subscription.
Timestamp
A value you can use with the ConfirmSubscription action to confirm the subscription. Alternatively,
you can simply visit the SubscribeURL.
TopicArn
The Amazon Resource Name (ARN) for the topic that this endpoint is subscribed to.
Type
POST / HTTP/1.1
x-amz-sns-message-type: SubscriptionConfirmation
x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
Content-Length: 1336
Content-Type: text/plain; charset=UTF-8
Host: myhost.example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "SubscriptionConfirmation",
"MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b",
"Token" :
"2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-
west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included
in this message.",
"SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-
west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd
"Timestamp" : "2012-04-26T20:45:04.751Z",
"SignatureVersion" : "1",
"Signature" : "EXAMPLEpH
+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH8
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-
f3ecfb7224c7233fe7bb5f59f96de52f.pem"
}
Message
The Message value specified when the notification was published to the topic.
MessageId
A Universally Unique Identifier, unique for each message published. For a notification that Amazon
SNS resends during a retry, the message ID of the original message is used.
Signature
Base64-encoded SHA1withRSA signature of the Message, MessageId, Subject (if present), Type,
Timestamp, and TopicArn values.
SignatureVersion
The URL to the certificate that was used to sign the message.
Subject
The Subject parameter specified when the notification was published to the topic. Note that this is
an optional parameter. If no Subject was specified, then this name/value pair does not appear in this
JSON document.
Timestamp
The Amazon Resource Name (ARN) for the topic that this message was published to.
Type
A URL that you can use to unsubscribe the endpoint from this topic. If you visit this URL, Amazon
SNS unsubscribes the endpoint and stops sending notifications to this endpoint.
The following HTTP POST message is an example of a Notification message to an HTTP endpoint.
POST / HTTP/1.1
x-amz-sns-message-type: Notification
x-amz-sns-message-id: 22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-
west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96
Content-Length: 773
Content-Type: text/plain; charset=UTF-8
Host: myhost.example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "Notification",
"MessageId" : "22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "My First Message",
"Message" : "Hello world!",
"Timestamp" : "2012-05-02T00:54:06.655Z",
"SignatureVersion" : "1",
"Signature" :
"EXAMPLEw6JRNwm1LFQL4ICB0bnXrdB8ClRMTQFGBqwLpGbM78tJ4etTwC5zU7O3tS6tGpey3ejedNdOJ
+1fkIp9F2/LmNVKb5aFlYq+9rk9ZiPph5YlLmWsDcyC5T+Sy9/
umic5S0UQc2PEtgdpVBahwNOdMW4JPwk0kAJJztnc=",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-
f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-
west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96"
}
The unsubscribe confirmation message is a POST message with a message body that contains a JSON
document with the following name/value pairs.
Message
A string that describes the message. For unsubscribe confirmation, this string looks like this:
MessageId
A Universally Unique Identifier, unique for each message published. For a message that Amazon SNS
resends during a retry, the message ID of the original message is used.
Signature
The URL to the certificate that was used to sign the message.
SubscribeURL
The URL that you must visit in order to re-confirm the subscription. Alternatively, you can instead
use the Token with the ConfirmSubscription action to re-confirm the subscription.
Timestamp
A value you can use with the ConfirmSubscription action to re-confirm the subscription.
Alternatively, you can simply visit the SubscribeURL.
TopicArn
The Amazon Resource Name (ARN) for the topic that this endpoint has been unsubscribed from.
Type
POST / HTTP/1.1
x-amz-sns-message-type: UnsubscribeConfirmation
x-amz-sns-message-id: 47138184-6831-46b8-8f7c-afc488602d7d
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-
beaa-fcfcc21c8f55
Content-Length: 1399
Content-Type: text/plain; charset=UTF-8
Host: myhost.example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "UnsubscribeConfirmation",
"MessageId" : "47138184-6831-46b8-8f7c-afc488602d7d",
"Token" :
"2336412f37fb687f5d51e6e241d09c805a5a57b30d712f7948a98bac386edfe3e10314e873973b3e0a3c09119b722dedf2b5e
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Message" : "You have chosen to deactivate subscription arn:aws:sns:us-
west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55.\nTo cancel this operation
and restore the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-
west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805a5a57b30d712f7948a98bac386edfe3e1031
"Timestamp" : "2012-04-26T20:06:41.581Z",
"SignatureVersion" : "1",
"Signature" : "EXAMPLEHXgJmXqnqsHTlqOCk7TIZsnk8zpJJoQbr8leD+8kAHcke3ClC4VPOvdpZo9s/
vR9GOznKab6sjGxE8uwqDI9HwpDm8lGxSlFGuwCruWeecnt7MdJCNh0XK4XQCbtGoXB762ePJfaSWi9tYwzW65zAFU04WkNBkNsIf60
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-
f3ecfb7224c7233fe7bb5f59f96de52f.pem"
}
http://sns.us-east-1.amazonaws.com/
?Action=SetSubscriptionAttributes
&SubscriptionArn=arn%3Aaws%3Asns%3Aus-east-1%3A123456789012%3AMy-Topic
%3A80289ba6-0fd4-4079-afb4-ce8c8260f0ca
&AttributeName=DeliveryPolicy
&AttributeValue={"healthyRetryPolicy":{"numRetries":5}}
...
Use the following JSON format for the value of the AttributeValue parameter.
{
"healthyRetryPolicy" : {
"minDelayTarget" : int,
"maxDelayTarget" : int,
"numRetries" : int,
"numMaxDelayRetries" : int,
"backoffFunction" : "linear|arithmetic|geometric|exponential"
},
"throttlePolicy" : {
"maxReceivesPerSecond" : int
}
}
http://sns.us-east-1.amazonaws.com/
?Action=SetTopicAttributes
&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A123456789012%3AMy-Topic
&AttributeName=DeliveryPolicy
&AttributeValue={"http":{"defaultHealthyRetryPolicy":{"numRetries":5}}}
...
Use the following JSON format for the value of the AttributeValue parameter.
{
"http" : {
"defaultHealthyRetryPolicy" : {
"minDelayTarget": int,
"maxDelayTarget": int,
"numRetries": int,
"numMaxDelayRetries": int,
"backoffFunction": "linear|arithmetic|geometric|exponential"
},
"disableSubscriptionOverrides" : Boolean,
"defaultThrottlePolicy" : {
"maxReceivesPerSecond" : int
}
}
}
For more information about the SetTopicAttribute action, go to SetTopicAttributes in the Amazon
Simple Notification Service API Reference.
In addition to sending large payloads, with Amazon SNS you can now enable raw message delivery for
messages delivered to either Amazon SQS endpoints or HTTP/S endpoints. This eliminates the need
for the endpoints to process JSON formatting, which is created for the Amazon SNS metadata when
raw message delivery is not selected. For example when enabling raw message delivery for an Amazon
SQS endpoint, the Amazon SNS metadata is not included and the published message is delivered to the
subscribed Amazon SQS endpoint as is. When enabling raw message delivery for HTTP/S endpoints, the
messages will contain an additional HTTP header x-amz-sns-rawdelivery with a value of true to
indicate that the message is being published raw instead of with JSON formatting. This enables those
endpoints to understand what is being delivered and enables easier transition for subscriptions from
JSON to raw delivery.
To enable raw message delivery using one of the AWS SDKs, you must use the
SetSubscriptionAttribute action and configure the RawMessageDelivery attribute with a value
of true. The default value is false.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. Select a topic that is subscribed to either an Amazon SQS endpoint or an HTTP/S endpoint and then
choose the topic ARN.
Topics
• Using Amazon SNS for System-to-System Messaging with a Lambda Function as a
Subscriber (p. 43)
• Using Amazon SNS for System-to-System Messaging with an Amazon SQS Queue as a
Subscriber (p. 44)
• Using Amazon SNS for System-to-System Messaging with an HTTP/S Endpoint as a
Subscriber (p. 57)
In addition, Amazon SNS also supports message delivery status attributes for message notifications sent
to Lambda endpoints. For more information, see Amazon SNS Topic Attributes for Message Delivery
Status (p. 14).
Prerequisites
To invoke Lambda functions using Amazon SNS notifications, you need the following:
• Lambda function
• Amazon SNS topic
For information on creating a Lambda function, see Getting Started with AWS Lambda. For information
on creating a Amazon SNS topic, see Create a Topic.
2. In the left Navigation pane, choose Topics, and then choose the topic to which you want to
subscribe a Lambda endpoint.
3. Choose Actions and then choose Subscribe to topic.
4. In the Protocol drop-down box, select AWS Lambda.
5. In the Endpoint drop-down box, select the ARN for the Lambda function.
6. In the Version or Alias drop-down box, select an available version or alias to use. If you don't want
to specify a version or alias, you can choose default (the latest version).
Note
Lambda doesn't allow event sources to be added for $LATEST. However, it allows event
sources on unqualified ARNs (effectively $LATEST).
For more information, see AWS Lambda Function Versioning and Aliases.
7. Choose Create subscription.
When a message is published to an SNS topic that has a Lambda function subscribed to it, the Lambda
function is invoked with the payload of the published message. For information on how to create
a sample message history store using SNS, Lambda, and Amazon DynamoDB, see the AWS Mobile
Development blog Invoking AWS Lambda functions via Amazon SNS.
When you subscribe an Amazon SQS queue to an Amazon SNS topic, you can publish a message to
the topic and Amazon SNS sends an Amazon SQS message to the subscribed queue. The Amazon SQS
message contains the subject and message that were published to the topic along with metadata about
the message in a JSON document. The Amazon SQS message will look similar to the following JSON
document.
{
"Type" : "Notification",
"MessageId" : "63a3f6b6-d533-4a47-aef9-fcf5cf758c76",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "Testing publish to subscribed queues",
"Message" : "Hello world!",
"Timestamp" : "2012-03-29T05:12:16.901Z",
"SignatureVersion" : "1",
"Signature" : "EXAMPLEnTrFPa37tnVO0FF9Iau3MGzjlJLRfySEoWz4uZHSj6ycK4ph71Zmdv0NtJ4dC/
El9FOGp3VuvchpaTraNHWhhq/
OsN1HVz20zxmF9b88R8GtqjfKB5woZZmz87HiM6CYDTo3l7LMwFT4VU7ELtyaBBafhPTg9O5CnKkg=",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-
f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c7fe3a54-
ab0e-4ec2-88e0-db410a0f2bee"
}
Important
Amazon SNS isn't currently compatible with Amazon SQS FIFO queues.
Instead of following the steps listed below, you can now subscribe an Amazon SQS queue to
an Amazon SNS topic using the Amazon SQS console, which simplifies the process. For more
information, see Subscribe Queue to Amazon SNS Topic
To enable an Amazon SNS topic to send messages to an Amazon SQS queue, follow these steps:
1. Get the Amazon Resource Name (ARN) of the queue you want to send messages to and the topic to
which you want to subscribe the queue. (p. 45)
2. Give sqs:SendMessage permission to the Amazon SNS topic so that it can send messages to the
queue. (p. 46)
3. Subscribe the queue to the Amazon SNS topic. (p. 46)
4. Give IAM users or AWS accounts the appropriate permissions to publish to the Amazon SNS topic and
read messages from the Amazon SQS queue. (p. 47)
5. Test it out by publishing a message to the topic and reading the message from the queue. (p. 49)
To learn about how to set up a topic to send messages to a queue that is in a different AWS account, see
Sending Amazon SNS Messages to an Amazon SQS Queue in a Different Aaccount (p. 50).
To see an AWS CloudFormation template that creates a topic that sends messages to two queues,
see Using an AWS CloudFormation Template to Create a Topic that Sends Messages to Amazon SQS
Queues (p. 53).
To get the queue ARN, you can use the Amazon SQS console or the GetQueueAttributes API action.
1. Sign in to the AWS Management Console and open the Amazon SQS console at https://
console.aws.amazon.com/sqs/.
2. Select the box for the queue whose ARN you want to get.
3. From the Details tab, copy the ARN value so that you can use it to subscribe to the Amazon SNS
topic.
To get the topic ARN, you can use the Amazon SNS console, the sns-get-topic-attributes command, or
the GetQueueAttributes API action.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, select the topic whose ARN you want to get.
3. From the Topic Details pane, copy the Topic ARN value so that you can use it to give permission for
the Amazon SNS topic to send messages to the queue.
Before you subscribe a queue to a topic, you need a topic and a queue. If you haven't already created a
topic or queue, create them now. For more information, see Creating a Topic, and see Creating a Queue
in the Amazon Simple Queue Service Developer Guide.
To set a policy on a queue, you can use the Amazon SQS console or the SetQueueAttributes API action.
Before you start, make sure you have the ARN for the topic that you want to allow to send messages to
the queue.
1. Sign in to the AWS Management Console and open the Amazon SQS console at https://
console.aws.amazon.com/sqs/.
2. Select the box for the queue whose policy you want to set, choose the Permissions tab, and then
choose Add a Permission.
3. In the Add a Permission dialog box, select Allow for Effect, select Everybody (*) for Principal, and
then select SendMessage from the Actions drop-down.
4. Add a condition that allows the action for the topic. Choose Add Conditions (optional), select
ArnEquals for Condition, select aws:SourceArn for Key, and paste in the topic ARN for Value.
Choose Add Condition. The new condition should appear at the bottom of the box (you may have to
scroll down to see this).
5. Choose Add Permission.
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",
"Id": "MyQueuePolicy",
"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"
}
}
}]
}
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, select the topic.
3. Choose Create Subscription, select Amazon SQS for Protocol, paste in the ARN for the queue that
you want the topic to send messages to for Endpoint, and choose Subscribe.
4. For the Subscription request received! message, choose Close.
When the subscription is confirmed, your new subscription's Subscription ID displays its subscription
ID. If the owner of the queue creates the subscription, the subscription is automatically confirmed
and the subscription should be active almost immediately.
Usually, you'll be subscribing your own queue to your own topic in your own account. However,
you can also subscribe a queue from a different account to your topic. If the user who creates the
subscription is not the owner of the queue (for example, if a user from account A subscribes a queue
from account B to a topic in account A), the subscription must be confirmed. For more information
about subscribing a queue from a different account and confirming the subscription, see Sending
Amazon SNS Messages to an Amazon SQS Queue in a Different Aaccount (p. 50).
• Add a policy to an IAM user or group (p. 47). The simplest way to give users permissions to topics
or queues is to create a group and add the appropriate policy to the group and then add users to that
group. It's much easier to add and remove users from a group than to keep track of which policies you
set on individual users.
• Add a policy to topic or queue (p. 48). If you want to give permissions to a topic or queue to another
AWS account, the only way you can do that is by adding a policy that has as its principal the AWS
account you want to give permissions to.
You should use the first method for most cases (apply policies to groups and manage permissions for
users by adding or removing the appropriate users to the groups). If you need to give permissions to a
user in another account, you should use the second method.
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowPublishToMyTopic",
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "arn:aws:sns:us-east-1:123456789012:MyTopic"
}]
}
If you added the following policy to an IAM user or group, you would give that user or members of that
group permission to perform the sqs:ReceiveMessage and sqs:DeleteMessage actions on the
queues MyQueue1 and MyQueue2.
{
"Version":"2012-10-17",
"Statement":[{
"Sid":"AllowReadDeleteMessageOnMyQueue",
"Effect":"Allow",
"Action":[
"sqs:ReceiveMessage",
"sqs:DeleteMessage"
],
"Resource":[
"arn:aws:sns:us-east-1:123456789012:MyQueue1",
"arn:aws:sns:us-east-1:123456789012:MyQueue2"
]
}]
}
If you added the following policy to a topic MyTopic in account 123456789012, you would give account
111122223333 permission to perform the sns:Publish action on that topic.
{
"Version":"2012-10-17",
"Id":"MyTopicPolicy",
"Statement":[{
"Sid":"Allow-publish-to-topic",
"Effect":"Allow",
"Principal":{
"AWS":"111122223333"
},
"Action":"sns:Publish",
"Resource":"arn:aws:sns:us-east-1:123456789012:MyTopic"
}]
}
If you added the following policy to a queue MyQueue in account 123456789012, you would give
account 111122223333 permission to perform the sqs:ReceiveMessage and sqs:DeleteMessage
actions on that queue.
"Version":"2012-10-17",
"Id":"MyQueuePolicy",
"Statement":[{
"Sid":"Allow-Processing-Of-Messages-for-Queue",
"Effect":"Allow",
"Principal":{
"AWS":"111122223333"
},
"Action":[
"sqs:DeleteMessage",
"sqs:ReceiveMessage"
],
"Resource":[
"arn:aws:sns:us-east-1:123456789012:MyQueue"
]
}]
}
1. Using the credentials of the AWS account or IAM user with permission to publish to the topic,
sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/.
2. In the navigation pane, select the topic and choose Publish to Topic.
3. In the Subject box, enter a subject (for example, Testing publish to queue) in the Message
box, enter some text (for example, Hello world!), and choose Publish Message. The following
message appears: Your message has been successfully published.
To view the message from the topic using the Amazon SQS console
1. Using the credentials of the AWS account or IAM user with permission to view messages in the
queue, sign in to the AWS Management Console and open the Amazon SQS console at https://
console.aws.amazon.com/sqs/.
2. Check the box for the queue that is subscribed to the topic.
3. From the Queue Action drop-down, select View/Delete Messages and choose Start Polling for
Messages. A message with a type of Notification appears.
4. In the Body column, choose More Details. The Message Details box contains a JSON document that
contains the subject and message that you published to the topic. The message looks similar to the
following JSON document.
{
"Type" : "Notification",
"MessageId" : "63a3f6b6-d533-4a47-aef9-fcf5cf758c76",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "Testing publish to subscribed queues",
"Message" : "Hello world!",
"Timestamp" : "2012-03-29T05:12:16.901Z",
"SignatureVersion" : "1",
"Signature" :
"EXAMPLEnTrFPa37tnVO0FF9Iau3MGzjlJLRfySEoWz4uZHSj6ycK4ph71Zmdv0NtJ4dC/
El9FOGp3VuvchpaTraNHWhhq/
OsN1HVz20zxmF9b88R8GtqjfKB5woZZmz87HiM6CYDTo3l7LMwFT4VU7ELtyaBBafhPTg9O5CnKkg=",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/
SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c7fe3a54-
ab0e-4ec2-88e0-db410a0f2bee"
}
5. Choose Close. You have successfully published to a topic that sends notification messages to a
queue.
Topics
• Queue Owner Creates Subscription (p. 50)
• User Who Does Not Own the Queue Creates Subscription (p. 51)
{
"Version":"2012-10-17",
"Id":"MyTopicSubscribePolicy",
"Statement":[{
"Sid":"Allow-other-account-to-subscribe-to-topic",
"Effect":"Allow",
"Principal":{
"AWS":"111122223333"
},
"Action":"sns:Subscribe",
"Resource":"arn:aws:sns:us-east-1:123456789012:MyTopic"
}
]
}
After this policy has been set on MyTopic, a user can log in to the Amazon SNS console with credentials
for account 111122223333 to subscribe to the topic.
To add an Amazon SQS queue subscription to a topic in another account using the Amazon
SQS console
1. Using the credentials of the AWS account containing the queue or an IAM user in that account,
sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/.
2. Make sure you have the ARNs for both the topic and the queue. You will need them when you create
the subscription.
3. Make sure you have set sqs:SendMessage permission on the queue so that it can receive messages
from the topic. For more information, see Give Permission to the Topic to Send Messages to the
Queue (p. 46).
4. In the navigation pane, select the SNS Dashboard.
5. In the Dashboard, in the Additional Actions section, choose Create New Subscription.
6. In the Topic ARN box, enter the ARN for the topic.
7. For Protocol, select Amazon SQS.
8. In the Endpoint box, enter the ARN for the queue.
9. Choose Subscribe.
10. For the Subscription request received! message, you'll notice text that says you must confirm the
subscription. Because you are the queue owner, the subscription does not need to be confirmed.
Choose Close. You've completed the subscription process and notification messages published to the
topic can now be sent to the queue.
The user can also use the access key and secret key for the AWS account 111122223333 to issue the
sns-subscribe command or call the Subscribe API action to subscribe an Amazon SQS queue to
MyTopic in the account 123456789012. The following sns-subscribe command subscribes the queue
MyQ from account 111122223333 to the topic MyTopic in account 123456789012.
Note
To be able to send, the queue must have permissions for Amazon SNS.
When the user calls the Subscribe action, a message of type SubscriptionConfirmation is sent
to the queue and the subscription is displayed in the Amazon SNS console with its Subscription ID set to
Pending Confirmation. To confirm the subscription, a user who can read messages from the queue must
visit the URL specified in the SubscribeURL value in the message. Until the subscription is confirmed,
no notifications published to the topic are sent to the queue. To confirm a subscription, you can use the
Amazon SQS console or the ReceiveMessage API action.
1. Sign in to the AWS Management Console and open the Amazon SQS console at https://
console.aws.amazon.com/sqs/.
5. In the text box, find the SubscribeURL value and copy the URL. It will look similar to the following
URL.
https://sns.us-west-2.amazonaws.com/?
Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-
west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805d352fe148e56f8cff30f023ff35db8bc
6. In a web browser, paste the URL into the address bar to visit the URL. You will see a response similar
to the following XML document.
<ConfirmSubscriptionResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
<ConfirmSubscriptionResult>
<SubscriptionArn>arn:aws:sns:us-west-2:123456789012:MyTopic:c7fe3a54-
ab0e-4ec2-88e0-db410a0f2bee</SubscriptionArn>
</ConfirmSubscriptionResult>
<ResponseMetadata>
<RequestId>dd266ecc-7955-11e1-b925-5140d02da9af</RequestId>
</ResponseMetadata>
</ConfirmSubscriptionResponse>
If you view the topic subscription in the Amazon SNS console, you will now see that subscription
ARN replaces the Pending Confirmation message in the Subscription ID column. The subscribed
queue is ready to receive messages from the topic.
For more information about deploying AWS resources using an AWS CloudFormation template, see Get
Started in the AWS CloudFormation User Guide.
MySNSTopic is set up to publish to two subscribed endpoints, which are two Amazon SQS queues
(MyQueue1 and MyQueue2). MyPublishTopicGroup is an IAM group whose members have permission
to publish to MySNSTopic using the Publish API action or sns-publish command. The template creates
the IAM users MyPublishUser and MyQueueUser and gives them login profiles and access keys. The user
who creates a stack with this template specifies the passwords for the login profiles as input parameters.
The template creates access keys for the two IAM users with MyPublishUserKey and MyQueueUserKey.
AddUserToMyPublishTopicGroup adds MyPublishUser to the MyPublishTopicGroup so that the user will
have the permissions assigned to the group.
MyRDMessageQueueGroup is an IAM group whose members have permission to read and delete
messages from the two Amazon SQS queues using the ReceiveMessage and DeleteMessage API actions.
AddUserToMyQueueGroup adds MyQueueUser to the MyRDMessageQueueGroup so that the user will
have the permissions assigned to the group. MyQueuePolicy assigns permission for MySNSTopic to
publish its notifications to the two queues.
{
"AWSTemplateFormatVersion":"2010-09-09",
"Description":"This Template creates an Amazon SNS topic that can send messages
to two Amazon SQS queues with appropriate permissions for one IAM user to publish to
the topic and another to read messages from the queues. MySNSTopic is set up to publish
to two subscribed endpoints, which are two Amazon SQS queues (MyQueue1 and MyQueue2).
MyPublishUser is an IAM user that can publish to MySNSTopic using the Publish API.
MyTopicPolicy assigns that permission to MyPublishUser. MyQueueUser is an IAM user
that can read messages from the two Amazon SQS queues. MyQueuePolicy assigns those
permissions to MyQueueUser. It also assigns permission for MySNSTopic to publish its
notifications to the two queues. The template creates access keys for the two IAM users
with MyPublishUserKey and MyQueueUserKey. Note that you will be billed for the AWS
resources used if you create a stack from this template.",
"Parameters":{
"MyPublishUserPassword":{
"NoEcho":"true",
"Type":"String",
"Description":"Password for the IAM user MyPublishUser",
"MinLength":"1",
"MaxLength":"41",
"AllowedPattern":"[a-zA-Z0-9]*",
"ConstraintDescription":"must contain only alphanumeric characters."
},
"MyQueueUserPassword":{
"NoEcho":"true",
"Type":"String",
"Description":"Password for the IAM user MyQueueUser",
"MinLength":"1",
"MaxLength":"41",
"AllowedPattern":"[a-zA-Z0-9]*",
"ConstraintDescription":"must contain only alphanumeric characters."
}
},
"Resources":{
"MySNSTopic":{
"Type":"AWS::SNS::Topic",
"Properties":{
"Subscription":[
{
"Endpoint":{"Fn::GetAtt":["MyQueue1","Arn"]},
"Protocol":"sqs"
},
{
"Endpoint":{"Fn::GetAtt":["MyQueue2","Arn"]},
"Protocol":"sqs"
}
]
}
},
"MyQueue1":{
"Type":"AWS::SQS::Queue"
},
"MyQueue2":{
"Type":"AWS::SQS::Queue"
},
"MyPublishUser":{
"Type":"AWS::IAM::User",
"Properties":{
"LoginProfile":{
"Password":{"Ref":"MyPublishUserPassword"}
}
}
},
"MyPublishUserKey":{
"Type":"AWS::IAM::AccessKey",
"Properties":{
"UserName":{"Ref":"MyPublishUser"}
}
},
"MyPublishTopicGroup":{
"Type":"AWS::IAM::Group",
"Properties":{
"Policies":[
{
"PolicyName":"MyTopicGroupPolicy",
"PolicyDocument":{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"sns:Publish"
],
"Resource":{"Ref":"MySNSTopic"}
}
]}
}
]
}
},
"AddUserToMyPublishTopicGroup":{
"Type":"AWS::IAM::UserToGroupAddition",
"Properties":{
"GroupName":{"Ref":"MyPublishTopicGroup"},
"Users":[{"Ref":"MyPublishUser"}]
}
},
"MyQueueUser":{
"Type":"AWS::IAM::User",
"Properties":{
"LoginProfile":{
"Password":{"Ref":"MyQueueUserPassword"}
}
}
},
"MyQueueUserKey":{
"Type":"AWS::IAM::AccessKey",
"Properties":{
"UserName":{"Ref":"MyQueueUser"}
}
},
"MyRDMessageQueueGroup":{
"Type":"AWS::IAM::Group",
"Properties":{
"Policies":[
{
"PolicyName":"MyQueueGroupPolicy",
"PolicyDocument":{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"sqs:DeleteMessage",
"sqs:ReceiveMessage"
],
"Resource":[
{"Fn::GetAtt":["MyQueue1","Arn"]},
{"Fn::GetAtt":["MyQueue2","Arn"]}
]
}
]}
}
]
}
},
"AddUserToMyQueueGroup":{
"Type":"AWS::IAM::UserToGroupAddition",
"Properties":{
"GroupName":{"Ref":"MyRDMessageQueueGroup"},
"Users":[{"Ref":"MyQueueUser"}]
}
},
"MyQueuePolicy":{
"Type":"AWS::SQS::QueuePolicy",
"Properties":{
"PolicyDocument":{
"Version":"2012-10-17",
"Id":"MyQueuePolicy",
"Statement":[
{
"Sid":"Allow-SendMessage-To-Both-Queues-From-SNS-Topic",
"Effect":"Allow",
"Principal":"*",
"Action":["sqs:SendMessage"],
"Resource":"*",
"Condition":{
"ArnEquals":{
"aws:SourceArn":{"Ref":"MySNSTopic"}
}
}
}
]
},
"Queues":[{"Ref":"MyQueue1"},{"Ref":"MyQueue2"}]
}
}
},
"Outputs":{
"MySNSTopicTopicARN":{
"Value":{"Ref":"MySNSTopic"}
},
"MyQueue1Info":{
"Value":{"Fn::Join":[
" ",
[
"ARN:",
{"Fn::GetAtt":["MyQueue1","Arn"]},
"URL:",
{"Ref":"MyQueue1"}
]
]}
},
"MyQueue2Info":{
"Value":{"Fn::Join":[
" ",
[
"ARN:",
{"Fn::GetAtt":["MyQueue2","Arn"]},
"URL:",
{"Ref":"MyQueue2"}
]
]}
},
"MyPublishUserInfo":{
"Value":{"Fn::Join":[
" ",
[
"ARN:",
{"Fn::GetAtt":["MyPublishUser","Arn"]},
"Access Key:",
{"Ref":"MyPublishUserKey"},
"Secret Key:",
{"Fn::GetAtt":["MyPublishUserKey","SecretAccessKey"]}
]
]}
},
"MyQueueUserInfo":{
"Value":{"Fn::Join":[
" ",
[
"ARN:",
{"Fn::GetAtt":["MyQueueUser","Arn"]},
"Access Key:",
{"Ref":"MyQueueUserKey"},
"Secret Key:",
{"Fn::GetAtt":["MyQueueUserKey","SecretAccessKey"]}
]
]}
}
}
}
• Server Name Indication (SNI)—This allows Amazon SNS to support HTTPS endpoints that require
SNI, such as a server requiring multiple certificates for hosting multiple domains. For more information
about SNI, see Server Name Indication.
• Basic and Digest Access Authentication—This allows you to specify a username and password in
the HTTPS URL for the HTTP POST request, such as https://user:[email protected] or
https://[email protected] The username and password are encrypted over the SSL connection
established when using HTTPS. Only the domain name is sent in plaintext. For more information about
Basic and Digest Access Authentication, see RFC-2617.
Note
The client service must be able to support the HTTP/1.1 401 Unauthorized header
response
The request contains the subject and message that were published to the topic along with metadata
about the notification in a JSON document. The request will look similar to the following HTTP POST
request. For details about the HTTP header and the JSON format of the request body, see HTTP/HTTPS
Headers (p. 36) and HTTP/HTTPS Notification JSON Format (p. 38).
POST / HTTP/1.1
x-amz-sns-message-type: Notification
x-amz-sns-message-id: da41e39f-ea4d-435a-b922-c6aae3915ebe
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-
west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55
Content-Length: 761
Content-Type: application/json; charset=UTF-8
Host: ec2-50-17-44-49.compute-1.amazonaws.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "Notification",
"MessageId" : "da41e39f-ea4d-435a-b922-c6aae3915ebe",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "test",
"Message" : "test message",
"Timestamp" : "2012-04-25T21:49:25.719Z",
"SignatureVersion" : "1",
"Signature" :
"EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUD
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-
f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-
west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55"
}
To enable an Amazon SNS topic to send messages to an HTTP or HTTPS endpoint, follow these steps:
Make Sure Your Endpoint is Ready to Process Amazon SNS Messages (p. 58)
Step 2: Subscribe the HTTP/HTTPS endpoint to the Amazon SNS topic (p. 61)
Step 4: Set the delivery retry policy for the subscription (optional) (p. 62)
Step 5: Give users permissions to publish to the topic (optional) (p. 62)
1. Your code should read the HTTP headers of the HTTP POST requests that Amazon SNS sends to
your endpoint. Your code should look for the header field x-amz-sns-message-type, which
tells you the type of message that Amazon SNS has sent to you. By looking at the header, you
can determine the message type without having to parse the body of the HTTP request. There
are two types that you need to handle: SubscriptionConfirmation and Notification. The
UnsubscribeConfirmation message is used only when the subscription is deleted from the topic.
For details about the HTTP header, see HTTP/HTTPS Headers (p. 36). The following HTTP POST
request is an example of a subscription confirmation message.
POST / HTTP/1.1
x-amz-sns-message-type: SubscriptionConfirmation
x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
Content-Length: 1336
Content-Type: application/json; charset=UTF-8
Host: example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "SubscriptionConfirmation",
"MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b",
"Token" :
"2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad0
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-
west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL
included in this message.",
"SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-
west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d927
"Timestamp" : "2012-04-26T20:45:04.751Z",
"SignatureVersion" : "1",
"Signature" : "EXAMPLEpH
+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/
SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem"
}
2. Your code should parse the JSON document in the body of the HTTP POST request to read
the name/value pairs that make up the Amazon SNS message. Use a JSON parser that handles
converting the escaped representation of control characters back to their ASCII character values
(for example, converting \n to a newline character). You can use an existing JSON parser such as
the Jackson JSON Processor or write your own. In order to send the text in the subject and message
fields as valid JSON, Amazon SNS must convert some control characters to escaped representations
that can be included in the JSON document. When you receive the JSON document in the body of
the POST request sent to your endpoint, you must convert the escaped characters back to their
original character values if you want an exact representation of the original subject and messages
published to the topic. This is critical if you want to verify the signature of a notification because the
signature uses the message and subject in their original forms as part of the string to sign.
3. Your code should verify the authenticity of a notification, subscription confirmation, or unsubscribe
confirmation message sent by Amazon SNS. Using information contained in the Amazon SNS
message, your endpoint can recreate the signature so that you can verify the contents of the
message by matching your signature with the signature that Amazon SNS sent with the message.
For more information about verifying the signature of a message, see Verifying the Signatures of
Amazon SNS Messages (p. 81).
4. Based on the type specified by the header field x-amz-sns-message-type, your code should read
the JSON document contained in the body of the HTTP request and process the message. Here are
the guidelines for handling the two primary types of messages:
SubscriptionConfirmation
Read the value for SubscribeURL and visit that URL. To confirm the subscription and start
receiving notifications at the endpoint, you must visit the SubscribeURLURL (for example,
by sending an HTTP GET request to the URL). See the example HTTP request in the previous
step to see what the SubscribeURL looks like. For more information about the format of
the SubscriptionConfirmation message, see HTTP/HTTPS Subscription Confirmation
JSON Format (p. 36). When you visit the URL, you will get back a response that looks like the
following XML document. The document returns the subscription ARN for the endpoint within
the ConfirmSubscriptionResult element.
<ConfirmSubscriptionResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
<ConfirmSubscriptionResult>
<SubscriptionArn>arn:aws:sns:us-
west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55</SubscriptionArn>
</ConfirmSubscriptionResult>
<ResponseMetadata>
<RequestId>075ecce8-8dac-11e1-bf80-f781d96e9307</RequestId>
</ResponseMetadata>
</ConfirmSubscriptionResponse>
Read the values for Subject and Message to get the notification information that was
published to the topic.
For details about the format of the Notification message, see HTTP/HTTPS Headers (p. 36).
The following HTTP POST request is an example of a notification message sent to the endpoint
example.com.
POST / HTTP/1.1
x-amz-sns-message-type: Notification
x-amz-sns-message-id: 22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
x-amz-sns-subscription-arn: arn:aws:sns:us-
west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96
Content-Length: 773
Content-Type: application/json; charset=UTF-8
Host: example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent
{
"Type" : "Notification",
"MessageId" : "22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324",
"TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Subject" : "My First Message",
"Message" : "Hello world!",
"Timestamp" : "2012-05-02T00:54:06.655Z",
"SignatureVersion" : "1",
"Signature" :
"EXAMPLEw6JRNwm1LFQL4ICB0bnXrdB8ClRMTQFGBqwLpGbM78tJ4etTwC5zU7O3tS6tGpey3ejedNdOJ
+1fkIp9F2/LmNVKb5aFlYq+9rk9ZiPph5YlLmWsDcyC5T+Sy9/
umic5S0UQc2PEtgdpVBahwNOdMW4JPwk0kAJJztnc=",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/
SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",
"UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?
Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-
west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96"
}
5. Make sure that your endpoint responds to the HTTP POST message from Amazon SNS with the
appropriate status code. The connection will time out in 15 seconds. If your endpoint does not
respond before the connection times out or if your endpoint returns a status code outside the range
of 200–4xx, Amazon SNS will consider the delivery of the message as a failed attempt.
6. Make sure that your code can handle message delivery retries from Amazon SNS. If Amazon SNS
doesn't receive a successful response from your endpoint, it attempts to deliver the message
again. This applies to all messages, including the subscription confirmation message. By default,
if the initial delivery of the message fails, Amazon SNS attempts up to three retries with a delay
between failed attempts set at 20 seconds. Note that the message request times out at 15 seconds.
This means that if the message delivery failure was caused by a timeout, Amazon SNS will retry
approximately 35 seconds after the previous delivery attempt. If you don't like the default delivery
policy, you can set a different delivery policy on the endpoint.
To be clear, Amazon SNS attempts to retry only after a delivery x-amz-sns-message-id header
field. By comparing the IDs of the messages you have processed with incoming messages, you can
determine whether the message is a retry attempt.
7. If you are subscribing an HTTPS endpoint, make sure that your endpoint has a server certificate
from a trusted Certificate Authority (CA). Amazon SNS will only send messages to HTTPS endpoints
that have a server certificate signed by a CA trusted by Amazon SNS. For a list of trusted CAs, see
Certificate Authorities (CA) Recognized by Amazon SNS for HTTPS Endpoints (p. 69).
8. Deploy the code that you have created to receive Amazon SNS messages. When you subscribe the
endpoint, the endpoint must be ready to receive at least the subscription confirmation message.
To subscribe an HTTP or HTTPS endpoint to a topic using the Amazon SNS console
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select the topic.
3. Choose the Other actions drop-down list and select Subscribe to topic.
4. In the Protocol drop-down list, select HTTP or HTTPS.
5. In the Endpoint box, paste in the URL for the endpoint that you want the topic to send messages to
and then choose Create subscription.
6. For the Subscription request received! message, choose Close.
Your new subscription's Subscription ID displays PendingConfirmation. When you confirm the
subscription, Subscription ID will display the subscription ID.
confirmed. When you visit the SubscribeURL, the response will contain an XML document containing
an element SubscriptionArn that specifies the ARN for the subscription. You can also use the Amazon
SNS console to verify that the subscription is confirmed: The Subscription ID will display the ARN for
the subscription instead of the PendingConfirmation value that you saw when you first added the
subscription.
• Add a policy to an IAM user or group. The simplest way to give users permissions to topics is to create
a group and add the appropriate policy to the group and then add users to that group. It's much easier
to add and remove users from a group than to keep track of which policies you set on individual users.
• Add a policy to the topic. If you want to give permissions to a topic to another AWS account, the only
way you can do that is by adding a policy that has as its principal the AWS account you want to give
permissions to.
You should use the first method for most cases (apply policies to groups and manage permissions for
users by adding or removing the appropriate users to the groups). If you need to give permissions to a
user in another account, use the second method.
If you added the following policy to an IAM user or group, you would give that user or members of that
group permission to perform the sns:Publish action on the topic MyTopic.
{
"Version":"2012-10-17",
"Statement":[{
"Sid":"AllowPublishToMyTopic",
"Effect":"Allow",
"Action":"sns:Publish",
"Resource":"arn:aws:sns:us-east-1:123456789012:MyTopic"
}
]
}
The following example policy shows how to give another account permissions to a topic.
Note
When you give another AWS account access to a resource in your account, you are also giving
IAM users who have admin-level access (wildcard access) permissions to that resource. All other
IAM users in the other account are automatically denied access to your resource. If you want
to give specific IAM users in that AWS account access to your resource, the account or an IAM
user with admin-level access must delegate permissions for the resource to those IAM users.
For more information about cross-account delegation, see Enabling Cross-Account Access in the
Using IAM Guide.
If you added the following policy to a topic MyTopic in account 123456789012, you would give account
111122223333 permission to perform the sns:Publish action on that topic.
{
"Version":"2012-10-17",
"Id":"MyTopicPolicy",
"Statement":[{
"Sid":"Allow-publish-to-topic",
"Effect":"Allow",
"Principal":{
"AWS":"111122223333"
},
"Action":"sns:Publish",
"Resource":"arn:aws:sns:us-east-1:123456789012:MyTopic"
}
]
}
If you followed Step 1 (p. 58), the code that you deployed at your endpoint should process the
notification.
1. Using the credentials of the AWS account or IAM user with permission to publish to the topic,
sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/.
2. In the left navigation pane, choose Topics and then select a topic.
3. Choose the Publish to topic button.
4. In the Subject box, enter a subject (for example, Testing publish to my endpoint).
5. In the Message box, enter some text (for example, Hello world!), and choose Publish message.
The following message appears: Your message has been successfully published.
A successful Amazon SNS delivery to an HTTP/HTTPS endpoint sometimes requires more than one
attempt. This can be the case, for example, if the web server that hosts the subscribed endpoint is
down for maintenance or is experiencing heavy traffic. If an initial delivery attempt doesn't result in a
successful response from the subscriber, Amazon SNS attempts to deliver the message again. We call
such an attempt a retry. In other words, a retry is an attempted delivery that occurs after the initial
delivery attempt.
Amazon SNS attempts a retry only after a failed delivery attempt. Amazon SNS considers the following
situations to indicate failed delivery attempts:
You can use delivery policies to control not only the total number of retries, but also the time delay
between each retry. You can specify up to 100 total retries distributed among four discrete phases. The
maximum lifetime of a message in the system is one hour. This one hour limit cannot be extended by a
delivery policy.
1. Immediate Retry Phase (p. 67)—Also called the no delay phase, this phase occurs immediately
after the initial delivery attempt. The value you set for Retries with no delay determines the number
of retries immediately after the initial delivery attempt. There is no delay between retries in this
phase.
2. Pre-Backoff Phase (p. 67)—The pre-backoff phase follows the immediate retry phase. Use this
phase to create a set of retries that occur before a backoff function applies to the retries. Use the
Minimum delay retries setting to specify the number of retries in the Pre-Backoff Phase. You can
control the time delay between retries in this phase by using the Minimum delay setting.
3. Backoff Phase (p. 68)—This phase is called the backoff phase because you can control the delay
between retries in this phase using the retry backoff function. Set the Minimum delay and the
Maximum delay, and then select a Retry backoff function to define how quickly the delay increases
from the minimum delay to the maximum delay.
4. Post-Backoff Phase (p. 69)—The post-backoff phase follows the backoff phase. Use the Maximum
delay retries setting to specify the number of retries in the post-backoff phase. You can control the
time delay between retries in this phase by using the Maximum delay setting.
The backoff phase is the most commonly used phase. If no delivery policies are set, the default is to retry
three times in the backoff phase, with a time delay of 20 seconds between each retry. The default value
for both the Minimum delay and the Maximum delay is 20. The default number of retries is 3, so the
default retry policy calls for a total of 3 retries with a 20 second delay between each retry. The following
diagram shows the delay associated with each retry.
To see how the retry backoff function affects the time delay between retries, you can set the maximum
delay to 40 seconds and leave the remaining settings at their default values. With this change, your
delivery policy now specifies 3 retries during the backoff phase, a minimum delay of 20 seconds, and
a maximum delay of 40 seconds. Because the default backoff function is linear, the delay between
messages increases at a constant rate over the course of the backoff phase. Amazon SNS attempts the
first retry after 20 seconds, the second retry after 30 seconds, and the final retry after 40 seconds. The
following diagram shows the delay associated with each retry.
The maximum lifetime of a message in the system is one hour. This one hour limit cannot be extended by
a delivery policy.
Note
Only HTTP and HTTPS subscription types are supported by delivery policies. Support for other
Amazon SNS subscription types (e.g., email, Amazon SQS, and SMS) is not currently available.
You can also apply delivery policies to individual subscriptions. If you assign a delivery policy to a
subscription, the subscription-level policy takes precedence over the topic-level delivery policy. In the
following diagram, one subscription has a subscription-level delivery policy whereas the two other
subscriptions do not.
In some cases, you might want to ignore all subscription delivery policies so that your topic's delivery
policy applies to all subscriptions even if a subscription has set its own delivery policy. To configure
Amazon SNS to apply your topic delivery policy to all subscriptions, choose Ignore subscription override
in the View/Edit Topic Delivery Policies dialog box. The following diagram shows a topic-level delivery
policy that applies to all subscriptions, even the subscription that has its own subscription delivery policy
because subscription-level policies have been specifically ignored.
• To set a maximum receive rate that applies to all of a topic's subscriptions, apply the setting at the
topic level using the Edit Topic Delivery Policy dialog box. For more information, see To set the
maximum receive rate for a topic (p. 67).
• To set a maximum receive rate that applies to a specific subscription, apply the setting at the
subscription level using the Edit Subscription Delivery Policy dialog box. For more information, see To
set the maximum receive rate for a subscription (p. 67).
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select the topic.
3. Choose the Other actions drop-down list and select Edit topic delivery policy.
4. In the Maximum receive rate box, type an integer value (e.g., 2).
5. Choose Update policy to save your changes.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select a topic ARN.
3. In the Topic Details pane, select a subscription and choose Edit topic delivery policy.
4. In the Maximum receive rate box, type an integer value (e.g., 2).
5. Choose Update policy to save your changes.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select a topic ARN.
3. In the Topic Details pane, select Edit topic delivery policy from the Other topic actions drop-down
list.
4. In the Retries with no delay box, type an integer value.
5. Choose Update policy to save your changes.
Pre-Backoff Phase
The pre-backoff phase follows the immediate retry phase. Use this phase if you want to create a set of
one or more retries that happen before the backoff function affects the delay between retries. In this
phase, the time between retries is constant and is equal to the setting that you choose for the Minimum
delay. The Minumum delay setting affects retries in two phases—it applies to all retries in the pre-
backoff phase and serves as the initial time delay for retries in the backoff phase. The default number of
retries for this phase is 0.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select a topic ARN.
3. In the Topic Details pane, select Edit topic delivery policy from the Other topic actions drop-down
list.
4. In the Minimum delay retries box, type an integer value.
5. In the Minimum delay box, type an integer value to set the delay between messages in this phase.
The value you set must be less than or equal to the value you set for Maximum delay.
6. Choose Update policy to save your changes.
Backoff Phase
The backoff phase is the only phase that applies by default. You can control the number of retries in the
backoff phase using Number of retries.
Important
The value you choose for Number of retries represents the total number of retries, including
the retries you set for Retries with no delay, Minimum delay retries, and Maximum delay
retries.
You can control the frequency of the retries in the backoff phase with three parameters.
• Minimum delay—The minimum delay defines the delay associated with the first retry attempt in the
backoff phase.
• Maximum delay—The maximum delay defines the delay associated with the final retry attempt in the
backoff phase.
• Retry backoff function—The retry backoff function defines the algorithm that Amazon SNS uses to
calculate the delays associated with all of the retry attempts between the first and last retries in the
backoff phase.
• Linear
• Arithmetic
• Geometric
• Exponential
The following screen shot shows how each retry backoff function affects the delay associated with
messages during the backoff period. The vertical axis represents the delay in seconds associated with
each of the 10 retries. The horizontal axis represents the retry number. The minimum delay is 5 seconds,
and the maximum delay is 260 seconds.
Post-Backoff Phase
The post-backoff phase is the final phase. Use this phase if you want to create a set of one or more
retries that happen after the backoff function affects the delay between retries. In this phase, the time
between retries is constant and is equal to the setting that you choose for the Maximum delay. The
Maximum delay setting affects retries in two phases—it applies to all retries in the post-backoff phase
and serves as the final time delay for retries in the backoff phase. The default number of retries for this
phase is 0.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left navigation pane, choose Topics and then select a topic ARN.
3. In the Topic Details pane, select Edit topic delivery policy from the Other topic actions drop-down
list.
4. In the Maximum delay retries box, type an integer value.
5. In the Maximum delay box, type an integer value to set the delay between messages in this phase.
The value you set must be greater than or equal to the value you set for Minimum delay.
6. Choose Update policy to save your changes.
To help prevent spoofing attacks, you should do the following when verifying messages sent by Amazon
SNS:
• Always use HTTPS when getting the certificate from Amazon SNS.
• Validate the authenticity of the certificate.
• Verify the certificate was received from Amazon SNS.
• When possible, use one of the supported AWS SDKs for Amazon SNS to validate and verify
messages. For example, with the AWS SDK for PHP you would use the isValid method from the
MessageValidator class.
For example code for a Java servlet that handles Amazon SNS messages see Example Code for an
Amazon SNS Endpoint Java Servlet (p. 83).
To verify the signature of an Amazon SNS message when using HTTP query-based requests
1. Extract the name/value pairs from the JSON document in the body of the HTTP POST request that
Amazon SNS sent to your endpoint. You'll be using the values of some of the name/value pairs to
create the string to sign. When you are verifying the signature of an Amazon SNS message, it is
critical that you convert the escaped control characters to their original character representations in
the Message and Subject values. These values must be in their original forms when you use them
as part of the string to sign. For information about how to parse the JSON document, see Make Sure
Your Endpoint is Ready to Process Amazon SNS Messages (p. 58).
The SignatureVersion tells you the signature version. From the signature version, you can
determine the requirements for how to generate the signature. For Amazon SNS notifications,
Amazon SNS currently supports signature version 1. This section provides the steps for creating a
signature using signature version 1.
2. Get the X509 certificate that Amazon SNS used to sign the message. The SigningCertURL value
points to the location of the X509 certificate used to create the digital signature for the message.
Retrieve the certificate from this location.
3. Extract the public key from the certificate. The public key from the certificate specified by
SigningCertURL is used to verify the authenticity and integrity of the message.
4. Determine the message type. The format of the string to sign depends on the message type, which
is specified by the Type value.
5. Create the string to sign. The string to sign is a newline character–delimited list of specific name/
value pairs from the message. Each name/value pair is represented with the name first followed by a
newline character, followed by the value, and ending with a newline character. The name/value pairs
must be listed in byte-sort order.
Depending on the message type, the string to sign must have the following name/value pairs.
Notification
Message
MessageId
Subject (if included in the message)
Timestamp
TopicArn
Type
Message
My Test Message
MessageId
4d4dc071-ddbf-465d-bba8-08f81c89da64
Subject
My subject
Timestamp
2012-06-05T04:37:04.321Z
TopicArn
arn:aws:sns:us-east-1:123456789012:s4-MySNSTopic-1G1WEFCOXTC0P
Type
Notification
Message
MessageId
SubscribeURL
Timestamp
Token
TopicArn
Type
Message
My Test Message
MessageId
3d891288-136d-417f-bc05-901c108273ee
SubscribeURL
https://sns.us-west-2.amazonaws.com/?
Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:123456789012:s4-
MySNSTopic-1G1WEFCOXTC0P&Token=2336412f37fb687f5d51e6e241d09c8058323f60b964268bfe08ce35640228c20
Timestamp
API Version 2010-03-31
82
Amazon Simple Notification Service Developer Guide
Example Code for an Endpoint Java Servlet
2012-06-03T19:25:13.719Z
Token
2336412f37fb687f5d51e6e241d09c8058323f60b964268bfe08ce35640228c208a66d3621bd9f7b012918cfdcfe65e
TopicArn
arn:aws:sns:us-west-2:123456789012:s4-MySNSTopic-1G1WEFCOXTC0P
Type
SubscriptionConfirmation
6. Decode the Signature value from Base64 format. The message delivers the signature in the
Signature value, which is encoded as Base64. Before you compare the signature value with the
signature you have calculated, make sure that you decode the Signature value from Base64 so
that you compare the values using the same format.
7. Generate the derived hash value of the Amazon SNS message. Submit the Amazon SNS message, in
canonical format, to the same hash function used to generate the signature.
8. Generate the asserted hash value of the Amazon SNS message. The asserted hash value is the result
of using the public key value (from step 3) to decrypt the signature delivered with the Amazon SNS
message.
9. Verify the authenticity and integrity of the Amazon SNS message. Compare the derived hash value
(from step 7) to the asserted hash value (from step 8). If the values are identical, then the receiver
is assured that the message has not been modified while in transit and the message must have
originated from Amazon SNS. If the values are not identical, it should not be trusted by the receiver.
The following method implements an example of a handler for HTTP POST requests from Amazon SNS
in a Java servlet.
while (scan.hasNextLine()) {
builder.append(scan.nextLine());
}
Message msg = readMessageFromJson(builder.toString());
The following example Java method creates a signature using information from a Message object
that contains the data sent in the request body and verifies that signature against the original Base64-
encoded signature of the message, which is also read from the Message object.
The following example Java methods work together to create the string to sign for an Amazon SNS
message. The getMessageBytesToSign method calls the appropriate string-to-sign method based on
the message type and runs the string to sign as a byte array. The buildNotificationStringToSign
and buildSubscriptionStringToSign methods create the string to sign based on the formats
described in Verifying the Signatures of Amazon SNS Messages (p. 81).
Topics
• Using Amazon SNS for User Notifications with a Mobile Application as a Subscriber (Mobile
Push) (p. 87)
• Using Amazon SNS for User Notifications with a Mobile Phone Number as a Subscriber (Send
SMS) (p. 153)
Overview
You send push notification messages to both mobile devices and desktops using one of the following
supported push notification services:
The following figure shows an overview of how Amazon SNS is used to send a direct push notification
message to a mobile endpoint.
Push notification services, such as APNS and GCM, maintain a connection with each app and associated
mobile device registered to use their service. When an app and mobile device register, the push
notification service returns a device token. Amazon SNS uses the device token to create a mobile
endpoint, to which it can send direct push notification messages. In order for Amazon SNS to
communicate with the different push notification services, you submit your push notification service
credentials to Amazon SNS to be used on your behalf. For more information, see Amazon SNS Mobile
Push High‐Level Steps (p. 89)
In addition to sending direct push notification messages, you can also use Amazon SNS to send messages
to mobile endpoints subscribed to a topic. The concept is the same as subscribing other endpoint
types, such as Amazon SQS, HTTP/S, email, and SMS, to a topic, as described in What is Amazon Simple
Notification Service? (p. 1). The difference is that Amazon SNS communicates using the push notification
services in order for the subscribed mobile endpoints to receive push notification messages sent to the
topic. The following figure shows a mobile endpoint as a subscriber to an Amazon SNS topic. The mobile
endpoint communicates using push notification services where the other endpoints do not.
Prerequisites
To begin using Amazon SNS mobile push notifications, you need the following:
• A set of credentials for connecting to one of the supported push notification services: ADM, APNS,
Baidu, GCM, MPNS, or WNS.
• A device token or registration ID for the mobile app and device.
• Amazon SNS configured to send push notification messages to the mobile endpoints.
• A mobile app that is registered and configured to use one of the supported push notification services.
Registering your application with a push notification service requires several steps. Amazon SNS needs
some of the information you provide to the push notification service in order to send direct push
notification messages to the mobile endpoint. Generally speaking, you need the required credentials for
connecting to the push notification service, a device token or registration ID (representing your mobile
device and mobile app) received from the push notification service, and the mobile app registered with
the push notification service.
The exact form the credentials take differs between mobile platforms, but in every case, these
credentials must be submitted while making a connection to the platform. One set of credentials is
issued for each mobile app, and it must be used to send a message to any instance of that app.
The specific names will vary depending on which push notification service is being used. For example,
when using APNS as the push notification service, you need a device token. Alternatively, when using
GCM, the device token equivalent is called a registration ID. The device token or registration ID is a
string that is sent to the application by the operating system of the mobile device. It uniquely identifies
an instance of a mobile app running on a particular mobile device and can be thought of as unique
identifiers of this app-device pair.
Amazon SNS stores the credentials (plus a few other settings) as a platform application resource. The
device tokens (again with some extra settings) are represented as objects called platform endpoints.
Each platform endpoint belongs to one specific platform application, and every platform endpoint can
be communicated with by using the credentials that are stored in its corresponding platform application.
The following sections include the prerequisites for each of the supported push notification services.
Once you've obtained the prerequisite information, you can send a push notification message using the
AWS Management Console or the Amazon SNS mobile push APIs. For more information, see Amazon
SNS Mobile Push High‐Level Steps (p. 89).
Topics
• ADM Prerequisites (p. 91)
• Step 1: Create a Kindle Fire App with the ADM Service Enabled (p. 91)
• Step 2: Obtain a Client ID and Client Secret (p. 91)
• Step 3: Obtain an API Key (p. 92)
• Step 4: Obtain a Registration ID (p. 92)
• Step 5: Sending a Push Notification Message to a Kindle Fire app using Amazon SNS and
ADM (p. 93)
ADM Prerequisites
To send push notifications to a Kindle Fire app using Amazon SNS and ADM, you need the following:
If you already have these prerequisites, then you can send a push notification message to a Kindle Fire
app using either the Amazon SNS console or the Amazon SNS API. For more information about using the
Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126). For more information about using
the Amazon SNS API, see Step 5: Sending a Push Notification Message to a Kindle Fire app using Amazon
SNS and ADM (p. 93)
Step 1: Create a Kindle Fire App with the ADM Service Enabled
To send a push notification message to a Kindle Fire app, you must have an Amazon developer account,
set up your development environment, created a Kindle Fire app with ADM enabled, and registered the
app with ADM. For more information, see Integrating Your App with ADM.
1. On the Amazon App Distribution Portal, choose Apps and Services, choose the name of your Kindle
Fire app, and then choose Security Profile. You should see a security profile associated with your
app. If not, choose Security Profiles to create a new security profile.
2. Choose View Security Profile. Make note of the client ID and client secret.
• Obtain an API key by following instructions at Getting Your OAuth Credentials and API Key.
After the sample Kindle Fire app has been imported into your IDE, you need to add the API key for
your Kindle Fire app to the strings.xml file, which is included in the sample Kindle Fire app.
3. Add the API key to the strings.xml file. In your IDE you will find the file included in the values
folder, which is a subfolder of res. You add the string to the following:
<string name="api_key"></string>
4. Run the app to see the registration ID as output to the Android logging system. If you are using
Eclipse with the Android ADT plug-in, you can see the registration ID in the LogCat display window.
For example, the output containing the registration ID will look similar to the following:
amzn1.adm-registration.v2.Example...1cwWJUvgkcPPYcaXCpPWmG3Bqn-
wiqIEzp5zZ7y_jsM0PKPxKhddCzx6paEsyay9Zn3D4wNUJb8m6HXrBf9dqaEw
You should now have the necessary information from ADM (client ID, client secret, API key, and
registration ID) to send push notification messages to your mobile endpoint. You can now send a push
notification message to the Kindle Fire app on your device by either using the Amazon SNS console or
the Amazon SNS API. To use the Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126).
To use the Amazon SNS API, see Step 5: Sending a Push Notification Message to a Kindle Fire app using
Amazon SNS and ADM (p. 93).
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Choose the Libraries tab, and then choose Add Library....
3. Choose AWS SDK for Java, choose Next, and then choose Finish.
sample.demoKindleAppNotification();
// sample.demoAppleAppNotification();
// sample.demoAppleSandboxAppNotification();
// sample.demoBaiduAppNotification();
// sample.demoWNSAppNotification();
// sample.demoMPNSAppNotification();
3. Locate the demoKindleAppNotification method and enter the registration ID you received from
ADM for the value of the registration ID string. For example, it should look similar to the following:
4. Enter the client ID for your app. For example, it should look similar to the following:
5. Enter the client secret for your app. For example, it should look similar to the following:
String clientSecret =
"EXAMPLE01658e75ceb7bf9f71939647b1aa105c1c8eaccabaf7d41f68EXAMPLE";
6. Enter a name for your app. App names must be made up of only uppercase and lowercase ASCII
letters, numbers, underscores, hyphens, and periods, and must be between 1 and 256 characters
long. For example, it should look similar to the following:
7. Run the Java application. You should see output similar to the following in the output window of
your IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/ADM/mypushappname}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/ADM/mypushappname/97e9ced9-
f136-3893-9d60-775467eafebb}
{"ADM": "{ \"data\": { \"message\": \"ENTER YOUR MESSAGE\" } }"}
Published. MessageId=b35fb4bz-b503-4e37-83d4-feu4218d6da6
On your Kindle Fire device, you should see a push notification message appear within the Kindle Fire
app.
Topics
• APNS Prerequisites (p. 95)
• Step 1: Create an iOS App (p. 95)
• Step 2: Obtain an APNS SSL Certificate (p. 95)
• Step 3: Obtain the App Private Key (p. 96)
• Step 4: Verify the Certificate and App Private Key (p. 96)
• Step 5: Obtain a Device Token (p. 96)
• Next Steps (p. 97)
• Send a push notification message to an iOS app using Amazon SNS and APNS (p. 97)
• Send a push notification message to a VoIP iOS app using Amazon SNS and APNS (p. 99)
• Send a push notification message to a Mac OS X app using Amazon SNS and APNS (p. 100)
APNS Prerequisites
To send push notifications to mobile devices using Amazon SNS and APNS, you need to obtain the
following:
If you already have these prerequisites, you can send a push notification message to an iOS app using
either the Amazon SNS console or you can use the Amazon SNS API. For more information about using
the Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126). For more information about
using the Amazon SNS API, see Send a push notification message to an iOS app using Amazon SNS and
APNS (p. 97).
1. On the Apple Developer web site, choose Member Center, choose Certificates, Identifiers and
Profiles, and then choose Certificates.
2. Select the certificate you created for iOS APNS development, choose Download, and then save the
file, which will have the .cer extension type.
To convert the APNS SSL certificate from .cer format to .pem format
• At a command prompt, type the following command. Replace myapnsappcert.cer with the name
of the certificate you downloaded from the Apple Developer web site.
The newly created .pem file will be used to configure Amazon SNS for sending mobile push
notification messages.
The private key associated with the SSL certificate can be exported from the Keychain Access application
on your Mac computer. This is based on the assumption that you have already imported the .cer file you
downloaded from the Apple Developer web site into Keychain Access. You can do this either by copying
the .cer file into Keychain Access or double-clicking the .cer file.
1. Open Keychain Access, select Keys, and then highlight your app private key.
2. Choose File, choose Export Items..., and then enter a name in the Save As: field.
3. Accept the default .p12 file format and then choose Save.
To convert the app private key from .p12 format to .pem format
The newly created .pem file will be used to configure Amazon SNS for sending mobile push
notification messages.
provided by AWS to obtain a device token from APNS. You can use this sample iOS app to help you get
started with Amazon SNS push notifications. For more information, see Configuring Remote Notification
Support in the Apple Local and Remote Notification Programming Guide.
Device Token = <examp1e 29z6j5c4 df46f809 505189c4 c83fjcgf 7f6257e9 8542d2jt 3395kj73>
Note
Do not include spaces in the device token when submitting it to Amazon SNS.
Next Steps
You should now have the necessary information from APNS (SSL certificate, app private key, and device
token) to send push notification messages to your mobile endpoint. You can now send a notification to
the iOS app on your device by either using the Amazon SNS console or the Amazon SNS API.
• To send a notification to the iOS app on your device using the Amazon SNS console, see Using Amazon
SNS Mobile Push (p. 126).
• To use the Amazon SNS API, see Send a push notification message to an iOS app using Amazon SNS
and APNS (p. 97).
• To send a push notification message to a VoIP app using Amazon SNS and APNS, see Send a push
notification message to a VoIP iOS app using Amazon SNS and APNS (p. 99).
• To send a push notification message to a Mac OS X app using Amazon SNS and APNS, see Send a push
notification message to a Mac OS X app using Amazon SNS and APNS (p. 100).
You can also use the Amazon SNS console. For more information about using the Amazon SNS console,
see Using Amazon SNS Mobile Push (p. 126).
Note
The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK
for Java and you have the AWS security credentials for your AWS account. For more information,
see AWS SDK for Java. For more information about credentials, see How Do I Get Security
Credentials? in the AWS General Reference.
2. Import the SNSSamples folder to the top-level directory of the newly created Java project. In
Eclipse, right-choose the name of the Java project and then choose Import, expand General, choose
File System, choose Next, browse to the SNSSamples folder, choose OK, and then choose Finish.
3. In the SNSSamples\src\com\amazonaws\sns\samples\mobilepush folder, open the
AwsCredentials.properties file and add your AWS security credentials.
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Choose the Libraries tab, and then choose Add Library....
3. Choose AWS SDK for Java, choose Next, and then choose Finish.
3. Locate the demoAppleSandboxAppNotification method and enter the device token you
received from APNS for the value of the device token string. For example, it should look similar to
the following:
4. Enter the APNS SSL certificate for your app. At the beginning of each new line in your certificate,
you must add \n. For example, it should look similar to the following:
5. Enter the private key for your app. At the beginning of each new line in your certificate, you must
add \n. For example, it should look similar to the following:
6. Enter a name for your app. App names must be made up of only uppercase and lowercase ASCII
letters, numbers, underscores, hyphens, and periods, and must be between 1 and 256 characters
long. For example, it should look similar to the following:
7. Run the Java application. You should see output similar to the following in the output window of
your IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/APNS_SANDBOX/
mypushappname}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/APNS_SANDBOX/
pushapp/97e9ced9-f136-3893-9d60-775467eafebb}
{"default":"This is the default Message","APNS_SANDBOX":"{ \"aps\" : { \"alert\" :
\"You have got email.\", \"badge\" : 9,\"sound\" :\"default\"}}"}
Published. MessageId=d65fb4bb-b903-5e37-83d4-feb4818d6da3
App names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores,
hyphens, and periods, and must be between 1 and 256 characters long.
3. In the Push Notification Platform field, select Apple Development or Apple Production.
4. In the Push Certification Type field, select VoIP Push Certificate.
5. Select the password encrypted certificate and private key, as exported from Keychain Access on your
Mac computer in the .p12 file format.
6. Enter your password, and then choose Create Platform Application.
App names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores,
hyphens, and periods, and must be between 1 and 256 characters long.
3. In the Push Notification Platform field, select Apple Development or Apple Production.
4. In the Push Certification Type field, select MacOS Push Certificate.
5. Select the password encrypted certificate and private key, as exported from Keychain Access on your
Mac computer in the .p12 file format.
6. Enter your password, and then choose Create Platform Application.
Topics
• Baidu Prerequisites (p. 100)
• Step 1: Create a Baidu Account (p. 101)
• Step 2: Register as a Baidu Developer (p. 102)
• Step 3: Create a Baidu Cloud Push Project (p. 105)
• Step 4: Download and Install the Android Demo App from Baidu (p. 108)
• Step 5: Obtain a User Id and Channel Id from Baidu (p. 111)
• Step 6: Send a Push Notification Message to a Mobile Endpoint using Amazon SNS and
Baidu (p. 112)
Baidu Prerequisites
To send a push notification message to mobile devices using Amazon SNS and Baidu, you need the
following:
• Baidu account
• Registration as a Baidu developer
• Baidu cloud push project
• API key and secret key from a Baidu cloud push project
• Baidu user ID and channel ID
• Android demo app
If you already have these prerequisites, then you can send a push notification message to a mobile
endpoint using the Amazon SNS API. For more information about using the Amazon SNS API, see Step 6:
Send a Push Notification Message to a Mobile Endpoint using Amazon SNS and Baidu (p. 112).
2. Enter an email address, password, and verification code, and then choose 注册 (Registration).
You should then see a page similar to the following, informing you that an activation email has been
sent to the email address you entered.
3. Login to your email account, open the activation email you received from Baidu, and choose the
provided link:
4. After you choose the provided link in the activation email from Baidu, you must then enter the
verification code (Chinese Simplified characters).
Once you have created a Baidu account, you can then register as a developer.
3. On the next page, near the top right corner, choose 开发者服务 (Developer Services).
5. Enter your name, description, and mobile phone number for receiving a verification text message,
and then choose 发送验证码 (Send Verification Code).
You should then receive a text message with a verification number, similar to the following:
6. Complete the developer registration by entering the verification number and then choose 提交
(Submit) on the bottom of the page.
After registering as a Baidu developer, you can then proceed to the next step to create a Baidu cloud
push project. This assumes that you are still logged in. If you are not logged in, then you can use the
following login procedure.
To login to Baidu
2. Enter your Baidu username (email address) and password and then choose 登录 (Login).
3. On the next page, near the top right corner, choose 开发者服务 (Developer Services).
9. Upon successful completion of the project, you will then see a page similar to the following with
your app ID, API Key, and Secret Key. Make note of the API key and secret key, as they will be
needed later.
Step 4: Download and Install the Android Demo App from Baidu
Baidu generates an Android demo app that you can download and install to your mobile device.
1. Starting from the page that displays the app ID, API Key, and Secret Key, choose 云推送 (Cloud
Push)
3. Using reverse domain name notation, enter a package name in the 应用包名 (App Package Name)
box.
6. On the Android mobile device you want to test with, scan the QR code icon using a code scanner,
such as QR Droid, to get a link to a demo app provided by Baidu.
Note
You can also download the demo app by chooseing 下载Android示例 (Download Android
Sample)
The Baidu Push Demo app is included in the downloaded PushDemo.zip package. You
can use the demo app as an example for creating your own app to use with Baidu. In
addition, the push service jar file (pushservice-4.0.0.jar) from Baidu is included in the
PushDemo.zip package. You must use the jar file from Baidu in order to create a new app.
7. Choose the link you receive after scanning the scan code. This will download the demo app provided
by Baidu onto your mobile device.
8. After the download has completed, install the demo app onto your mobile device. You should then
see the following Push Demo app installed:
1. Open Push Demo and then choose, in the bottom right, 无账号绑定 (Bind Without Baidu Account).
You should then see a screen similar to the following with the userId and channelId.
2. Make a note of the userId and channelId, as you will be using them in the next step.
Note
For an example of Java code that is used to retrieve the userID and channelId, see the onBind
method in the MyPushMessageReceiver.java file of the Push Demo app from Baidu. For
more information, see the Android integration guide. To translate this guide into English, you
can paste the URL, http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/guide,
into Bing Translator and then choose Translate.
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Locate the demoBaiduAppNotification method and enter the user ID and channel ID you
received from Baidu for the value of the userId and channelId strings. For example, it should look
similar to the following:
3. Enter the secret key for your application. For example, it should look similar to the following:
4. Enter the API key for your application. For example, it should look similar to the following:
5. Enter a name for your application. Application names must be made up of only uppercase and
lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and
256 characters long. For example, it should look similar to the following:
6. Run the application. You should see output similar to the following in the output window of your
IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/BAIDU/TestApp}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/BAIDU/
TestApp/8f3fdf0d-520b-38d1-8ed2-3301a477eef3}
{Message Body: {"BAIDU":"{\"title\":\"New Notification Received from SNS\",
\"description\":\"Hello World!\"}"}}
{Message Attributes: ("AWS.SNS.MOBILE.BAIDU.MessageKey": "default-channel-msg-key"),
("AWS.SNS.MOBILE.BAIDU.DeployStatus": "1"),("AWS.SNS.MOBILE.BAIDU.MessageType": "0")}
Published!
{MessageId=56a3a3e6-4b4b-59b4-8d1d-eff592c0ffa1}
On your Android device, you should see a push notification message appear within the Android app,
similar to the following:
The following Java example shows how to create an Amazon SNS endpoint for a Baidu app and mobile
device.
// Baidu endpoints are identified by a combination of the userId and channelId which must
be supplied as endpoint attributes,
// without which a valid endpoint cannot be successfully created.
createPlatformEndpointRequest.setAttributes(attributes);
Note the following considerations when using the Amazon SNS API to create an endpoint for use with
Baidu:
• If you specify the endpoint attribute "Token" in the attributes map, this field must encapsulate the
channelId as well.
• The channelId should also be specified as an endpoint attribute with the name "ChannelId".
• The value of the "ChannelId" endpoint attribute and the platform token field and/or "Token" endpoint
attribute must be identical to construct a successful request.
• The userId should be specified as an endpoint attribute with the name "UserId".
• For a successful response, the request must contain valid UserId and ChannelId values in the
attributes. Also, the ChannelId parameter entered using setPlatformToken(String), which is a part of
CreatePlatformEndpointRequest, must be the same as the ChannelId specified in the attributes map.
The following Java example shows how to send a push notification message to a mobile endpoint and
how to use the optional message attributes for structuring the message. If an attribute is not sent, a
default value is auto-set in its place.
Note
The push notification message cannot exceed 4,096 bytes, which is the maximum size allowed
by Baidu.
// Insert your desired value of Message Type here. 0 = IN-APP MESSAGE, 1 = ALERT
NOTIFICATION
messageAttributes.put("AWS.SNS.MOBILE.BAIDU.MessageType", new
MessageAttributeValue().withDataType("String").withStringValue("1"));
Note the following considerations when using the optional message attributes for structuring the
message:
• AWS.SNS.MOBILE.BAIDU.DeployStatus
1 – Generates an alert notification. Alert notifications are restricted to the following format:
{"title":"<TITLE>","description":"<DESCRIPTION>"}
<TITLE> and <DESCRIPTION> are the title and description you desire for your alert notification. If the
message is incorrectly formatted JSON, the request fails.
• AWS.SNS.MOBILE.BAIDU.MessageKey
On April 10, 2018, Google announced the deprecation of its Google Cloud Messaging (GCM) platform.
Specifically, the GCM server and client APIs are deprecated and will be removed on April 11, 2019. For
more information, see The End of Google Cloud Messaging, and What it Means for Your Apps.
Google Cloud Messaging for Android (GCM) is a service that enables you to send push notification
messages to an Android app. This section describes how to obtain the GCM prerequisites and send a push
notification message to a mobile endpoint.
Topics
• GCM Prerequisites (p. 116)
• Step 1: Create a Google API Project and Enable the GCM Service (p. 117)
• Step 2: Obtain the Server API Key (p. 117)
• Step 3: Obtain a Registration ID from GCM (p. 117)
• Step 4: Send a Push Notification Message to a Mobile Endpoint using GCM (p. 118)
GCM Prerequisites
To send push notification messages to an Android app, you need the following:
If you already have these prerequisites, then you can either use the Amazon SNS console to send
a push notification message to the mobile endpoint or you can use the Amazon SNS API. For more
information about using the Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126). For
more information about using the Amazon SNS API, see Step 4: Send a Push Notification Message to a
Mobile Endpoint using GCM (p. 118).
Step 1: Create a Google API Project and Enable the GCM Service
To send an push notification message to an Android app, you must have a Google API project and enable
the GCM service.
1. On the Google APIs Console web site, verify that you have a Google API project.
2. Choose Services, and make sure Google Cloud Messaging for Android is turned on.
1. On the Google APIs Console web site, choose API Access and make note of the server API key with
the Key for server apps (with IP locking) label.
2. If you have not yet created a server API key, then choose Create new Server key. This key will be
used later in this section to send a push notification to a mobile endpoint.
The following steps show how to use the sample Android app provided by AWS to obtain a registration
ID from GCM. You can use this sample Android app to help you get started with Amazon SNS push
notifications. This sample app requires the Android SDK, the Google Play Services SDK, and the Android
Support Library package. For more information about these SDKs, see Get the Android SDK and Setup
Google Play Services SDK. For more information about the Android Support Library package, see
Support Library Setup.
Note
The provided sample Android app is compatible with physical devices running Android version
2.3 or later and with virtual devices running Google API 17 or later.
After the sample Android app has been imported into your IDE, you need to add the Project Number
for your Google API project to the strings.xml file, which is included in the sample Android app.
3. Add the Project Number for your Google API project to the strings.xml file. In your IDE, you will
find the file included in the values folder, which is a subfolder of res. The string will look similar to
the following:
<string name="project_number">012345678912</string>
5. Run the app to see the registration ID as output to the Android logging system. If you are using
Eclipse with the Android ADT plug-in, you can see the registration ID in the LogCat display window.
For example, the output containing the registration ID will look similar to the following:
You should now have a registration ID, server API key, and Android app registered with GCM. You can
now send a notification to the Android app on your device by either using the Amazon SNS console or
the Amazon SNS API. To use the Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126).
To use the Amazon SNS API, see Step 4: Send a Push Notification Message to a Mobile Endpoint using
GCM (p. 118).
Note
The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK
for Java and you have the AWS security credentials for your AWS account. For more information,
see AWS SDK for Java. For more information about credentials, see How Do I Get Security
Credentials? in the AWS General Reference.
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Choose the Libraries tab, and then choose Add Library....
3. Choose AWS SDK for Java, choose Next, and then choose Finish.
2. Locate the demoAndroidAppNotification method and enter the registration ID you received
from GCM for the value of the registration ID string. For example, it should look similar to the
following:
3. Enter the API key for your application. For example, it should look similar to the following:
4. Enter a name for your application. Application names must be made up of only uppercase and
lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and
256 characters long. For example, it should look similar to the following:
5. Run the application. You should see output similar to the following in the output window of your
IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/GCM/gcmpushapp}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/GCM/
gcmpushapp/5e3e9847-3183-3f18-a7e8-671c3a57d4b3}
{"default":"This is the default message","GCM":"{\"delay_while_idle\":true,
\"collapse_key\":\"Welcome\",\"data\":{\"message\":\"Visit Amazon!\",\"url\":\"http://
www.amazon.com/\"},\"time_to_live\":125,\"dry_run\":false}"}
Published. MessageId=1ca8d7d1-c261-5bfc-8689-9db269c4e46c
On your Android device, you should see a push notification message appear within the Android app,
similar to the following:
Topics
• MPNS Prerequisites (p. 120)
• Step 1: Set Up Your Windows Phone App to Receive Push Notifications Messages (p. 121)
• Step 2: Get a Push Notification URI from MPNS (p. 121)
• Step 3: Create a Windows Developer Account (p. 121)
• Step 4: Upload TLS Certificate (p. 121)
• Step 5: Send a Push Notification Message to a Windows Phone app using Amazon SNS and
MPNS (p. 121)
MPNS Prerequisites
To send an unauthenticated push notification message to a Windows Phone app using Amazon SNS and
MPNS, you need the following:
To send an authenticated push notification message to a Windows Phone app using Amazon SNS and
MPNS, you also need the following:
If you already have these prerequisites, then you can send a push notification message to a Windows
Phone app using either the Amazon SNS console or the Amazon SNS API. For more information about
using the Amazon SNS console, see Using Amazon SNS Mobile Push (p. 126). For more information
about using the Amazon SNS API, see Step 5: Send a Push Notification Message to a Windows Phone app
using Amazon SNS and MPNS (p. 121).
gathered prerequisite information to the AWS sample file SNSMobilePush.java, which is included in
the snsmobilepush.zip file.
You can also use the Amazon SNS console. However, to send toast notifications, you must use the
Amazon SNS API. For more information about using the Amazon SNS console, see Using Amazon SNS
Mobile Push (p. 126).
Note
The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK
for Java and you have the AWS security credentials for your AWS account. For more information,
see AWS SDK for Java. For more information about credentials, see How Do I Get Security
Credentials? in the AWS General Reference.
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Choose the Libraries tab, and then choose Add Library....
3. Choose AWS SDK for Java, choose Next, and then choose Finish.
2. Locate the demoMPNSAppNotification method and enter the notification URI you received from
MPNS for the value of the notificationChannelURI string.
3. Enter a name for your application. Application names must be made up of only uppercase and
lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and
256 characters long. For example, it should look similar to the following:
4. Enter the MPNS TLS certificate in .pem file format. You must include the complete certificate
chain, beginning with the root CA certificate at the top and ending with the issued certificate at
the bottom. At the beginning of each new line in your certificate, you must add \n. For example, it
should look similar to the following:
5. Enter the private key for the MPNS TLS certificate in .pem file format. At the beginning of each new
line in your certificate, you must add \n. For example, it should look similar to the following:
6. Run the application. You should see output similar to the following in the output window of your
IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/MPNS/TestApp}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/MPNS/TestApp/557597f8-
be4a-3035-8c6d-bb7fa8b20fef}
{Message Body: {"MPNS":"<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification
xmlns:wp=\"WPNotification\"><wp:Tile><wp:Count>23</wp:Count><wp:Title>This is a tile
notification</wp:Title></wp:Tile></wp:Notification>"}}
{Message Attributes: ("AWS.SNS.MOBILE.MPNS.Type": "token"),
("AWS.SNS.MOBILE.MPNS.NotificationClass": "realtime")}
Published!
{MessageId=ce9855bf-395f-5a1a-a4b9-19ace305780d}
On your Windows Phone, you should see a push notification message appear within the app.
Topics
• WNS Prerequisites (p. 124)
• Step 1: Set Up Your App to Receive Push Notifications Messages (p. 124)
WNS Prerequisites
To send push notification messages to Windows devices using Amazon SNS and WNS, you need the
following:
• Windows 8 (and later) or Windows Phone 8.1 app configured to use WNS
• Push notification URI from WNS
• Package security identifier
• Secret key
If you already have these prerequisites, then you can send a push notification message to an app using
either the Amazon SNS console or the Amazon SNS API. For more information about using the Amazon
SNS console, see Using Amazon SNS Mobile Push (p. 126). For more information about using the
Amazon SNS API, see Step 5: Send a Push Notification Message to an App using Amazon SNS and
WNS (p. 124).
1. Right-choose the Java project folder, choose Build Path, and then choose Configure Build Path...
2. Choose the Libraries tab, and then choose Add Library....
3. Choose AWS SDK for Java, choose Next, and then choose Finish.
2. Locate the demoWNSAppNotification method and enter the string values for the push
notification URI, package security identifier, and secret key.
3. Enter a name for your application. Application names must be made up of only uppercase and
lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and
256 characters long. For example, it should look similar to the following:
4. Run the application. You should see output similar to the following in the output window of your
IDE:
===========================================
Getting Started with Amazon SNS
===========================================
{PlatformApplicationArn: arn:aws:sns:us-west-2:111122223333:app/WNS/TestApp}
{EndpointArn: arn:aws:sns:us-west-2:111122223333:endpoint/WNS/TestApp/17cc2f2a-
dfa8-3450-90c6-e1f88d820f3d}
{Message Body: {"WNS":"<badge version=\"1\" value=\"23\"/>"}}
{Message Attributes: ("AWS.SNS.MOBILE.WNS.Type": "wns/badge"),
("AWS.SNS.MOBILE.WNS.CachePolicy": "cache")}
Published!
{MessageId=d4899281-927e-5f68-9fd0-de9248be6d47}
On your Windows device, you should see a push notification message appear within the app.
Topics
• Register Your Mobile App with AWS (p. 126)
• Add Device Tokens or Registration IDs (p. 128)
• Create a Platform Endpoint and Manage Device Tokens (p. 130)
• Send a Direct Message to a Mobile Device (p. 137)
• Send Messages to Mobile Devices Subscribed to a Topic (p. 137)
• Send Custom Platform-Specific Payloads in Messages to Mobile Devices (p. 137)
App names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores,
hyphens, and periods, and must be between 1 and 256 characters long.
3. In the Push notification platform box, select the platform that the app is registered with and then
enter the appropriate credentials.
Note
If you are using one of the APNS platforms, then you can select Choose file to upload
the .p12 file (exported from Keychain Access) to Amazon SNS.
For detailed instructions on how to acquire the following information, see Getting Started with
Amazon Device Messaging (p. 90), Getting Started with Apple Push Notification Service (p. 94),
Getting Started with Baidu Cloud Push (p. 100), Getting Started with Google Cloud Messaging for
Android (p. 116), Getting Started with MPNS (p. 120), or Getting Started with WNS (p. 123).
Platform Credentials
Platform Credentials
Platform Credentials
4. After you have entered this information, then choose Add New App.
This registers the app with Amazon SNS, which creates a platform application object for the selected
platform and then returns a corresponding PlatformApplicationArn.
You can add device tokens and registration IDs to Amazon SNS using the following methods:
• Manually add a single token to AWS using the AWS Management Console
• Migrate existing tokens from a CSV file to AWS using the AWS Management Console
• Register tokens from devices that will install your apps in the future
Now with the endpoint created, you can either send messages directly to a mobile device or send
messages to mobile devices that are subscribed to a topic.
You can migrate existing tokens contained in a CSV file. The CSV file cannot be larger than 2MB. When
migrating several tokens, it is recommended to use the CreatePlatformEndpoint API. Each of the
tokens in the CSV file must be followed by a newline. For example, your CSV file should look similar to
the following:
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--KMTlmMWxwRkxMaDNST2luZz01,"User data
with spaces requires quotes"
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--
KMTlmMWxwRkxMaDNST2luZz04,"Data,with,commas,requires,quotes"
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--KMTlmMWxwRkxMaDNST2luZz02,"Quoted data
requires ""escaped"" quotes"
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--KMTlmMWxwRkxMaDNST2luZz03,"{""key"":
""json is allowed"", ""value"":""endpoint"", ""number"": 1}"
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--
KMTlmMWxwRkxMaDNST2luZz05,SimpleDataNoQuotes
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--KMTlmMWxwRkxMaDNST2luZz06,"The following
line has no user data"
amzn1.adm-registration.v1.XpvSSUk0Rc3hTVVV--TOKEN--KMTlmMWxwRkxMaDNST2luZz07
APBTKzPGlCyT6E6oOfpdwLpcRNxQp5vCPFiFeru9oZylc22HvZSwQTDgmmw9WdNlXMerUPxmpX0w1,"Different
token style"
The following steps show how to use the sample Java app (bulkupload package) provided by AWS to
upload several tokens (device tokens or registration IDs) to Amazon SNS. You can use this sample app to
help you get started with uploading your existing tokens.
Note
The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK
for Java and you have the AWS security credentials for your AWS account. For more information,
see AWS SDK for Java. For more information about credentials, see How Do I Get Security
Credentials? in the AWS General Reference.
applicationarn:arn:aws:sns:us-west-2:111122223333:app/GCM/gcmpushapp
csvfilename:C:\\mytokendirectory\\mytokens.csv
goodfilename:C:\\mylogfiles\\goodtokens.csv
badfilename:C:\\mylogfiles\\badtokens.csv
delimiterchar:'
quotechar:"
numofthreads:5
In this example, the endpoints that were created for the tokens that were uploaded successfully to
Amazon SNS would be logged to goodTokens.csv, while the malformed tokens would be logged
to badTokens.csv. In addition, you should see STD OUT logs written to the console of Eclipse,
containing content similar to the following:
To register tokens from devices that will install your apps in the future
• Use the Amazon Cognito service: Your mobile app will need credentials to create endpoints
associated with your Amazon SNS platform application. We recommend that you use temporary
credentials that expire after a period of time. For most scenarios, we recommend that you use Amazon
Cognito to create temporary security credentials. For more information, see the Amazon Cognito
Developer Guide . If you would like to be notified when an app registers with Amazon SNS, you can
register to receive an Amazon SNS event that will provide the new endpoint ARN. You can also use
the ListEndpointByPlatformApplication API to obtain the full list of endpoints registered with
Amazon SNS.
• Use a proxy server: If your application infrastructure is already set up for your mobile apps to call in
and register on each installation, you can continue to use this setup. Your server will act as a proxy
and pass the device token to Amazon SNS mobile push notifications, along with any user data you
would like to store. For this purpose, the proxy server will connect to Amazon SNS using your AWS
credentials and use the CreatePlatformEndpoint API call to upload the token information. The
newly created endpoint Amazon Resource Name (ARN) will be returned, which your server can store
for making subsequent publish calls to Amazon SNS.
This section describes the recommended approach for creating a platform endpoint and managing
device tokens.
Topics
• Create a Platform Endpoint (p. 131)
• If the platform endpoint already exists, then do not create it again. Return to the caller the ARN of the
existing platform endpoint.
• If the platform endpoint with the same device token but different settings already exists, then do not
create it again. Throw an exception to the caller.
• If the platform endpoint does not exist, then create it. Return to the caller the ARN of the newly-
created platform endpoint.
You should not call the create platform endpoint action immediately every time an app starts, because
this approach does not always provide a working endpoint. This can happen, for example, when an app
is uninstalled and reinstalled on the same device and the endpoint for it already exists but is disabled. A
successful registration process should accomplish the following:
Pseudo Code
The following pseudo code describes a recommended practice for creating a working, current, enabled
platform endpoint in a wide variety of starting conditions. This approach works whether this is a first
time the app is being registered or not, whether the platform endpoint for this app already exists, and
whether the platform endpoint is enabled, has the correct device token, and so on. It is safe to call it
multiple times in a row, as it will not create duplicate platform endpoints or change an existing platform
endpoint if it is already up to date and enabled.
retrieve the latest device token from the mobile operating system
if (the platform endpoint ARN is not stored)
# this is a first-time registration
call create platform endpoint
store the returned platform endpoint ARN
endif
endif
endif
This approach can be used any time the app wants to register or re-register itself. It can also be used
when notifying Amazon SNS of a device token change. In this case, you can just call the action with the
latest device token value. Some points to note about this approach are:
• There are two cases where it may call the create platform endpoint action. It may be called at the very
beginning, where the app does not know its own platform endpoint ARN, as happens during a first-
time registration. It is also called if the initial get endpoint attributes action call fails with a not-found
exception, as would happen if the application knows its endpoint ARN but it was deleted.
• The get endpoint attributes action is called to verify the platform endpoint's state even if the platform
endpoint was just created. This happens when the platform endpoint already exists but is disabled. In
this case, the create platform endpoint action succeeds but does not enable the platform endpoint, so
you must double-check the state of the platform endpoint before returning success.
class RegistrationExample {
if (createNeeded) {
// No platform endpoint ARN is stored; need to call createEndpoint.
endpointArn = createEndpoint();
createNeeded = false;
}
updateNeeded = !geaRes.getAttributes().get("Token").equals(token)
|| !geaRes.getAttributes().get("Enabled").equalsIgnoreCase("true");
if (createNeeded) {
createEndpoint(token);
}
if (updateNeeded) {
// The platform endpoint is out of sync with the current data;
// update the token and enable it.
System.out.println("Updating platform endpoint " + endpointArn);
Map attribs = new HashMap();
attribs.put("Token", token);
attribs.put("Enabled", "true");
SetEndpointAttributesRequest saeReq =
new SetEndpointAttributesRequest()
.withEndpointArn(endpointArn)
.withAttributes(attribs);
client.setEndpointAttributes(saeReq);
}
}
/**
* @return never null
* */
private String createEndpoint(String token) {
/**
* @return the ARN the app was registered under previously, or null if no
* platform endpoint ARN is stored.
*/
private String retrieveEndpointArn() {
// Retrieve the platform endpoint ARN from permanent storage,
/**
* Stores the platform endpoint ARN in permanent storage for lookup next time.
* */
private void storeEndpointArn(String endpointArn) {
// Write the platform endpoint ARN to permanent storage.
arnStorage = endpointArn;
}
}
For more information, see Using Amazon SNS Mobile Push APIs (p. 146).
AWS SDK for .NET
class RegistrationExample
{
private AmazonSimpleNotificationServiceClient client = new
AmazonSimpleNotificationServiceClient();
private String arnStorage = null;
if (createNeeded)
{
// No platform endpoint ARN is stored; need to call createEndpoint.
EndpointArn = CreateEndpoint(token, applicationArn);
createNeeded = false;
}
{
// We had a stored ARN, but the platform endpoint associated with it
// disappeared. Recreate it.
createNeeded = true;
}
if (createNeeded)
{
CreateEndpoint(token, applicationArn);
}
if (updateNeeded)
{
// The platform endpoint is out of sync with the current data;
// update the token and enable it.
Console.WriteLine("Updating platform endpoint " + endpointArn);
Dictionary<String,String> attribs = new Dictionary<String,String>();
attribs["Token"] = token;
attribs["Enabled"] = "true";
SetEndpointAttributesRequest saeReq = new SetEndpointAttributesRequest();
saeReq.EndpointArn = EndpointArn;
saeReq.Attributes = attribs;
client.SetEndpointAttributes(saeReq);
}
}
try
{
Console.WriteLine("Creating platform endpoint with token " + token);
CreatePlatformEndpointRequest cpeReq = new CreatePlatformEndpointRequest();
cpeReq.PlatformApplicationArn = applicationArn;
cpeReq.Token = token;
CreatePlatformEndpointResponse cpeRes =
client.CreatePlatformEndpoint(cpeReq);
endpointArn = cpeRes.EndpointArn;
}
catch (InvalidParameterException ipe)
{
String message = ipe.Message;
Console.WriteLine("Exception message: " + message);
Regex rgx = new Regex(".*Endpoint (arn:aws:sns[^ ]+) already exists with
the same token.*",
RegexOptions.IgnoreCase);
MatchCollection m = rgx.Matches(message);
if (m.Count > 0)
{
// The platform endpoint already exists for this token, but with
// additional custom data that
// createEndpoint doesn't want to overwrite. Just use the
// existing platform endpoint.
endpointArn = m[1].Value;
}
else
{
// Rethrow the exception, the input is actually bad.
throw ipe;
}
}
EndpointArn = endpointArn;
return endpointArn;
// Get/Set arn
public String EndpointArn
{
get
{
return arnStorage;
}
set
{
arnStorage = value;
}
}
}
For more information, see Using Amazon SNS Mobile Push APIs (p. 146).
Troubleshooting
Repeatedly Calling Create Platform Endpoint with an Outdated Device Token
Especially for GCM endpoints, you may think it is best to store the first device token the application
is issued and then call the create platform endpoint with that device token every time on application
startup. This may seem correct since it frees the app from having to manage the state of the device
token and Amazon SNS will automatically update the device token to its latest value. However, this
solution has a number of serious issues:
• Amazon SNS relies on feedback from GCM to update expired device tokens to new device tokens. GCM
retains information on old device tokens for some time, but not indefinitely. Once GCM forgets about
the connection between the old device token and the new device token, Amazon SNS will no longer be
able to update the device token stored in the platform endpoint to its correct value; it will just disable
the platform endpoint instead.
• The platform application will contain multiple platform endpoints corresponding to the same device
token.
• Amazon SNS imposes a limit to the number of platform endpoints that can be created starting with
the same device token. Eventually, the creation of new endpoints will fail with an invalid parameter
exception and the following error message: "This endpoint is already registered with a different token."
This is because the device token associated with the platform endpoint is genuinely invalid. Deliveries to
it cannot succeed because it no longer corresponds to any installed app. The next time it is published to,
the mobile platform will again inform Amazon SNS that the device token is invalid, and Amazon SNS will
again disable the platform endpoint.
To re-enable a disabled platform endpoint, it needs to be associated with a valid device token (with a
set endpoint attributes action call) and then enabled. Only then will deliveries to that platform endpoint
become successful. The only time re-enabling a platform endpoint without updating its device token
will work is when a device token associated with that endpoint used to be invalid but then became valid
again. This can happen, for example, when an app was uninstalled and then re-installed on the same
mobile device and receives the same device token. The approach presented above does this, making sure
to only re-enable a platform endpoint after verifying that the device token associated with it is the most
current one available.
1. Go to https://console.aws.amazon.com/sns/v2/home.
2. In the left Navigation pane, choose Apps and choose the app that you want to send a message to.
3. On the Application Details screen, select Endpoint Actions and then choose Publish.
4. On the Publish dialog box, enter the message to appear in the app on the mobile device and then
choose Publish.
The notification message will then be sent from Amazon SNS to the platform notification service,
which will then send the message to the app.
1. Follow the steps as described in Subscribe to a Topic (p. 5). You just need to select Application in the
Protocol drop-down menu and then enter the mobile endpoint Amazon Resource Name (ARN) in the
Endpoint box.
2. Follow the steps to publish messages to a topic, as described in Publish to a Topic (p. 6), then all
mobile endpoints that are subscribed to the topic will be sent the message.
"GCM":"{
"data":{
"message":"Check out these awesome deals!",
"url":"www.amazon.com"
}
}"
}
When sending messages using the console quotation marks must be escaped (\"), as the following
example shows.
{
"GCM":"{
\"data\":{
\"message\":\"Check out these awesome deals!\",
\"url\":\"www.amazon.com\"
}
}"
}
When entered in the Amazon SNS console, the example should look similar to the following:
{
"GCM":"{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com
\"}}"
}
{
"GCM":"{
"data":{
"message":"Check out these awesome deals!",
"url":"www.amazon.com"
},
"time_to_live": 3600,
"collapse_key": "deals"
}"
}
When entered in the Amazon SNS console, the example should look similar to the following:
{
"GCM":"{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com
\"},\"time_to_live\": 3600,\"collapse_key\":\"deals\"}"
}
For a list of the supported key-value pairs in each of the push notification services supported in Amazon
SNS, see the following links:
{
"default": "This is the default message which must be present when publishing a message to
a topic. The default message will only be used if a message is not present for
one of the notification platforms.",
"APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\":\"www.amazon.com
\"} }",
"GCM":"{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com
\"}}",
"ADM": "{ \"data\": { \"message\": \"Check out these awesome deals!\",\"url\":
\"www.amazon.com\" }}"
}
• Know whether a push notification message was delivered from Amazon SNS to the push notification
service.
• Identify the response sent from the push notification service to Amazon SNS.
• Determine the message dwell time (the time between the publish timestamp and just before handing
off to a push notification service).
To configure application attributes for message delivery status, you can use the AWS Management
Console, AWS software development kits (SDKs), or query API.
Topics
• Configuring Message Delivery Status Attributes with the AWS Management Console (p. 139)
• Amazon SNS Message Delivery Status CloudWatch Log Examples (p. 140)
• Configuring Message Delivery Status Attributes with the AWS SDKs (p. 141)
• Platform Response Codes (p. 141)
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left Navigation pane, choose Apps, and then choose the app containing the endpoints for
which you want receive CloudWatch Logs.
3. Choose Application Actions and then choose Delivery Status.
SUCCESS
{
"status": "SUCCESS",
"notification": {
"timestamp": "2015-01-26 23:07:39.54",
"messageId": "9655abe4-6ed6-5734-89f7-e6a6a42de02a"
},
"delivery": {
"statusCode": 200,
"dwellTimeMs": 65,
"token": "Examplei7fFachkJ1xjlqT64RaBkcGHochmf1VQAr9k-
IBJtKjp7fedYPzEwT_Pq3Tu0lroqro1cwWJUvgkcPPYcaXCpPWmG3Bqn-
wiqIEzp5zZ7y_jsM0PKPxKhddCzx6paEsyay9Zn3D4wNUJb8m6HXrBf9dqaEw",
"attempts": 1,
"providerResponse": "{\"multicast_id\":5138139752481671853,\"success\":1,\"failure
\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1422313659698010%d6ba8edff9fd7ecd
\"}]}",
"destination": "arn:aws:sns:us-east-1:111122223333:endpoint/GCM/GCMPushApp/
c23e42de-3699-3639-84dd-65f84474629d"
}
}
FAILURE
{
"status": "FAILURE",
"notification": {
"timestamp": "2015-01-26 23:29:35.678",
"messageId": "c3ad79b0-8996-550a-8bfa-24f05989898f"
},
"delivery": {
"statusCode": 8,
"dwellTimeMs": 1451,
"token": "examp1e29z6j5c4df46f809505189c4c83fjcgf7f6257e98542d2jt3395kj73",
"attempts": 1,
"providerResponse": "NotificationErrorResponse(command=8, status=InvalidToken,
id=1, cause=null)",
"destination": "arn:aws:sns:us-east-1:111122223333:endpoint/APNS_SANDBOX/
APNSPushApp/986cb8a1-4f6b-34b1-9a1b-d9e9cb553944"
}
}
For a list of push notification service response codes, see Platform Response Codes (p. 141).
The following Java example shows how to use the SetPlatformApplicationAttributes API
to configure application attributes for message delivery status of push notification messages.
You can use the following attributes for message delivery status: SuccessFeedbackRoleArn,
FailureFeedbackRoleArn, and SuccessFeedbackSampleRate. The SuccessFeedbackRoleArn
and FailureFeedbackRoleArn attributes are used to give Amazon SNS write access to use
CloudWatch Logs on your behalf. The SuccessFeedbackSampleRate attribute is for specifying
the sample rate percentage (0-100) of successfully delivered messages. After you configure the
FailureFeedbackRoleArn attribute, then all failed message deliveries generate CloudWatch Logs.
For more information about the SDK for Java, see Getting Started with the AWS SDK for Java.
Amazon Device Messaging (ADM) See Response Format in the ADM documentation.
Apple Push Notification Service (APNS) See HTTP/2 Response from APNs in
Communicating with APNs in the Local and
Remote Notification Programming Guide.
Firebase Cloud Messaging (FCM) See Downstream Message Error Response Codes
in the Firebase Cloud Messaging documentation.
Microsoft Push Notification Service for Windows See Push Notification Service Response Codes for
Phone (MPNS) Windows Phone 8 in the Windows 8 Development
documentation.
Windows Push Notification Services (WNS) See "Response codes" in Push Notification
Service Request and Response Headers (Windows
Runtime Apps) in the Windows 8 Development
documentation.
Topics
• Available Application Events (p. 142)
• Sending Application Event Notifications (p. 142)
Each of the preceding attributes can be associated with an application. The application can then receive
these event notifications.
• Each topic that receives notifications should contain only subscriptions for programmatic
endpoints, such as HTTP or HTTPS endpoints, Amazon SQS queues, or AWS Lambda
functions.
• To reduce the amount of processing that is triggered by the notifications, limit each topic's
subscriptions to a small number (e.g., five or fewer).
You can send application event notifications by using the Amazon SNS console, the AWS Command Line
Interface (AWS CLI), or the AWS SDKs.
AWS CLI
Run the set-platform-application-attributes command.
The following example sets the same Amazon SNS topic for all four application events:
AWS SDKs
Call one of the following APIs, depending on your target programming language or platform:
Android setPlatformApplicationAttributes
iOS AWSSNSSetPlatformApplicationAttributesInput
Java setPlatformApplicationAttributes
JavaScript setPlatformApplicationAttributes
.NET SetPlatformApplicationAttributes
PHP SetPlatformApplicationAttributes
Ruby set_platform_application_attributes
Unity SetPlatformApplicationAttributesAsync
The TTL message attribute is used to specify expiration metadata about a message. This allows you to
specify the amount of time that the push notification service, such as Apple Push Notification Service
(APNS) or GCM, has to deliver the message to the endpoint. If for some reason (such as the mobile device
has been turned off) the message is not deliverable within the specified TTL, then the message will be
dropped and no further attempts to deliver it will be made. To specify TTL within message attributes,
you can use the AWS Management Console, AWS software development kits (SDKs), or query API.
Topics
• TTL Message Attributes for Push Notification Services (p. 144)
• Precedence Order for Determining TTL (p. 145)
• Specifying TTL with the AWS Management Console (p. 145)
• Specifying TTL with the AWS SDKs (p. 145)
Each of the push notification services handle TTL differently. Amazon SNS provides an abstract view of
TTL over all the push notification services, which makes it easier to specify TTL. When you use the AWS
Management Console to specify TTL (in seconds), you only have to enter the TTL value once and Amazon
SNS will then calculate the TTL for each of the selected push notification services when publishing the
message.
TTL is relative to the publish time. Before handing off a push notification message to a specific push
notification service, Amazon SNS computes the dwell time (the time between the publish timestamp and
just before handing off to a push notification service) for the push notification and passes the remaining
TTL to the specific push notification service. If TTL is shorter than the dwell time, Amazon SNS won't
attempt to publish.
If you specify a TTL for a push notification message, then the TTL value must be a positive integer, unless
the value of 0 has a specific meaning for the push notification service—such as with APNS and GCM. If
the TTL value is set to 0 and the push notification service does not have a specific meaning for 0, then
Amazon SNS will drop the message. For more information about the TTL parameter set to 0 when using
APNS, see Table A-3 Item identifiers for remote notifications in the Binary Provider API documentation.
For more information about the TTL parameter set to 0 when using GCM, see Lifetime of a message.
If you set different TTL values (one in message attributes and another in the message body) for the same
message, then Amazon SNS will modify the TTL in the message body to match the TTL specified in the
message attribute.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the left Navigation pane, choose Apps, and then choose the app containing the endpoints you
want to set TTL for when publishing a message.
3. Select the endpoints to publish a message to, choose Endpoint Actions and then choose Publish.
4. On the Publish dialog box, enter the number of seconds for Time to Live (TTL) and then choose
Publish Message.
For more information about the SDK for Java, see Getting Started with the AWS SDK for Java.
The following Java example shows how to configure a TTL message attribute and publish the message to
an endpoint, which in this example is registered with Baidu Cloud Push:
// Insert your desired value (in seconds) of TTL here. For example, a TTL of 1 day would be
86,400 seconds.
messageAttributes.put("AWS.SNS.MOBILE.BAIDU.TTL", new
MessageAttributeValue().withDataType("String").withStringValue("86400"));
For more information about using message attributes with Amazon SNS, see Amazon SNS Message
Attributes (p. 17).
To send a push notification message to a mobile app and device using the APIs, you must first use the
CreatePlatformApplication action, which returns a PlatformApplicationArn attribute. The
PlatformApplicationArn attribute is then used by CreatePlatformEndpoint, which returns an
EndpointArn attribute. You can then use the EndpointArn attribute with the Publish action to send
a notification message to a mobile app and device, or you could use the EndpointArn attribute with the
Subscribe action for subscription to a topic. For more information, see Amazon SNS Mobile Push High‐
Level Steps (p. 89).
CreatePlatformApplication
Creates a platform application object for one of the supported push notification services,
such as APNS and GCM, to which devices and mobile apps may register. Returns a
PlatformApplicationArn attribute, which is used by the CreatePlatformEndpoint action.
CreatePlatformEndpoint
Creates an endpoint for a device and mobile app on one of the supported push notification services.
CreatePlatformEndpoint uses the PlatformApplicationArn attribute returned from the
CreatePlatformApplication action. The EndpointArn attribute, which is returned when using
CreatePlatformEndpoint, is then used with the Publish action to send a notification message
to a mobile app and device.
CreateTopic
Deletes the endpoint for a device and mobile app on one of the supported push notification services.
DeletePlatformApplication
ListEndpointsByPlatformApplication
Lists the endpoints and endpoint attributes for devices and mobile apps in a supported push
notification service.
ListPlatformApplications
Lists the platform application objects for the supported push notification services.
Publish
Sets the attributes for an endpoint for a device and mobile app.
SetPlatformApplicationAttributes
Deletes a subscription.
EventDeliveryAttemptFailure
EventDeliveryAttemptFailure
400 CreatePlatformApplication
has invalid ARN format has invalid ARN format.
EventDeliveryAttemptFailure
EventDeliveryAttemptFailure
400 CreatePlatformApplication
is not an existing Topic is not an existing topic.
EventDeliveryAttemptFailure
EventDeliveryAttemptFailure
400 SetPlatformAttributes
has invalid ARN format has invalid ARN format.
EventDeliveryAttemptFailure
EventDeliveryAttemptFailure
400 SetPlatformAttributes
is not an existing Topic is not an existing topic.
Target ARN is valid but The target ARN is valid, 403 Publish
does not belong to the but does not belong to
user the user.
You can set SMS preferences (p. 154) for your AWS account to tailor your SMS deliveries for your use
cases and budget. For example, you can choose whether your messages are optimized for cost or reliable
delivery. You can also specify spending limits for individual message deliveries and monthly spending
limits for your AWS account.
Where required by local laws and regulations (such as the US and Canada), SMS recipients can opt
out (p. 173), which means that they choose to stop receiving SMS messages from your AWS account.
After a recipient opts out, you can, with limitations, opt in the phone number again so that you can
resume sending messages to it.
Amazon SNS supports SMS messaging in several regions, and you can send messages to more than 200
countries and regions. For more information, see Supported Regions and Countries (p. 178).
Topics
• Setting SMS Messaging Preferences (p. 154)
• Sending an SMS Message (p. 157)
• Sending an SMS Message to Multiple Phone Numbers (p. 161)
• Monitoring SMS Activity (p. 167)
• Managing Phone Numbers and SMS Subscriptions (p. 172)
• Reserving a Dedicated Short Code for SMS Messaging (p. 177)
• Supported Regions and Countries (p. 178)
These preferences take effect for every SMS message that you send from your account, but you can
override some of them when you send an individual message. For more information, see Sending an SMS
Message (p. 157).
Topics
• Setting Preferences (Console) (p. 154)
• Setting Preferences (AWS SDKs) (p. 155)
For pricing information for promotional and transactional messages, see Global SMS Pricing.
6. For Account spend limit, type the maximum amount in USD that you want to spend on SMS
messages each calendar month. When Amazon SNS determines that sending an SMS message
would incur a cost that exceeds your spend limit for that month, Amazon SNS stops publishing SMS
messages within minutes.
Important
Because Amazon SNS is a distributed system, it stops sending SMS messages within a time
interval of minutes of the spend limit being exceeded. During that interval, if you continue
to send SMS messages, you may incur costs that exceed your limit.
By default, the spend limit is set to 1.00 USD. If you want to raise the limit, submit an SNS Text
Messaging case with AWS Support. For New limit value, enter your desired monthly spend limit.
In the Use Case Description field, explain that you are requesting an SMS monthly spend limit
increase. Typically, AWS Support processes your case within 2 business days. Depending on the
spend limit you request and the complexity of your case, AWS Support might require an additional 3
- 5 days to ensure that your request can be processed.
7. For IAM role for CloudWatch Logs access, create an IAM role that allows Amazon SNS to write logs
for SMS deliveries in CloudWatch Logs:
Support for sender IDs varies by country or region. For example, messages delivered to U.S. phone
numbers will not display the sender ID. For the countries and regions that support sender IDs, see
Supported Regions and Countries (p. 178).
If you do not specify a sender ID, the message will display a long code as the sender ID in supported
countries and regions. For countries and regions that require an alphabetic sender ID, the message
displays NOTICE as the sender ID.
You can override the this setting when you send a message.
10. For Reports storage, type the name of the Amazon S3 bucket to receive daily SMS usage reports
from Amazon SNS. Amazon SNS does not create daily usage reports unless you specify an Amazon
S3 bucket to receive them. For more information, see Viewing Daily SMS Usage Reports (p. 170).
11. Choose Update preferences.
The following examples show how to set SMS preferences by using the Amazon SNS clients that are
provided by the AWS SDKs.
The following example uses the setSMSAttributes method of the AmazonSNSClient class in the
AWS SDK for Java. This examples sets values for the different attribute names:
This example sets the value for the MonthlySpendLimit attribute to 1.00 USD. By default, this is
the maximum amount allowed by Amazon SNS. If you want to raise the limit, submit an SNS Text
Messaging case with AWS Support. For New limit value, enter your desired monthly spend limit. In
the Use Case Description field, explain that you are requesting an SMS monthly spend limit increase.
Typically, AWS Support processes your case within 2 business days. Depending on the spend limit
you request and the complexity of your case, AWS Support might require an additional 3 - 5 days to
ensure that your request can be processed.
To verify that the attributes were set correctly, the example prints the result of the
getSMSAttributes method. When you run this example, the attributes are displayed in the
console output window of your IDE:
My SMS attributes:
DeliveryStatusSuccessSamplingRate = 10
UsageReportS3Bucket = sns-sms-daily-usage
DefaultSMSType = Transactional
DeliveryStatusIAMRole = arn:aws:iam::123456789012:role/mySnsRole
MonthlySpendLimit = 1
DefaultSenderID = mySenderID
setRequest.Attributes["DefaultSenderID"] = "mySenderID";
setRequest.Attributes["MonthlySpendLimit"] = "1";
setRequest.Attributes["DeliveryStatusIAMRole"] = "arn:aws:iam::123456789012:role/
mySnsRole";
setRequest.Attributes["DeliveryStatusSuccessSamplingRate"] = "10";
setRequest.Attributes["DefaultSMSType"] = "Transactional";
setRequest.Attributes["UsageReportS3Bucket"] = "sns-sms-daily-usage";
SetSMSAttributesResponse setResponse = snsClient.SetSMSAttributes(setRequest);
GetSMSAttributesRequest getRequest = new GetSMSAttributesRequest();
GetSMSAttributesResponse getResponse = snsClient.GetSMSAttributes(getRequest);
Console.WriteLine("My SMS attributes:");
foreach (var item in getResponse.Attributes)
{
Console.WriteLine(item.Key + " = " + item.Value);
}
}
This example sets the value for the MonthlySpendLimit attribute to 1.00 USD. By default, this is
the maximum amount allowed by Amazon SNS. If you want to raise the limit, submit an SNS Text
Messaging case with AWS Support. For New limit value, enter your desired monthly spend limit. In
the Use Case Description field, explain that you are requesting an SMS monthly spend limit increase.
Typically, AWS Support processes your case within 2 business days. Depending on the spend limit
you request and the complexity of your case, AWS Support might require an additional 3 - 5 days to
ensure that your request can be processed.
To verify that the attributes were set correctly, the example prints the result of the
GetSMSAttributes method. When you run this example, the attributes are displayed in the
console output window of your IDE:
My SMS attributes:
DeliveryStatusSuccessSamplingRate = 10
UsageReportS3Bucket = sns-sms-daily-usage
DefaultSMSType = Transactional
DeliveryStatusIAMRole = arn:aws:iam::123456789012:role/mySnsRole
MonthlySpendLimit = 1
DefaultSenderID = mySenderID
Subscribing phone numbers to a topic can be still useful if you want to publish each message to multiple
phone numbers at once. For steps on how to publish an SMS message to a topic, see Sending an SMS
Message to Multiple Phone Numbers (p. 161).
When you send a message, you can control whether the message is optimized for cost or reliable
delivery, and you can specify a sender ID. If you send the message programmatically by using the
Amazon SNS API or AWS SDKs, you can specify a maximum price for the message delivery.
Each SMS message can contain up to 140 bytes, and the character limit depends on the encoding
scheme. For example, an SMS message can contain:
If you publish a message that exceeds the size limit, Amazon SNS sends it as multiple messages,
each fitting within the size limit. Messages are not cut off in the middle of a word but on whole-word
boundaries. The total size limit for a single SMS publish action is 1600 bytes.
When you send an SMS message, specify the phone number using the E.164 format. E.164 is a standard
for the phone number structure used for international telecommunication. Phone numbers that follow
this format can have a maximum of 15 digits, and they are prefixed with the plus character (+) and the
country code. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100.
Topics
• Sending a Message (Console) (p. 158)
• Sending a Message (AWS SDKs) (p. 159)
• Promotional – Noncritical messages, such as marketing messages. Amazon SNS optimizes the
message delivery to incur the lowest cost.
• Transactional – Critical messages that support customer transactions, such as one-time passcodes
for multi-factor authentication. Amazon SNS optimizes the message delivery to achieve the
highest reliability.
This message-level setting overrides your default message type, which you set on the Text
messaging preferences page.
For pricing information for promotional and transactional messages, see Global SMS Pricing.
6. For Number, type the phone number to which you want to send the message.
7. For Message, type the message to send.
8. (Optional) For Sender ID, type a custom ID that contains up to 11 alphanumeric characters,
including at least one letter and no spaces. The sender ID is displayed as the message sender on the
receiving device. For example, you can use your business brand to make the message source easier to
recognize.
Support for sender IDs varies by country and/or region. For example, messages delivered to U.S.
phone numbers will not display the sender ID. For the countries and regions that support sender IDs,
see Supported Regions and Countries (p. 178).
If you do not specify a sender ID, the message will display a long code as the sender ID in supported
countries or regions. For countries and regions that require an alphabetic sender ID, the message
displays NOTICE as the sender ID.
This message-level sender ID overrides your default sender ID, which you set on the Text messaging
preferences page.
9. Choose Send text message.
AWS.SNS.SMS.SenderID
A custom ID that contains up to 11 alphanumeric characters, including at least one letter and no
spaces. The sender ID is displayed as the message sender on the receiving device. For example, you
can use your business brand to make the message source easier to recognize.
Support for sender IDs varies by country and/or region. For example, messages delivered to U.S.
phone numbers will not display the sender ID. For the countries and regions that support sender IDs,
see Supported Regions and Countries (p. 178).
If you do not specify a sender ID, the message will display a long code as the sender ID in supported
countries and regions. For countries or regions that require an alphabetic sender ID, the message
displays NOTICE as the sender ID.
This message-level attribute overrides the account-level attribute DefaultSenderID, which you set
by using the SetSMSAttributes request.
AWS.SNS.SMS.MaxPrice
The maximum amount in USD that you are willing to spend to send the SMS message. Amazon
SNS will not send the message if it determines that doing so would incur a cost that exceeds the
maximum price.
This attribute has no effect if your month-to-date SMS costs have already exceeded the limit set for
the MonthlySpendLimit attribute, which you set by using the SetSMSAttributes request.
If you are sending the message to an Amazon SNS topic, the maximum price applies to each
message delivery to each phone number that is subscribed to the topic.
AWS.SNS.SMS.SMSType
This message-level attribute overrides the account-level attribute DefaultSMSType, which you set
by using the SetSMSAttributes request.
With the AWS SDK for Java, you set message attribute values by constructing a map that associates
the attribute keys with MessageAttributeValue objects. Each MessageAttributeValue object
is initialized with an attribute value, and each object declares the data type for the value. The
following example sets the sender ID to "mySenderID", maximum price to 0.50 USD, and SMS type to
promotional:
When you send an SMS message, you will apply your attributes to the PublishRequest object.
AWS SDK for .NET
With the AWS SDK for .NET. you set message attribute values by constructing a map that associates
the attribute keys with MessageAttributeValue objects. Each MessageAttributeValue object
is initialized with an attribute value, and each object declares the data type for the value. The
following example sets the sender ID to "mySenderID", maximum price to 0.50 USD, and SMS type to
promotional:
Sending a Message
The following examples show how to send a message by using the Amazon SNS clients that are provided
by the AWS SDKs.
The following example uses the publish method of the AmazonSNSClient class in the AWS SDK
for Java. This example sends a message directly to a phone number:
When you run this example, the message ID is displayed in the console output window of your IDE:
{MessageId: 9b888f80-15f7-5c30-81a2-c4511a3f5229}
When you run this example, the message ID is displayed in the console output window of your IDE:
9b888f80-15f7-5c30-81a2-c4511a3f5229
Topics
• Sending a Message to a Topic (Console) (p. 161)
• Sending a Message to a Topic (AWS SDKs) (p. 162)
Complete the following steps if you don't already have a topic to which you want to send SMS messages.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the console menu, set the region selector to a region that supports SMS messaging (p. 178).
3. In the navigation pane, choose Topics.
4. On the Topics page, choose Create new topic. The Create new topic window opens.
5. For Topic name, type a name.
6. (Optional) For Display name, type a custom prefix for your SMS messages. When you send a
message to the topic, Amazon SNS prepends the display name followed by a right angle bracket
(>) and a space. Display names are not case sensitive, and Amazon SNS converts display names to
uppercase characters. For example, if the display name of a topic is MyTopic and the message is
Hello World!, the message would appear as:
7. Choose Create topic. The topic name and Amazon Resource Name (ARN) are added to the table on
the Topics page.
Subscriptions enable you to send an SMS message to multiple recipients by publishing the message just
once to your topic.
You can repeat these steps to add more phone numbers, and you can add other types of
subscriptions, such as email.
When you publish a message to a topic, Amazon SNS attempts to deliver that message to every phone
number that is subscribed to the topic.
For information about the size limits for SMS messages, see Sending an SMS Message (p. 157).
If your topic has a display name, Amazon SNS adds it to the message, which increases the message
length. The display name length is the number of characters in the name plus two characters for the
right angle bracket (>) and space that Amazon SNS adds.
4. Choose Publish message. Amazon SNS sends the SMS message and displays a success message.
CreateTopic
Creates a topic to which you can subscribe phone numbers and then publish messages to all of those
phone numbers at once by publishing to the topic.
Subscribe
You can use the MessageAttributes parameter to set several attributes for the message (for
example, the maximum price). For more information, see Sending a Message (AWS SDKs) (p. 159).
Creating a Topic
The following examples show how to create a topic by using the Amazon SNS clients that are provided
by the AWS SDKs.
The following example uses the createTopic method of the AmazonSNSClient class in the AWS
SDK for Java:
The example uses the getCachedResponseMetadata method to get the request ID.
When you run this example, the following is displayed in the console output window of your IDE:
{TopicArn: arn:aws:sns:us-east-1:123456789012:mySNSTopic}
CreateTopicRequest - {AWS_REQUEST_ID=93f7fc90-f131-5ca3-ab18-b741fef918b5}
Console.WriteLine("CreateTopicRequest - " +
createTopicResponse.ResponseMetadata.RequestId);
return createTopicResponse.TopicArn;
}
When you run this example, the following is displayed in the console output window of your IDE:
{TopicArn: arn:aws:sns:us-east-1:123456789012:mySNSTopic}
CreateTopicRequest - 93f7fc90-f131-5ca3-ab18-b741fef918b5
The following example uses the subscribe method of the AmazonSNSClient class in the AWS
SDK for Java:
This example constructs the subscribeRequest object and passes it the following arguments:
• topicArn - The Amazon Resource Name (ARN) of the topic to which you are adding a
subscription.
• "sms" - The protocol option for an SMS subscription.
• endpoint - The phone number that you are subscribing to the topic.
The example uses the getCachedResponseMetadata method to get the request ID for the
subscribe request.
When you run this example, the ID of the subscribe request is displayed in the console window of
your IDE:
SubscribeRequest - {AWS_REQUEST_ID=f38fe925-8093-5bd4-9c19-a7c7625de38c}
This example constructs the SubscribeRequest object and passes it the following arguments:
• topicArn - The Amazon Resource Name (ARN) of the topic to which you are adding a
subscription.
• "sms" - The protocol option for an SMS subscription.
• endpoint - The phone number that you are subscribing to the topic.
When you run this example, the ID of the subscribe request is displayed in the console window of
your IDE:
SubscribeRequest - f38fe925-8093-5bd4-9c19-a7c7625de38c
With the AWS SDK for Java, you set message attribute values by constructing a map that associates
the attribute keys with MessageAttributeValue objects. Each MessageAttributeValue object
is initialized with an attribute value, and each object declares the data type for the value. The
following example sets the sender ID to "mySenderID", maximum price to 0.50 USD, and SMS type to
promotional:
.withDataType("String"));
For more information about message attributes, see Sending a Message (AWS SDKs) (p. 159)
When you send an SMS message, you will apply your attributes to the PublishRequest object.
AWS SDK for .NET
With the AWS SDK for .NET, you set message attribute values by adding attribute keys with
MessageAttributeValue objects to the MessageAttributes field of the PublishRequest object.
Each MessageAttributeValue object is initialized with an attribute value, and each object
declares the data type for the value. The following example sets the sender ID to "mySenderID",
maximum price to 0.50 USD, and SMS type to promotional:
For more information about message attributes, see Sending a Message (AWS SDKs) (p. 159)
When you send an SMS message, you will apply your attributes to the PublishRequest object.
The following example uses the publish method of the AmazonSNSClient class in the AWS SDK
for Java:
Amazon SNS will attempt to deliver that message to every phone number that is subscribed to the
topic.
This example constructs the publishRequest object while passing the topic Amazon Resource
Name (ARN) and the message as arguments. The publishResult object captures the message ID
returned by Amazon SNS.
When you run this example, the message ID is displayed in the console output window of your IDE:
{MessageId: 9b888f80-15f7-5c30-81a2-c4511a3f5229}
Amazon SNS will attempt to deliver that message to every phone number that is subscribed to the
topic.
This example constructs the publishRequest object and assigns the topic Amazon Resource
Name (ARN) and the message. The publishResponse object captures the message ID returned by
Amazon SNS.
When you run this example, the message ID is displayed in the console output window of your IDE:
9b888f80-15f7-5c30-81a2-c4511a3f5229
Topics
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the console menu, set the region selector to a region that supports SMS messaging (p. 178).
3. In the navigation pane, choose Text messaging (SMS).
4. On the Text messaging (SMS) page, in the Account stats section, view the charts for your
transactional and promotional SMS message deliveries. Each chart shows the following data for the
preceding 15 days:
On this page, you can also choose the Usage button to go to the Amazon S3 bucket where you store
your daily usage reports. For more information, see Viewing Daily SMS Usage Reports (p. 170).
Topics
• Viewing Amazon CloudWatch Metrics (p. 168)
• Viewing CloudWatch Logs (p. 168)
• Example Log for Successful SMS Delivery (p. 169)
• Example Log for Failed SMS Delivery (p. 169)
• SMS Delivery Failure Reasons (p. 170)
For information about monitoring CloudWatch metrics, setting CloudWatch alarms, and the types of
metrics available, see Monitoring Amazon SNS Topics Using CloudWatch (p. 186).
will write a log that includes the message price, the success or failure status, the reason for failure (if the
message failed), the message dwell time, and other information.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the console menu, set the region selector to a region that supports SMS messaging (p. 178).
3. In the navigation pane, choose Text messaging (SMS).
4. On the Text messaging (SMS) page, choose Manage text messaging preferences.
5. On the Text messaging preferences page, for IAM role for CloudWatch Logs access, create an IAM
role that allows Amazon SNS to write logs for SMS deliveries in CloudWatch Logs:
For information about the other options on the Text messaging preferences page, see Setting
Preferences (Console) (p. 154).
{
"notification": {
"messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf",
"timestamp": "2016-06-28 00:40:34.558"
},
"delivery": {
"phoneCarrier": "My Phone Carrier",
"mnc": 270,
"destination": "+1XXX5550100”,
"priceInUSD": 0.00645,
"smsType": "Transactional",
"mcc": 310,
"providerResponse": "Message has been accepted by phone carrier",
"dwellTimeMs": 599,
"dwellTimeMsUntilDeviceAck": 1344
},
"status": "SUCCESS"
}
{
"notification": {
"messageId": "1077257a-92f3-5ca3-bc97-6a915b310625",
"timestamp": "2016-06-28 00:40:34.559"
},
"delivery": {
"mnc": 0,
"destination": "+1XXX5550100”,
"priceInUSD": 0.00645,
"smsType": "Transactional",
"mcc": 0,
"providerResponse": "Unknown error attempting to reach phone",
"dwellTimeMs": 1420,
"dwellTimeMsUntilDeviceAck": 1692
},
"status": "FAILURE"
}
Topics
• Daily Usage Report Information (p. 170)
• Subscribing to Daily Usage Reports (p. 171)
• Message type
• Delivery status
• Message price (in USD)
• Part number (a message is split into multiple parts if it is too long for a single message)
• Total number of parts
1. Sign in to the AWS Management Console and open the Amazon S3 console at https://
console.aws.amazon.com/s3/.
2. Choose Create Bucket.
3. For Bucket Name, type a name, such as sns-sms-daily-usage. For information about
conventions and restrictions for bucket names, see Rules for Bucket Naming in the Amazon Simple
Storage Service Developer Guide.
4. Choose Create.
5. In the All Buckets table, select the bucket and choose Properties.
6. In the Permissions section, choose Add bucket policy.
7. In the Bucket Policy Editor window, provide a policy that allows the Amazon SNS service principal
to write to your bucket. For an example, see Example Bucket Policy (p. 171).
If you use the example policy, remember to replace my-s3-bucket with the name of your bucket.
8. Choose Save.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the navigation pane, choose Text messaging (SMS).
3. On the Text messaging (SMS) page, choose Manage text messaging preferences.
4. On the Text messaging preferences page, for Reports storage, type the name of the Amazon S3
bucket that will receive the daily SMS usage reports.
5. Choose Update preferences.
For information about the other options on the Text messaging preferences page, see Setting
Preferences (Console) (p. 154).
After you subscribe to daily usage reports, you can view the reports in the Amazon S3 console. You can
also go to the Text messaging (SMS) page in the Amazon SNS console and choose the Usage button.
The following policy allows the Amazon SNS service principal to perform the s3:PutObject and
s3:GetBucketLocation actions. You can use this example when you create an Amazon S3 bucket to
receive daily SMS usage reports from Amazon SNS.
"Version": "2012-10-17",
"Id": "sns-sms-daily-usage-policy",
"Statement": [
{
"Sid": "AllowPutObject",
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-s3-bucket/*"
},
{
"Sid": "AllowGetBucketLocation",
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "s3:GetBucketLocation",
"Resource": "arn:aws:s3:::my-s3-bucket"
}
]
}
After you subscribe to daily usage reports, each day, Amazon SNS puts a CSV file with usage data in the
following location:
<my-s3-bucket>/SMSUsageReports/<region>/YYYY/MM/DD/00x.csv.gz
Each file can contain up to 50,000 records. If the records for a day exceed this limit, Amazon SNS will add
multiple files.
PublishTimeUTC,MessageId,DestinationPhoneNumber,MessageType,DeliveryStatus,PriceInUSD,PartNumber,TotalP
2016-05-10T03:00:29.476Z,96a298ac-1458-4825-
a7eb-7330e0720b72,1XXX5550100,Promotional,Message has been accepted by phone
carrier,0.90084,1,1
2016-05-10T03:00:29.561Z,1e29d394-
d7f4-4dc9-996e-26412032c344,1XXX5550100,Promotional,Message has been accepted by phone
carrier,0.34322,1,1
2016-05-10T03:00:30.769Z,98ba941c-afc7-4c51-
ba2c-56c6570a6c08,1XXX5550100,Transactional,Message has been accepted by phone
carrier,0.27815,1,1
. . .
Topics
• Opting Out of Receiving SMS Messages (p. 173)
• Managing Phone Numbers and Subscriptions (Console) (p. 173)
• ARRET (French)
• CANCEL
• END
• OPT-OUT
• OPTOUT
• QUIT
• REMOVE
• STOP
• TD
• UNSUBSCRIBE
To opt out, the recipient must reply to the same long code or short code that Amazon SNS used to
deliver the message. After opting out, the recipient will no longer receive SMS messages delivered from
your AWS account unless you opt in the phone number.
If the phone number is subscribed to an Amazon SNS topic, opting out does not remove the subscription,
but SMS messages will fail to deliver to that subscription unless you opt in the phone number.
1. Sign in to the AWS Management Console and open the Amazon SNS console at https://
console.aws.amazon.com/sns/v2/home.
2. In the console menu, set the region selector to a region that supports SMS messaging (p. 178).
3. In the navigation pane, choose Text messaging (SMS).
4. On the Text messaging (SMS) page, choose View opted out phone numbers. The Opted out phone
numbers page displays the opted out phone numbers.
5. Select the check box for the phone number that you want to opt in, and choose Opt in. The phone
number is no longer opted out and will receive SMS messages that you send to it.
Deleting a Topic
Delete a topic when you no longer want to publish messages to its subscribed endpoints.
Or, you can use the Amazon SNS clients in the AWS SDKs, as shown by the following examples:
With the AWS SDK for Java, you can use the listPhoneNumbersOptedOut method of the
AmazonSNSClient class:
With the AWS SDK for .NET, you can use the ListPhoneNumbersOptedOut method of the
AmazonSimpleNotificationServiceClient class:
{
AmazonSimpleNotificationServiceClient snsClient = new
AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USWest2);
ListOptOut(snsClient);
}
Amazon SNS returns a paginated response, so this example repeats the request each time Amazon SNS
returns a next token. When you run this example, it displays a list of all opted out phone numbers in the
console output window of your IDE.
Or, you can use the Amazon SNS clients in the AWS SDKs, as shown by the following examples:
With the AWS SDK for Java, you can use the checkIfPhoneNumberIsOptedOut method of the
AmazonSNSClient class:
When you run this example, a true or false result is displayed in the console output window of your
IDE:
{IsOptedOut: false}
Using the AWS SDK for .NET, you can use the CheckIfPhoneNumberIsOptedOut method of the
AmazonSimpleNotificationServiceClient class:
When you run this example, a true or false result is displayed in the console output window of your
IDE:
false
Or, you can use the Amazon SNS clients in the AWS SDKs, as shown by the following examples:
With the AWS SDK for Java, you can use the optInPhoneNumber method of the
AmazonSNSClient class:
snsClient.optInPhoneNumber(new OptInPhoneNumberRequest().withPhoneNumber(phoneNumber));
With the AWS SDK for .NET, you can use the OptInPhoneNumber method of the
AmazonSimpleNotificationServiceClient class:
Or, you can use the Amazon SNS clients in the AWS SDKs, as shown by the following examples:
With the AWS SDK for Java, you can get your subscription ARNs by using the listSubscriptions
method of the AmazonSNSClient class:
You can delete a subscription by passing its ARN as a string argument to the unsubscribe method:
snsClient.unsubscribe(subscriptionArn);
With the AWS SDK for .NET, use code like the following:
Console.WriteLine(sub.SubscriptionArn);
// unsubscribe
snsClient.Unsubscribe(subscriptionArn);
Deleting a Topic
To delete a topic and all of its subscriptions, get the topic ARN by submitting a ListTopics request
with the Amazon SNS API, and then pass the ARN to the DeleteTopic request.
Or, you can use the Amazon SNS clients in the AWS SDKs, as shown by the following examples:
With the AWS SDK for Java, you can get your topic ARNs by using the listTopics method of the
AmazonSNSClient class:
You can delete a topic by passing its ARN as a string argument to the deleteTopic method:
snsClient.deleteTopic(topicArn);
Using the AWS SDK for .NET, use code like the following:
A short code is a 5 or 6 digit number that you can use to send SMS messages to certain destinations.
Short codes are often used for application-to-person (A2P) messaging, two-factor authentication
(2FA), and marketing. Unless you reserve a short code, Amazon SNS will assign a short code to your
messages. This short code is shared with other Amazon SNS users, and it varies based upon destination
and message type (transactional or promotional). By reserving a short code, you make it easier for your
audience to recognize that your organization is the source of your messages.
Your dedicated short code is available exclusively to you, so others are unable to message your audience
using the same short code. Consequently, your short code has some protection from malicious activity
that might threaten your brand reputation or prompt wireless carriers to block your messages.
Amazon SNS can use your short code to message telephone numbers in the United States. For other
destinations, Amazon SNS assigns a long code or alphanumeric code as required.
A dedicated short code supports a higher delivery rate, which enables you send up to 100 SMS messages
per second. After you reserve a short code, you can request to increase this limit by submitting an SNS
Limit Increase case.
A customer service associate will contact you for additional information about your use case, including
the customized messages your audience members will see when they reply to your short code with
HELP or STOP. AWS will work with wireless carriers on your behalf to provision your short code. It
typically takes 6 - 12 weeks for all carriers to approve your use case and provision the short code so that
you can send messages to the subscribers in their networks. AWS will notify you when the short code
provisioning is complete.
You can use Amazon SNS to send SMS messages to the following countries and regions:
Afghanistan AF
Albania AL Yes
Algeria DZ
Andorra AD Yes
Angola AO Yes
Anguilla AI Yes
Argentina AR
Armenia AM Yes
Aruba AW Yes
Australia AU Yes
Austria AT Yes
Azerbaijan AZ
Bahamas BS Yes
Bahrain BH Yes
Bangladesh BD
Barbados BB Yes
Belarus BY Yes
Belgium BE
Belize BZ Yes
Benin BJ Yes
Bermuda BM Yes
Bhutan BT Yes
Bolivia BO Yes
Botswana BW Yes
Brazil BR
Brunei BN Yes
Bulgaria BG Yes
Burundi BI Yes
Cambodia KH Yes
Cameroon CM Yes
Canada CA
Chad TD Yes
Chile CL
China CN
Colombia CO
Comoros KM Yes
Costa Rica CR
Croatia HR
Cyprus CY Yes
Denmark DK Yes
Djibouti DJ Yes
Dominica DM Yes
Dominican republic DO
East Timor TL
Ecuador EC
Egypt EG
El Salvador SV
Estonia EE Yes
Ethiopia ET
Fiji FJ Yes
Finland FI Yes
France FR Yes
French Guiana GF
Gabon GA Yes
Gambia GM Yes
Georgia GE Yes
Germany DE Yes
Ghana GH
Gibraltar GI Yes
Greece GR Yes
Greenland GL Yes
Grenada GD Yes
Guadeloupe GP Yes
Guam GU
Guatemala GT
Guinea GN Yes
Guinea-Bissau GW Yes
Guyana GY Yes
Haiti HT Yes
Honduras HN
Hungary HU
Iceland IS Yes
India IN
Indonesia ID
Iraq IQ
Ireland IE Yes
Israel IL Yes
Italy IT Yes
Ivory Coast CI
Jamaica JM Yes
Japan JP
Jordan JO Yes
Kazakhstan KZ
Kenya KE
Kiribati KI
Kuwait KW
Kyrgyzstan KG
Laos LA
Latvia LV Yes
Lebanon LB Yes
Lesotho LS Yes
Liberia LR Yes
Libya LY Yes
Liechtenstein LI Yes
Lithuania LT Yes
Luxembourg LU Yes
Macau MO Yes
Macedonia MK Yes
Madagascar MG Yes
Malawi MW Yes
Malaysia MY
Maldives MV Yes
Mali ML
Malta MT Yes
Martinique MQ Yes
Mauritania MR Yes
Mauritius MU Yes
Mexico MX
Moldova MD Yes
Monaco MC
Mongolia MN Yes
Montenegro ME Yes
Montserrat MS Yes
Morocco MA
Mozambique MZ
Myanmar MM
Namibia NA
Nepal NP
Netherlands NL Yes
New Zealand NZ
Nicaragua NI
Niger NE Yes
Nigeria NG Yes
Norway NO Yes
Oman OM
Pakistan PK
Palau PW
Panama PA
Paraguay PY Yes
Peru PE Yes
Philippines PH
Poland PL Yes
Portugal PT Yes
Puerto Rico PR
Qatar QA
Romania RO
Russia RU Yes
Rwanda RW Yes
Saint Lucia LC
Samoa WS Yes
Saudi Arabia SA
Senegal SN Yes
Serbia RS
Seychelles SC Yes
Singapore SG Yes
Slovakia SK Yes
Slovenia SI Yes
Somalia SO Yes
South Africa ZA
South Korea KR
Spain ES Yes
Sri Lanka LK
Suriname SR Yes
Swaziland SZ Yes
Sweden SE Yes
Switzerland CH Yes
Taiwan TW
Tajikistan TJ Yes
Tanzania TZ Yes
Thailand TH
Togo TG Yes
Tonga TO Yes
Tunisia TN
Turkey TR
Turkmenistan TM Yes
Uganda UG Yes
Ukraine UA Yes
United States US
Uruguay UY
Uzbekistan UZ Yes
Vanuatu VU Yes
Venezuela VE
Vietnam VN
Virgin Islands, US VI
Yemen YE Yes
Zambia ZM Yes
Zimbabwe ZW Yes
Topics
• Monitoring Amazon SNS Topics Using CloudWatch (p. 186)
• Logging Amazon Simple Notification Service API Calls Using AWS CloudTrail (p. 191)
The metrics you configure with CloudWatch for your Amazon SNS topics are automatically collected
and pushed to CloudWatch every five minutes. These metrics are gathered on all topics that meet the
CloudWatch guidelines for being active. A topic is considered active by CloudWatch for up to six hours
from the last activity (i.e., any API call) on the topic.
Note
There is no charge for the Amazon SNS metrics reported in CloudWatch; they are provided as
part of the Amazon SNS service.
1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose View Metrics.
3. From the Viewing drop-down menu select either SNS: Topic Metrics, SNS: Push Notifications by
Application, SNS: Push Notifications by Application and Platform, or SNS: Push Notifications by
Platform to show the available metrics.
4. Choose a specific item to see more detail, such as a graph of the data collected. For example, the
following graph of the selected metric, NumberOfMessagesPublished, shows the average number
of published Amazon SNS messages for a five-minute period throughout the time range of 6 hours.
• Call mon-get-stats. You can learn more about this and other metrics-related functions in the
Amazon CloudWatch User Guide.
• Call GetMetricStatistics. You can learn more about this and other metrics-related functions in
the Amazon CloudWatch API Reference.
1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose Alarms, and then choose the Create Alarm button. This launches the Create Alarm wizard.
3. Scroll through the Amazon SNS metrics to locate the metric you want to place an alarm on. Select
the metric to create an alarm on and choose Continue.
4. Fill in the Name, Description, Threshold, and Time values for the metric, and then choose Continue.
5. Choose Alarm as the alarm state. If you want CloudWatch to send you an email when the alarm
state is reached, either select a preexisting Amazon SNS topic or choose Create New Email Topic. If
you choose Create New Email Topic, you can set the name and email addresses for a new topic. This
list will be saved and appear in the drop-down box for future alarms. Choose Continue.
Note
If you use Create New Email Topic to create a new Amazon SNS topic, the email addresses
must be verified before they will receive notifications. Emails are sent only when the alarm
enters an alarm state. If this alarm state change happens before the email addresses are
verified, they will not receive a notification.
6. At this point, the Create Alarm wizard gives you a chance to review the alarm you’re about to create.
If you need to make any changes, you can use the Edit links on the right. Once you are satisfied,
choose Create Alarm.
For more information about using CloudWatch and alarms, see the CloudWatch Documentation.
Metric Description
Units: Count
Units: Count
Metric Description
You can control the number of retries for HTTP
endpoints. For more information, see Setting
Amazon SNS Delivery Retry Policies for HTTP/HTTPS
Endpoints (p. 63).
Units: Count
Units: Count
Units: Count
Units: Count
Units: Bytes
Metric Description
SMSMonthToDateSpentUSD The charges you have accrued since the start of the
current calendar month for sending SMS messages.
Units: USD
Units: Count
Dimension Description
Platform Filters on platform objects for the push notification services, such
as APNS and GCM.
To learn more about CloudTrail, including how to configure and enable it, see the AWS CloudTrail User
Guide.
For an ongoing record of events in your AWS account, including events for Amazon SNS, create a trail.
A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a
trail in the console, the trail applies to all AWS Regions. The trail logs events from all Regions in the
AWS partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can
configure other AWS services to further analyze and act upon the event data collected in CloudTrail logs.
For more information, see the following:
Amazon SNS supports logging the following actions as events in CloudTrail log files:
• AddPermission
• ConfirmSubscription
• CreatePlatformApplication
• CreatePlatformEndpoint
• CreateTopic
• DeleteEndpoint
• DeletePlatformApplication
• DeleteTopic
• GetEndpointAttributes
• GetPlatformApplicationAttributes
• GetSubscriptionAttributes
• GetTopicAttributes
• ListEndpointsByPlatformApplication
• ListPlatformApplications
• ListSubscriptions
• ListSubscriptionsByTopic
• ListTopics
• RemovePermission
• SetEndpointAttributes
• SetPlatformApplicationAttributes
• SetSubscriptionAttributes
• SetTopicAttributes
• Subscribe
• Unsubscribe
Note
When you are not logged in to Amazon Web Services (unauthenticated mode) and either
the ConfirmSubscription or Unsubscribe actions are invoked, then they will not be logged
to CloudTrail. Such as, when you choose the provided link in an email notification to
confirm a pending subscription to a topic, the ConfirmSubscription action is invoked in
unauthenticated mode. In this example, the ConfirmSubscription action would not be
logged to CloudTrail.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
• Whether the request was made with root or AWS Identity and Access Management (IAM) user
credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
The following example shows a CloudTrail log entry that demonstrates the ListTopics, CreateTopic,
and DeleteTopic actions.
{
"Records": [
{
"eventVersion": "1.02",
"userIdentity": {
"type":"IAMUser",
"userName":"Bob"
"principalId": "EX_PRINCIPAL_ID",
"arn": "arn:aws:iam::123456789012:user/Bob",
"accountId": "123456789012",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE"
},
"eventTime": "2014-09-30T00:00:00Z",
"eventSource": "sns.amazonaws.com",
"eventName": "ListTopics",
"awsRegion": "us-west-2",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-sdk-java/unknown-version",
"requestParameters": {
"nextToken": "ABCDEF1234567890EXAMPLE=="
},
"responseElements": null,
"requestID": "example1-b9bb-50fa-abdb-80f274981d60",
"eventID": "example0-09a3-47d6-a810-c5f9fd2534fe",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
},
{
"eventVersion": "1.02",
"userIdentity": {
"type":"IAMUser",
"userName":"Bob"
"principalId": "EX_PRINCIPAL_ID",
"arn": "arn:aws:iam::123456789012:user/Bob",
"accountId": "123456789012",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE"
},
"eventTime": "2014-09-30T00:00:00Z",
"eventSource": "sns.amazonaws.com",
"eventName": "CreateTopic",
"awsRegion": "us-west-2",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-sdk-java/unknown-version",
"requestParameters": {
"name": "hello"
},
"responseElements": {
"topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic"
},
"requestID": "example7-5cd3-5323-8a00-f1889011fee9",
"eventID": "examplec-4f2f-4625-8378-130ac89660b1",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
},
{
"eventVersion": "1.02",
"userIdentity": {
"type":"IAMUser",
"userName":"Bob"
"principalId": "EX_PRINCIPAL_ID",
"arn": "arn:aws:iam::123456789012:user/Bob",
"accountId": "123456789012",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE"
},
"eventTime": "2014-09-30T00:00:00Z",
"eventSource": "sns.amazonaws.com",
"eventName": "DeleteTopic",
"awsRegion": "us-west-2",
"sourceIPAddress": "127.0.0.1",
"userAgent": "aws-sdk-java/unknown-version",
"requestParameters": {
"topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic"
},
"responseElements": null,
"requestID": "example5-4faa-51d5-aab2-803a8294388d",
"eventID": "example8-6443-4b4d-abfd-1b867280d964",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
},
]
}
Topics
• Authentication and Access Control for Amazon SNS (p. 195)
• Publishing to an Amazon SNS Topic from Amazon Virtual Private Cloud (p. 216)
• Protecting Amazon SNS Data Using Server-Side Encryption (SSE) and AWS KMS (p. 227)
Amazon SNS supports other protocols beside email. You can use HTTP, HTTPS, and Amazon SQS queues.
You have detailed control over which endpoints a topic allows, who is able to publish to a topic, and
under what conditions. This appendix shows you how to control through the use of access control
policies.
The main portion of this section includes basic concepts you need to understand, how to write a policy,
and the logic Amazon Web Services (AWS) uses to evaluate policies and decide whether to give the
requester access to the resource. Although most of the information in this section is service-agnostic,
there are some Amazon SNS-specific details you need to know. For more information, see Special
Information for Amazon SNS Policies (p. 209).
This section describes basic concepts you need to understand to use the access policy language to
write policies. It also describes the general process for how access control works with the access policy
language, and how policies are evaluated.
• You want to grant another AWS account a particular type of topic action (e.g., Publish). For more
information, see Allowing AWS account Access to a Topic (p. 206).
• You want to limit subscriptions to your topic to only the HTTPS protocol. For more information, see
Limiting Subscriptions to HTTPS (p. 206).
• You want to allow Amazon SNS to publish messages to your Amazon SQS queue. For more
information, see Publishing to an Amazon SQS Queue (p. 207).
Key Concepts
The following sections describe the concepts you need to understand to use the access policy language.
They're presented in a logical order, with the first terms you need to know at the top of the list.
Permission
A permission is the concept of allowing or disallowing some kind of access to a particular resource.
Permissions essentially follow this form: "A is/isn't allowed to do B to C where D applies." For example,
Jane (A) has permission to publish (B) to TopicA (C) as long as she uses the HTTP protocol (D). Whenever
Jane publishes to TopicA, the service checks to see if she has permission and if the request satisfies the
conditions set forth in the permission.
Statement
A statement is the formal description of a single permission, written in the access policy language.
You always write a statement as part of a broader container document known as a policy (see the next
concept).
Policy
A policy is a document (written in the access policy language) that acts as a container for one or more
statements. For example, a policy could have two statements in it: one that states that Jane can
subscribe using the email protocol, and another that states that Bob cannot publish to TopicA. As shown
in the following figure, an equivalent scenario would be to have two policies, one that states that Jane
can subscribe using the email protocol, and another that states that Bob cannot publish to TopicA.
Issuer
The issuer is the person who writes a policy to grant permissions for a resource. The issuer (by definition)
is always the resource owner. AWS does not permit AWS service users to create policies for resources they
don't own. If John is the resource owner, AWS authenticates John's identity when he submits the policy
he's written to grant permissions for that resource.
Principal
The principal is the person or persons who receive the permission in the policy. The principal is A in
the statement "A has permission to do B to C where D applies." In a policy, you can set the principal to
"anyone" (i.e., you can specify a wildcard to represent all people). You might do this, for example, if you
don't want to restrict access based on the actual identity of the requester, but instead on some other
identifying characteristic such as the requester's IP address.
Action
The action is the activity the principal has permission to perform. The action is B in the statement "A has
permission to do B to C where D applies." Typically, the action is just the operation in the request to AWS.
For example, Jane sends a request to Amazon SNS with Action=Subscribe. You can specify one or
multiple actions in a policy.
Resource
The resource is the object the principal is requesting access to. The resource is C in the statement "A has
permission to do B to C where D applies."
• Date and time (e.g., the request must arrive before a specific day)
• IP address (e.g., the requester's IP address must be part of a particular CIDR range)
A key is the specific characteristic that is the basis for access restriction. For example, the date and time
of request.
You use both conditions and keys together to express the restriction. The easiest way to understand how
you actually implement a restriction is with an example: If you want to restrict access to before May
30, 2010, you use the condition called DateLessThan. You use the key called aws:CurrentTime and
set it to the value 2010-05-30T00:00:00Z. AWS defines the conditions and keys you can use. The
AWS service itself (e.g., Amazon SQS or Amazon SNS) might also define service-specific keys. For more
information, see Special Information for Amazon SNS Policies (p. 209).
Requester
The requester is the person who sends a request to an AWS service and asks for access to a particular
resource. The requester sends a request to AWS that essentially says: "Will you allow me to do B to C
where D applies?"
Evaluation
Evaluation is the process the AWS service uses to determine if an incoming request should be denied
or allowed based on the applicable policies. For information about the evaluation logic, see Evaluation
Logic (p. 201).
Effect
The effect is the result that you want a policy statement to return at evaluation time. You specify this
value when you write the statements in a policy, and the possible values are deny and allow.
For example, you could write a policy that has a statement that denies all requests that come from
Antarctica (effect=deny given that the request uses an IP address allocated to Antarctica). Alternately,
you could write a policy that has a statement that allows all requests that don't come from Antarctica
(effect=allow, given that the request doesn't come from Antarctica). Although the two statements sound
like they do the same thing, in the access policy language logic, they are different. For more information,
see Evaluation Logic (p. 201).
Although there are only two possible values you can specify for the effect (allow or deny), there can
be three different results at policy evaluation time: default deny, allow, or explicit deny. For more
information, see the following concepts and Evaluation Logic (p. 201).
Default Deny
A default deny is the default result from a policy in the absence of an allow or explicit deny.
Allow
An allow results from a statement that has effect=allow, assuming any stated conditions are met.
Example: Allow requests if they are received before 1:00 p.m. on April 30, 2010. An allow overrides all
default denies, but never an explicit deny.
Explicit Deny
An explicit deny results from a statement that has effect=deny, assuming any stated conditions are met.
Example: Deny all requests if they are from Antarctica. Any request that comes from Antarctica will
always be denied no matter what any other policies might allow.
Architectural Overview
The following figure and table describe the main components that interact to provide access control for
your resources.
2 Your resources (contained within the AWS service; e.g., Amazon SQS queues).
3 Your policies.
Typically you have one policy per resource, although you could have multiple. The AWS service
itself provides an API you use to upload and manage your policies.
This is the set of code within the AWS service that evaluates incoming requests against the
applicable policies and determines whether the requester is allowed access to the resource. For
information about how the service makes the decision, see Evaluation Logic (p. 201).
Process for Using Access Control with the Access Policy Language
For example, you write a policy to specify permissions for your Amazon SNS topics.
The AWS service itself provides an API you use to upload your policies. For example, you use
the Amazon SNS SetTopicAttributes action to upload a policy for a particular Amazon SNS
topic.
For example, a user sends a request to Amazon SNS to use one of your topics.
4 The AWS service determines which policies are applicable to the request.
For example, Amazon SNS looks at all the available Amazon SNS policies and determines which
ones are applicable (based on what the resource is, who the requester is, etc.).
For example, Amazon SNS evaluates the policies and determines if the requester is allowed to
use your topic or not. For information about the decision logic, see Evaluation Logic (p. 201).
6 The AWS service either denies the request or continues to process it.
For example, based on the policy evaluation result, the service either returns an "Access denied"
error to the requester or continues to process the request.
Related Topics
Evaluation Logic
The goal at evaluation time is to decide whether a given request should be allowed or denied. The
evaluation logic follows several basic rules:
• By default, all requests to use your resource coming from anyone but you are denied
• An allow overrides any default denies
• An explicit deny overrides any allows
• The order in which the policies are evaluated is not important
The following flow chart and discussion describe in more detail how the decision is made.
2 The enforcement code then evaluates all the policies that are applicable to the request (based
on the resource, principal, action, and conditions).
The order in which the enforcement code evaluates the policies is not important.
3 In all those policies, the enforcement code looks for an explicit deny instruction that would
apply to the request.
If it finds even one, the enforcement code returns a decision of "deny" and the process is
finished (this is an explicit deny; for more information, see Explicit Deny (p. 198)).
4 If no explicit deny is found, the enforcement code looks for any "allow" instructions that would
apply to the request.
If it finds even one, the enforcement code returns a decision of "allow" and the process is done
(the service continues to process the request).
5 If no allow is found, then the final decision is "deny" (because there was no explicit deny or
allow, this is considered a default deny (for more information, see Default Deny (p. 198)).
A policy also results in a default deny if a condition in a statement isn't met. If all conditions in the
statement are met, then the policy results in either an allow or an explicit deny, based on the value of
the Effect element in the policy. Policies don't specify what to do if a condition isn't met, and so the
default result in that case is a default deny.
For example, let's say you want to prevent requests coming in from Antarctica. You write a policy (called
Policy A1) that allows a request only if it doesn't come from Antarctica. The following diagram illustrates
the policy.
If someone sends a request from the U.S., the condition is met (the request is not from Antarctica).
Therefore, the request is allowed. But, if someone sends a request from Antarctica, the condition isn't
met, and the policy's result is therefore a default deny.
You could turn the result into an explicit deny by rewriting the policy (named Policy A2) as in the
following diagram. Here, the policy explicitly denies a request if it comes from Antarctica.
If someone sends a request from Antarctica, the condition is met, and the policy's result is therefore an
explicit deny.
The distinction between a default deny and an explicit deny is important because a default deny can be
overridden by an allow, but an explicit deny can't. For example, let's say there's another policy that allows
requests if they arrive on June 1, 2010. How does this policy affect the overall outcome when coupled
with the policy restricting access from Antarctica? We'll compare the overall outcome when coupling the
date-based policy (we'll call Policy B) with the preceding policies A1 and A2. Scenario 1 couples Policy A1
with Policy B, and Scenario 2 couples Policy A2 with Policy B. The following figure and discussion show
the results when a request comes in from Antarctica on June 1, 2010.
In Scenario 1, Policy A1 returns a default deny, as described earlier in this section. Policy B returns an
allow because the policy (by definition) allows requests that come in on June 1, 2010. The allow from
Policy B overrides the default deny from Policy A1, and the request is therefore allowed.
In Scenario 2, Policy A2 returns an explicit deny, as described earlier in this section. Again, Policy B
returns an allow. The explicit deny from Policy A2 overrides the allow from Policy B, and the request is
therefore denied.
This section gives a few examples of typical use cases for access control.
You can do this by using the Amazon SNS API action AddPermission. It takes a topic, a list of AWS
account IDs, a list of actions, and a label, and automatically creates a new statement in the topic's
access control policy. In this case, you don't write a policy yourself, because Amazon SNS automatically
generates the new policy statement for you. You can remove the policy statement later by calling
RemovePermission with its label.
{
"Version":"2012-10-17",
"Id":"AWSAccountTopicAccess",
"Statement" :[
{
"Sid":"give-1234-publish",
"Effect":"Allow",
"Principal" :{
"AWS":"111122223333"
},
"Action":["sns:Publish"],
"Resource":"arn:aws:sns:us-east-1:444455556666:MyTopic"
}
]
}
Once this statement is added, the user with AWS account 1111-2222-3333 can publish messages to the
topic.
You need to know how to write your own policy for the topic because the Amazon SNS AddPermission
action doesn't let you specify a protocol restriction when granting someone access to your topic. In this
case, you would write your own policy, and then use the SetTopicAttributes action to set the topic's
Policy attribute to your new policy.
The following example of a full policy gives the AWS account ID 1111-2222-3333 the ability to subscribe
to notifications from a topic.
{
"Version":"2012-10-17",
"Id":"SomePolicyId",
"Statement" :[
{
"Sid":"Statement1",
"Effect":"Allow",
"Principal" :{
"AWS":"111122223333"
},
"Action":["sns:Subscribe"],
"Resource": "arn:aws:sns:us-east-1:444455556666:MyTopic",
"Condition" :{
"StringEquals" :{
"sns:Protocol":"https"
}
}
}
]
}
Again, you'll need to know how to write your own policy because the Amazon SQS AddPermission
action doesn't create policy statements with conditions.
Note that the example presented below is an Amazon SQS policy (controlling access to your queue),
not an Amazon SNS policy (controlling access to your topic). The actions are Amazon SQS actions, and
the resource is the Amazon Resource Name (ARN) of the queue. You can determine the queue's ARN by
retrieving the queue's QueueArn attribute with the GetQueueAttributes action.
{
"Version":"2012-10-17",
"Id":"MyQueuePolicy",
"Statement" :[
{
"Sid":"Allow-SNS-SendMessage",
"Effect":"Allow",
"Principal" :"*",
"Action":["sqs:SendMessage"],
"Resource": "arn:aws:sqs:us-east-1:444455556666:MyQueue",
"Condition" :{
"ArnEquals" :{
"aws:SourceArn":"arn:aws:sns:us-east-1:444455556666:MyTopic"
}
}
}
]
}
This policy uses the aws:SourceArn condition to restrict access to the queue based on the source of the
message being sent to the queue. You can use this type of policy to allow Amazon SNS to send messages
to your queue only if the messages are coming from one of your own topics. In this case, you specify a
particular one of your topics, whose ARN is arn:aws:sns:us-east-1:444455556666:MyTopic.
The preceding policy is an example of the Amazon SQS policy you could write and add to a specific
queue. It would grant Amazon SNS and other AWS products access. Amazon SNS gives a default policy to
all newly created topics. The default policy gives all other AWS products access to your topic. This default
policy uses an aws:SourceArn condition to ensure that AWS products access your topic only on behalf
of AWS resources you own.
In the following example statement, the topic owner in these policies is 1111-2222-3333 and the AWS
resource owner is 4444-5555-6666. The example gives the AWS account ID 4444-5555-6666 the ability
to publish to My-Topic from any AWS resource owned by the account.
{
"Version":"2012-10-17",
"Id":"MyAWSPolicy",
"Statement" :[
{
"Sid":"My-statement-id",
"Effect":"Allow",
"Principal" :"*",
"Action":"sns:Publish",
"Resource":"arn:aws:sns:us-east-1:111122223333:My-Topic",
"Condition":{
"StringEquals":{
"AWS:SourceAccount":"444455556666"
}
}
}
]
}
This example assumes that you write your own policy and then use the SetTopicAttributes action to
set the topic's Policy attribute to your new policy.
The following example statement uses the ArnLike condition to make sure the ARN of the resource
making the request (the AWS:SourceARN) is an Amazon S3 ARN. You could use a similar condition to
restrict the permission to a set of Amazon S3 buckets, or even to a specific bucket. In this example, the
topic owner is 1111-2222-3333 and the Amazon S3 owner is 4444-5555-6666. The example states that
any Amazon S3 bucket owned by 4444-5555-6666 is allowed to publish to My-Topic.
{
"Version":"2012-10-17",
"Id":"MyAWSPolicy",
"Statement" :[
{
"Sid":"My-statement-id",
"Effect":"Allow",
"Principal" :"*",
"Action":"sns:Publish",
"Resource":"arn:aws:sns:us-east-1:111122223333:My-Topic",
"Condition":{
"StringEquals":{ "AWS:SourceAccount":"444455556666" } ,
"ArnLike": {"AWS:SourceArn": "arn:aws:s3:*:*:*" }
}
}
]
}
• Each policy must cover only a single topic (when writing a policy, don't include statements that cover
different topics)
• Each policy must have a unique policy Id
• Each statement in a policy must have a unique statement sid
Bytes 30 kb
Statements 100
Action Description
Action Description
• sns:Endpoint—The URL, email address, or ARN from a Subscribe request or a previously confirmed
subscription. Use with string conditions (see Example Policies for Amazon SNS (p. 214)) to restrict
access to specific endpoints (e.g., *@example.com).
• sns:Protocol—The protocol value from a Subscribe request or a previously confirmed subscription.
Use with string conditions (see Example Policies for Amazon SNS (p. 214)) to restrict publication to
specific delivery protocols (e.g., https).
Important
When you use a policy to control access by sns:Endpoint, be aware that DNS issues might affect
the endpoint's name resolution in the future.
Amazon Simple Notification Service integrates with AWS Identity and Access Management (IAM) so that
you can specify which Amazon SNS actions a user in your AWS account can perform with Amazon SNS
resources. You can specify a particular topic in the policy. For example, you could use variables when
creating an IAM policy that gives certain users in your organization permission to use the Publish action
with specific topics in your AWS account. For more information, see Policy Variables in the Using IAM
guide.
Important
Using Amazon SNS with IAM doesn't change how you use Amazon SNS. There are no changes to
Amazon SNS actions, and no new Amazon SNS actions related to users and access control.
For examples of policies that cover Amazon SNS actions and resources, see Example Policies for Amazon
SNS (p. 214).
You use an Amazon SNS policy with a particular topic to restrict who can work with that topic (e.g., who
can publish messages to it, who can subscribe to it, etc.). Amazon SNS policies can give access to other
AWS accounts, or to users within your own AWS account.
To give your users permissions for your Amazon SNS topics, you can use IAM policies, Amazon SNS
policies, or both. For the most part, you can achieve the same results with either. For example, the
following diagram shows an IAM policy and an Amazon SNS policy that are equivalent. The IAM policy
allows the Amazon SNS Subscribe action for the topic called topic_xyz in your AWS account. The IAM
policy is attached to the users Bob and Susan (which means that Bob and Susan have the permissions
stated in the policy). The Amazon SNS policy likewise gives Bob and Susan permission to access
Subscribe for topic_xyz.
Note
The preceding example shows simple policies with no conditions. You could specify a particular
condition in either policy and get the same result.
There is one difference between AWS IAM and Amazon SNS policies: The Amazon SNS policy system lets
you grant permission to other AWS accounts, whereas the IAM policy doesn't.
It's up to you how you use both of the systems together to manage your permissions, based on your
needs. The following examples show how the two policy systems work together.
Example 1
In this example, both an IAM policy and an Amazon SNS policy apply to Bob. The IAM policy gives him
permission for Subscribe on any of the AWS account's topics, whereas the Amazon SNS policy gives
him permission to use Publish on a specific topic (topic_xyz). The following diagram illustrates the
concept.
If Bob were to send a request to subscribe to any topic in the AWS account, the IAM policy would allow
the action. If Bob were to send a request to publish a message to topic_xyz, the Amazon SNS policy
would allow the action.
Example 2
In this example, we build on example 1 (where Bob has two policies that apply to him). Let's say that
Bob publishes messages to topic_xyz that he shouldn't have, so you want to entirely remove his ability
to publish to topics. The easiest thing to do is to add an IAM policy that denies him access to the
Publish action on all topics. This third policy overrides the Amazon SNS policy that originally gave
him permission to publish to topic_xyz, because an explicit deny always overrides an allow (for more
information about policy evaluation logic, see Evaluation Logic (p. 201)). The following diagram
illustrates the concept.
For examples of policies that cover Amazon SNS actions and resources, see Example Policies for
Amazon SNS (p. 214). For more information about writing Amazon SNS policies, go to the technical
documentation for Amazon SNS.
arn:aws:sns:region:account_ID:topic_name
Example
Following is an ARN for a topic named my_topic in the us-east-1 region, belonging to AWS account
123456789012.
arn:aws:sns:us-east-1:123456789012:my_topic
Example
If you had a topic named my_topic in each of the different Regions that Amazon SNS supports, you could
specify the topics with the following ARN.
arn:aws:sns:*:123456789012:my_topic
You can use * and ? wildcards in the topic name. For example, the following could refer to all the topics
created by Bob that he has prefixed with bob_.
arn:aws:sns:*:123456789012:bob_*
As a convenience to you, when you create a topic, Amazon SNS returns the topic's ARN in the response.
Each action you specify in a policy must be prefixed with the lowercase string sns:. To specify all
Amazon SNS actions, for example, you would use sns:*. For a list of the actions, go to the Amazon
Simple Notification Service API Reference.
For a list of context keys supported by each AWS service and a list of AWS-wide policy keys, see Actions,
Resources, and Condition Keys for AWS Services and AWS Global Condition Context Keys in the IAM User
Guide.
Amazon SNS uses the following service-specific keys. Use these keys in policies that restrict access to
Subscribe requests.
• sns:Endpoint—The URL, email address, or ARN from a Subscribe request or a previously confirmed
subscription. Use with string conditions (see Example Policies for Amazon SNS (p. 214)) to restrict
access to specific endpoints (e.g., *@yourcompany.com).
• sns:Protocol—The protocol value from a Subscribe request or a previously confirmed subscription.
Use with string conditions (see Example Policies for Amazon SNS (p. 214)) to restrict publication to
specific delivery protocols (e.g., https).
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":
["sns:CreateTopic","sns:ListTopics","sns:SetTopicAttributes","sns:DeleteTopic"],
"Resource":"*"
}
]
}
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":"sns:Publish",
"Resource":"arn:aws:sns:*:123456789012:topic_xyz"
}
]
}
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":["sns:Subscribe"],
"Resource":"*",
"Condition":{
"StringLike": {
"SNS:Endpoint":"*@yourcompany.com"
},
"StringEquals":{
"sns:Protocol":"email"
}
}
}
]
}
For this example, we create a group called WidgetCo that represents the partner company; we create a
user for the specific person (or application) at the partner company who needs access; and then we put
the user in the group.
We then attach a policy that gives the group Publish access on the specific topic named
WidgetPartnerTopic.
We also want to prevent the WidgetCo group from doing anything else with topics, so we add a
statement that denies permission to any Amazon SNS actions other than Publish on any topics other
than WidgetPartnerTopic. This is necessary only if there's a broad policy elsewhere in the system that
gives users wide access to Amazon SNS.
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":"sns:Publish",
"Resource":"arn:aws:sns:*:123456789012:WidgetPartnerTopic"
},
{
"Effect":"Deny",
"NotAction":"sns:Publish",
"NotResource":"arn:aws:sns:*:123456789012:WidgetPartnerTopic"
}
]
}
You can use these temporary security credentials in making requests to Amazon SNS. The API libraries
compute the necessary signature value using those credentials to authenticate your request. If you send
requests using expired credentials Amazon SNS denies the request.
For more information about IAM support for temporary security credentials, go to Granting Temporary
Access to Your AWS Resources in Using IAM.
http://sns.us-east-1.amazonaws.com/
?Name=My-Topic
&Action=CreateTopic
&Signature=gfzIF53exFVdpSNb8AiwN3Lv%2FNYXh6S%2Br3yySK70oX4%3D
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-03-31T12%3A00%3A00.000Z
&SecurityToken=SecurityTokenValue
&AWSAccessKeyId=Access Key ID provided by AWS Security Token Service
Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you
define. With a VPC, you have control over your network settings, such the IP address range, subnets,
route tables, and network gateways. To connect your VPC to Amazon SNS, you define an interface VPC
endpoint. This type of endpoint enables you to connect your VPC to AWS services. The endpoint provides
reliable, scalable connectivity to Amazon SNS without requiring an internet gateway, network address
translation (NAT) instance, or VPN connection. For more information, see Interface VPC Endpoints in the
Amazon VPC User Guide.
The information in this section is for users of Amazon VPC. For more information, and to get started with
creating a VPC, see Getting Started With Amazon VPC in the Amazon VPC User Guide.
Topics
• Tutorial: Publishing Amazon SNS Messages Privately from Amazon VPC (p. 217)
• Creating an Amazon VPC Endpoint for Amazon SNS (p. 226)
• Use an AWS CloudFormation template to automatically create a temporary private network in your
AWS account.
• Create a VPC endpoint that connects the VPC with Amazon SNS.
• Log in to an Amazon EC2 instance and publish a message privately to an Amazon SNS topic.
• Verify that the message was delivered successfully.
• Delete the resources that you created for this tutorial so that they don't remain in your AWS account.
The following diagram depicts the private network that you create in your AWS account as you complete
this tutorial:
This network consists of a VPC that contains an Amazon EC2 instance. The instance connects to Amazon
SNS through an interface VPC endpoint. This type of endpoint connects to services that are powered
by AWS PrivateLink. With this connection established, you can log in to the Amazon EC2 instance and
publish messages to the Amazon SNS topic, even though the network is disconnected from the public
internet. The topic fans out the messages that it receives to two subscribing AWS Lambda functions.
These functions log the messages that they receive in Amazon CloudWatch Logs.
Topics
• Before You Begin (p. 218)
• Step 1: Create an Amazon EC2 Key Pair (p. 218)
• Step 2: Create the AWS Resources (p. 219)
• Step 3: Confirm That Your Amazon EC2 Instance Lacks Internet Access (p. 220)
• Step 4: Create an Amazon VPC Endpoint for Amazon SNS (p. 221)
• Step 5: Publish a Message to Your Amazon SNS Topic (p. 223)
• Step 6: Verify Your Message Deliveries (p. 223)
• Step 7: Clean Up (p. 225)
• Related Resources (p. 226)
1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://
console.aws.amazon.com/ec2/.
2. In the navigation menu on the left, find the Network & Security section. Then, choose Key Pairs.
3. Choose Create Key Pair.
4. In the Create Key Pair window, for Key pair name, type VPCE-Tutorial-KeyPair. Then, choose
Create.
5. The private key file is automatically downloaded by your browser. Save it in a safe place. Amazon
EC2 gives the file an extension of .pem.
6. (Optional) If you're using an SSH client on a Mac or Linux computer to connect to your instance, use
the chmod command to set the permissions of your private key file so that only you can read it:
a. Open a terminal and navigate to the directory that contains the private key:
$ cd /filepath_to_private_key/
You provide the template to AWS CloudFormation, and AWS CloudFormation provisions the resources
that you need as a stack in your AWS account. A stack is a collection of resources that you manage as a
single unit. When you finish the tutorial, you can use AWS CloudFormation to delete all of the resources
in the stack at once. These resources don't remain in your AWS account, unless you want them to.
• A VPC and the associated networking resources, including a subnet, a security group, an internet
gateway, and a route table.
• An Amazon EC2 instance that's launched into the subnet in the VPC.
• An Amazon SNS topic.
• Two AWS Lambda functions. These functions receive messages that are published to the Amazon SNS
topic, and they log events in CloudWatch Logs.
• Amazon CloudWatch metrics and logs.
• An IAM role that allows the Amazon EC2 instance to use Amazon SNS, and an IAM role that allows the
Lambda functions to write to CloudWatch logs.
d. Choose Next.
6. On the Options page, keep all of the default values, and choose Next.
7. On the Review page, verify the stack details.
8. Under Capabilities, select the check box that acknowledges that AWS CloudFormation might create
IAM resources with custom names.
9. Choose Create.
The AWS CloudFormation console opens the Stacks page. The VPCE-Tutorial-Stack has a status of
CREATE_IN_PROGRESS. In a few minutes, after the creation process completes, the status changes
to CREATE_COMPLETE.
Tip
Choose the Refresh button to see the latest stack status.
At this point in the tutorial, the publish attempt fails. In a later step, after you create a VPC endpoint for
Amazon SNS, your publish attempt succeeds.
5. Open a terminal. From the directory that contains the key pair, connect to the instance by using
the following command, where instance-hostname is the hostname that you copied from the
Amazon EC2 console:
$ ping amazon.com
Because the connection attempt fails, you can cancel at any time (Ctrl + C on Windows or Command
+ C on macOS).
Because the publish attempt fails, you can cancel at any time.
Note that the instance still lacks access to other AWS services and endpoints on the internet.
The service names vary based on the chosen region. For example, if you chose US East (N. Virginia),
the service name is com.amazonaws.us-east-1.sns.
6. For VPC, choose the VPC that has the name VPCE-Tutorial-VPC.
7. For Subnets, select the subnet that has VPCE-Tutorial-Subnet in the subnet ID.
8. For Enable Private DNS Name, select Enable for this endpoint.
9. For Security group, choose Select security group, and select the one named VPCE-Tutorial-
SecurityGroup.
10. Choose Create endpoint. The Amazon VPC console confirms that a VPC endpoint was created.
The Amazon VPC console opens the Endpoints page. The new endpoint has a status of pending. In a
few minutes, after the creation process completes, the status changes to available.
To publish a message
1. If your terminal is no longer connected to your Amazon EC2 instance, connect again:
2. Run the same command that you did previously to publish a message to your Amazon SNS topic.
This time, the publish attempt succeeds, and Amazon SNS returns a message ID:
4. Check the Invocation count graph. This graph shows the number of times that the Lambda function
has been run.
The invocation count matches the number of times you published a message to the topic.
d. Choose Log Groups at the top of the console to return the Log Groups page. Then, repeat the
preceding steps for the /aws/lambda/VPCE-Tutorial-Lambda-2/ log group.
Congratulations! By adding an endpoint for Amazon SNS to a VPC, you were able to publish a message
to a topic from within the network that's managed by the VPC. The message was published privately
without being exposed to the public internet.
Step 7: Clean Up
Unless you want to retain the resources that you created for this tutorial, you can delete them now.
By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS
account.
First, delete your VPC endpoint by using the Amazon VPC console. Then, delete the other resources that
you created by deleting the stack in the AWS CloudFormation console. When you delete a stack, AWS
CloudFormation removes the stack's resources from your AWS account.
The endpoint status changes to deleting. When the deletion completes, the endpoint is removed
from the page.
The stack status changes to DELETE_IN_PROGRESS. When the deletion completes, the stack is
removed from the page.
Related Resources
If you want to dive more deeply into the concepts introduced in this tutorial, see the following resources.
• AWS Security Blog: Securing messages published to Amazon SNS with AWS PrivateLink
• What Is Amazon VPC?
• VPC Endpoints
• What Is Amazon EC2?
• AWS CloudFormation Concepts
Use the following information to create the endpoint and test the connection between your VPC and
Amazon SNS. Or, for a walkthrough that helps you start from scratch, see Tutorial: Publishing Amazon
SNS Messages Privately from Amazon VPC (p. 217).
For information on creating and configuring an endpoint using the Amazon VPC console or the AWS CLI,
see Creating an Interface Endpoint in the Amazon VPC User Guide.
Note
When you create an endpoint, specify Amazon SNS as the service that you want your VPC to
connect to. In the Amazon VPC console, service names vary based on the region. For example, if
you choose US East (N. Virginia), the service name is com.amazonaws.us-east-1.sns.
For information on creating and configuring an endpoint using AWS CloudFormation, see the
AWS::EC2::VPCEndpoint resource in the AWS CloudFormation User Guide.
1. Connect to an Amazon EC2 instance that resides in your VPC. For information about connecting,
see Connect to Your Linux Instance or Connecting to Your Windows Instance in the Amazon EC2
documentation.
For example, to connect to a Linux instance by using an SSH client, run the following command from
a terminal:
Where:
• ec2-key-pair.pem is the file that contains the key pair that Amazon EC2 provided when you created
the instance.
• instance-hostname is the public hostname of the instance. To get the hostname in the Amazon
EC2 console: Choose Instances, select your instance, and find the value for Public DNS (IPv4).
2. From your instance, use the Amazon SNS publish command with the AWS CLI. You can send a
simple message to a topic with the following command:
Where:
If the message is successfully received by Amazon SNS, the terminal prints a message ID, like the
following:
{
"MessageId": "6c96dfff-0fdf-5b37-88d7-8cba910a8b64"
}
For information about managing SSE using the AWS Management Console or the AWS SDK for Java
(by setting the KmsMasterKeyId attribute using the CreateTopic and SetTopicAttributes API
actions), see Enabling Server-Side Encryption (SSE) for an Amazon SNS Topic (p. 233).
SSE encrypts messages as soon as Amazon SNS receives them. The messages are stored in encrypted
form and Amazon SNS decrypts messages only when they are sent.
Important
All requests to topics with SSE enabled must use HTTPS and Signature Version 4.
For information about compatibility of other services with encrypted topics, see your service
documentation.
AWS KMS combines secure, highly available hardware and software to provide a key management
system scaled for the cloud. When you use Amazon SNS with AWS KMS, the data keys (p. 228) that
encrypt your message data are also encrypted and stored with the data they protect.
• You can create and manage customer master keys (CMKs) (p. 228) yourself.
• You can also use the AWS managed CMK for Amazon SNS, which is unique for each account and
region.
• The AWS KMS security standards can help you meet encryption-related compliance requirements.
For more information, see What is AWS Key Management Service? in the AWS Key Management Service
Developer Guide and the AWS Key Management Service Cryptographic Details whitepaper.
Topics
• Encryption Scope (p. 228)
• Key Terms (p. 228)
• Estimating AWS KMS Costs (p. 229)
• Configuring AWS KMS Permissions (p. 230)
• Errors (p. 232)
• Tutorial: Enabling Server-Side Encryption (SSE) for an Amazon SNS Topic (p. 233)
Encryption Scope
SSE encrypts the body of a message in an Amazon SNS topic.
Note
• A message is encrypted only if it is sent after the encryption of a topic is enabled. Amazon
SNS doesn't encrypt backlogged messages.
• Any encrypted message remains encrypted even if the encryption of its topic is disabled.
Key Terms
The following key terms can help you better understand the functionality of SSE. For detailed
descriptions, see the Amazon Simple Notification Service API Reference.
Data Key
The data encryption key (DEK) responsible for encrypting the contents of Amazon SNS messages.
For more information, see Data Keys in the AWS Key Management Service Developer Guide and
Envelope Encryption in the AWS Encryption SDK Developer Guide.
Customer Master Key ID
The alias, alias ARN, key ID, or key ARN of an AWS managed customer master key (CMK) or a custom
CMK—in your account or in another account. While the alias of the AWS managed CMK for Amazon
SNS is always alias/aws/sns, the alias of a custom CMK can, for example, be alias/MyAlias.
You can use these CMKs to protect the messages in Amazon SNS topics.
Note
Keep the following in mind:
• The first time you use the AWS Management Console to specify the AWS managed CMK
for Amazon SNS for a topic, AWS KMS creates the AWS managed CMK for Amazon SNS.
• Alternatively, the first time you use the Publish action on a topic with SSE enabled, AWS
KMS creates the AWS managed CMK for Amazon SNS.
You can create CMKs, define the policies that control how CMKs can be used, and audit CMK usage
using the Encryption Keys section of the AWS KMS console or using AWS KMS actions. For more
information about CMKs, see Customer Master Keys in the AWS Key Management Service Developer
Guide. For more examples of CMK identifiers, see KeyId in the AWS Key Management Service API
Reference.
Important
There are additional charges for using AWS KMS. For more information, see Estimating AWS
KMS Costs (p. 229) and AWS Key Management Service Pricing.
To calculate the number of API requests (R) per topic, use the following formula:
R = B / D * (2 * P)
D is the data key reuse period (in seconds—Amazon SNS reuses a data key for up to 5 minutes).
P is the number of publishing principals that send to the Amazon SNS topic.
The following are example calculations. For exact pricing information, see AWS Key Management Service
Pricing.
You must also ensure that the key policies of the customer master key (CMK) allow the necessary
permissions. To do this, name the principals that produce and consume encrypted messages in Amazon
SNS as users in the CMK key policy.
Alternatively, you can specify the required AWS KMS actions and CMK ARN in an IAM policy assigned
to the principals that publish and subscribe to receive encrypted messages in Amazon SNS. For more
information, see Managing Access to AWS KMS CMKs in the AWS Key Management Service Developer
Guide.
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": [
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": "arn:aws:kms:us-
east-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}, {
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": "arn:aws:sns:*:123456789012:MyTopic"
}]
}
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": "service.amazonaws.com"
},
"Action": [
"kms:GenerateDataKey*",
"kms:Decrypt"
],
"Resource": "*"
}]
}
Note
Some Amazon SNS event sources require you to provide an IAM role (rather than the service
principal) in the AWS KMS key policy:
Errors
When you work with Amazon SNS and AWS KMS, you might encounter errors. The following list
describes the errors and possible troubleshooting solutions.
KMSAccessDeniedException
The ciphertext references a key that doesn't exist or that you don't have access to.
The request was rejected because the specified CMK isn't enabled.
The request was rejected because the state of the specified resource isn't valid for this request.
For more information, see How Key State Affects Use of a Customer Master Key in the AWS Key
Management Service Developer Guide.
The request was rejected because the specified entity or resource can't be found.
The request was denied due to request throttling. For more information about throttling, see Limits
in the AWS Key Management Service Developer Guide.
In this tutorial you learn how to enable, disable, and configure SSE for an existing Amazon SNS topic
using the AWS Management Console or the AWS SDK for Java (by setting the KmsMasterKeyId
attribute using the CreateTopic and SetTopicAttributes API actions).
Topics
• AWS Management Console (p. 233)
• AWS SDK for Java (p. 234)
For each CMK type, the Description, Account, and Key ARN of the CMK are displayed.
Important
If you aren't the owner of the CMK, or if you log in with an account that doesn't have
the kms:ListAliases and kms:DescribeKey permissions, you won't be able to view
information about the CMK on the Amazon SNS console.
Ask the owner of the CMK to grant you these permissions. For more information,
see the AWS KMS API Permissions: Actions and Resources Reference in the AWS Key
Management Service Developer Guide.
• The AWS managed CMK for Amazon SNS (Default) aws/sns is selected by default.
Note
Keep the following in mind:
• The first time you use the AWS Management Console to specify the AWS managed
CMK for Amazon SNS for a topic, AWS KMS creates the AWS managed CMK for
Amazon SNS.
• Alternatively, the first time you use the Publish action on a topic with SSE
enabled, AWS KMS creates the AWS managed CMK for Amazon SNS.
• To use a custom CMK from your AWS account, select it from the list.
Note
For instructions on creating custom CMKs, see Creating Keys in the AWS Key
Management Service Developer Guide
• To use a custom CMK ARN from your AWS account or from another AWS account, select Enter
an existing CMK ARN from the list and type or copy the CMK.
c. Choose Enable server-side encryption.
API Version 2010-03-31
233
Amazon Simple Notification Service Developer Guide
Enabling SSE for a Topic
SSE is enabled for your topic. To check the encryption status of your topic, on the Topics page, choose
the ARN of the topic.
Before you can use SSE, you must configure AWS KMS key policies to allow encryption of topics
and encryption and decryption of messages. For more information, see Configuring AWS KMS
Permissions (p. 230)
1. Obtain the customer master key (CMK) ID. For more information, see Key Terms (p. 228).
Note
Keep the following in mind:
• The first time you use the AWS Management Console to specify the AWS managed CMK
for Amazon SNS for a topic, AWS KMS creates the AWS managed CMK for Amazon SNS.
• Alternatively, the first time you use the Publish action on a topic with SSE enabled, AWS
KMS creates the AWS managed CMK for Amazon SNS.
2. To enable server-side encryption, specify the CMK ID by setting the KmsMasterKeyId attribute
using the CreateTopic or SetTopicAttributes action.
The following code example enables SSE for an existing topic using the AWS managed CMK for
Amazon SNS:
// Enable server-side encryption by specifying the alias ARN of the AWS managed CMK for
Amazon SNS.
final String kmsMasterKeyAlias = "arn:aws:kms:us-east-2:123456789012:alias/aws/sns";
To disable server-side encryption for an existing topic, set the KmsMasterKeyId attribute to an
empty string using the SetTopicAttributes action.
Important
null isn't a valid value for KmsMasterKeyId.
The following code example creates a new topic with SSE using a custom CMK:
// Enable server-side encryption by specifying the alias ARN of the custom CMK.
final String kmsMasterKeyAlias = "arn:aws:kms:us-east-2:123456789012:alias/MyAlias";
attributes.put("KmsMasterKeyId", kmsMasterKeyAlias);
Document History
The following table describes the important changes to the documentation since the last release of the
Amazon SNS Developer Guide.
New Feature Server-side encryption (SSE) for Amazon SNS lets you November 15, 2018
protect the contents of messages in Amazon SNS topics
using keys managed in the AWS Key Management Service
(AWS KMS). For more information about server-side
encryption and how to get started using it, see Protecting
Amazon SNS Data Using Server-Side Encryption (SSE) and
AWS KMS (p. 227) and Enabling Server-Side Encryption
(SSE) for an Amazon SNS Topic (p. 233).
Guide Changes Corrected the example headers and requests in the October 8, 2018
Amazon SNS Message and JSON Formats (p. 35) section.
Guide Changes • Clarified the information in the following sections: October 5, 2018
• With an Amazon SQS Queue as a Subscriber (p. 44)
• Create a Topic (p. 5)
• Backoff Phase (p. 68)
• Corrected the example policies in the following
sections:
• Give Permission to the Topic to Send Messages to the
Queue (p. 46)
• Adding a Policy to an IAM User or Group (p. 47)
• Queue Owner Creates Subscription (p. 50)
Guide Changes Added the following statement to the Getting Started September 24, 2018
with Google Cloud Messaging for Android (p. 116)
section: On April 10, 2018, Google announced the
deprecation of its Google Cloud Messaging (GCM)
platform. Specifically, the GCM server and client APIs
are deprecated and will be removed on April 11, 2019.
For more information, see The End of Google Cloud
Messaging, and What it Means for Your Apps.
Guide Changes Made minor corrections throughout this guide. September 20, 2018
Guide Changes Updated all the links in the Platform Response September 19, 2018
Codes (p. 141) section.
Guide Changes • Corrected HTTP request examples to use September 17, 2018
application/json in the following sections:
• With an HTTP/S Endpoint as a Subscriber (p. 57)
• Make Sure Your Endpoint is Ready to Process Amazon
SNS Messages (p. 58)
• Clarified the explanation of the HTTP status codes in
the Setting Amazon SNS Delivery Retry Policies for
HTTP/HTTPS Endpoints (p. 63) section.
• Added information about new prerequisites for
creating a Baidu account to the Step 1: Create a Baidu
Account (p. 101) section.
• Made other minor corrections throughout this guide.
Guide Changes • Corrected the information in the following section: September 13, 2018
• Reserving a Dedicated Short Code for SMS
Messaging (p. 177)
• Clean Up (p. 8)
• Corrected the code example to include throw new
SecurityException("Signature verification
failed."); in the correct place in the
SecurityException {
String messagetype =
request.getHeader("x-amz-sns-message-type");
if (messagetype == null) {
return;
its contents
Amazon Simple Notification Service Developer Guide
Guide Changes • Corrected the information in the following section: September 12, 2018
• The Interplay of Explicit and Default Denials (p. 203)
• Configuring Amazon SNS with Lambda Endpoints
with the AWS Management Console (p. 43)
• With an HTTP/S Endpoint as a Subscriber (p. 57)
• Added instructions for setting the policy to the Queue
Owner Creates Subscription (p. 50) section.
• Fixed broken links in the following sections:
• Platform Response Codes (p. 141)
• Platform-Specific Key-Value Pairs (p. 138)
• With an HTTP/S Endpoint as a Subscriber (p. 57)
Guide Changes Corrected the information in the following sections: September 6, 2018
Guide Changes • Clarified the information in the Daily Usage Report September 5, 2018
Information (p. 170) section.
• Corrected the code example to include
.collect(Collectors.joining(",")); in the
Example: Filter Policy as a Java Collection (p. 33)
section, to prevent Attribute.List from
returning an incorrect policy format when
formatFilterPolicy() is called.
• Corrected the code example to include
encryptedVal.add(false); in the Applying
Message Attributes with the AWS SDKs (p. 20) section.
• Corrected the maximum push notification message
size to 4,096 bytes in the Using Message Attributes for
Structuring the Message (p. 115) section.
• Corrected the ISO code for Mongolia to MN in the
Supported Regions and Countries (p. 178) section.
• Made other minor corrections throughout this guide.
Guide Changes • Clarified that Amazon SNS isn't currently compatible September 4, 2018
with Amazon SQS queues in the With an Amazon SQS
Queue as a Subscriber (p. 44) section.
• Clarified that message attributes (p. 17) are sent only
when the message structure is String, not JSON.
• Updated the content in the Subscribe the Queue to the
Topic (p. 46) section.
• Made a minor correction in the Access CloudWatch
Metrics for Amazon SNS (p. 186) section.
• Replaced all instances of click with choose for a device-
agnostic user experience.
• Fixed broken links throughout this guide.
Guide Changes • Rewrote the Logging Amazon Simple Notification August 30, 2018
Service API Calls Using AWS CloudTrail (p. 191) and
Creating the Endpoint (p. 226) sections.
• Made a minor correction in the Step 2: Create the AWS
Resources (p. 219) section.
• Added the Applying a Filter Policy Using AWS
CloudFormation (p. 31) and Removing a Filter Policy
Using AWS CloudFormation (p. 32) sections.
Guide Changes Reconfigured and restructured parts of this guide. August 22, 2018
AWS SDK for .NET Code examples are provided on multiple pages that show August 7, 2018
examples you how to use Amazon SNS with the AWS SDK for .NET.
For more information, see Using the AWS SDK for .NET
with Amazon SNS (p. 10).
Tutorial for Follow a tutorial to learn how to set up a VPC and June 8, 2018
publishing from a publish private messages to Amazon SNS. See Tutorial:
VPC Publishing Amazon SNS Messages Privately from Amazon
VPC (p. 217).
CloudWatch Amazon SNS now sends metrics to Amazon CloudWatch May 30, 2018
metrics for filtered about messages that are filtered by subscription
messages filter policies. For more information, see Amazon SNS
Metrics (p. 188).
Publishing from a Publish to your Amazon SNS topics privately from April 10, 2018
VPC Amazon Virtual Private Cloud. See Publishing to
an Amazon SNS Topic from Amazon Virtual Private
Cloud (p. 216).
Removing filter Remove the filter policy that is assigned to a subscription April 10, 2018
policies to stop filtering messages. See Removing Subscription
Filter Policies (p. 31).
New operations for In addition to exact matching with string values, filter March 12, 2018
subscription filter policies support the following operations for matching
policies message attributes: anything-but matching, prefix
matching, exact numeric matching, and numeric range
matching. For more information, see Amazon SNS
Message Filtering (p. 24).
Subscription filter Subscribers can selectively receive messages published November 21, 2017
policies to Amazon SNS topics by applying filter policies to topic
subscriptions. For more information, see Amazon SNS
Message Filtering (p. 24).
Applying message Applying Message Attributes (p. 19) includes steps and November 21, 2017
attributes examples for applying message attributes by using the
Amazon SNS console, AWS CLI, and the AWS SDK for
Java.
CloudWatch metric Amazon SNS sends the SMSMonthToDateSpentUSD March 31, 2017
for SMS spend metric to CloudWatch. This metric shows the charges
you have accrued since the start of the current calendar
month for sending SMS messages. For more information,
see Amazon SNS Metrics (p. 188).
Dedicated short To send SMS messages using a persistent short code, you March 06, 2017
codes for SMS can reserve a dedicated short code that is assigned to
your account and available exclusively to you. For more
information, see Reserving a Dedicated Short Code for
SMS Messaging (p. 177).
Amazon SNS Amazon SNS now supports SMS messaging to more June 28, 2016
supports worldwide than 200 countries and regions. You can send a message
SMS directly to a phone number, or you can send a message
to multiple phone numbers at once by subscribing those
phone numbers to a topic and sending your message to
the topic. For more information, see Using Amazon SNS
for User Notifications with a Mobile Phone Number as a
Subscriber (Send SMS) (p. 153).
Platform endpoints Added a topic about how to create a platform endpoint September 23, 2015
and device tokens and manage device tokens for Amazon SNS mobile push
notification. For more information, see Create a Platform
Endpoint and Manage Device Tokens (p. 130).
Application event Added a topic about how to trigger notifications when September 23, 2015
notifications certain application events occur. For more information,
see Application Event Notifications (p. 142).
New support for Added new topics about sending push notification June 15, 2015
VoIP and Mac OS X messages to VoIP and Mac OS X apps using Apple Push
push notifications Notification Service. For more information, see Getting
Started with Apple Push Notification Service (p. 94).
Invoking AWS Added a topic on how to invoke Lambda functions using April 09, 2015
Lambda functions Amazon SNS notifications. For more information, see
With a Lambda Function as a Subscriber (p. 43).
Using Amazon SNS Added a topic on using Amazon SNS topic attributes April 09, 2015
topic attributes for for message delivery status. For more information, see
message delivery Amazon SNS Topic Attributes for Message Delivery
status Status (p. 14).
Support to log the Added a topic on using Amazon SNS application February 05, 2015
delivery status of attributes for message delivery status. For more
push notification information, see Using Amazon SNS Application
messages Attributes for Message Delivery Status (p. 139).
Support for AWS Added a topic on logging Amazon SNS API calls by October 09, 2014
CloudTrail with using CloudTrail. For more information, see Logging
Amazon Simple Amazon Simple Notification Service API Calls Using AWS
Notification Service CloudTrail (p. 191).
Amazon SNS mobile Added a topic about the high-level steps you must October 09, 2014
push high-level perform to use Amazon SNS mobile push. This
steps information should help you gain a better understanding
of the steps involved when using the Amazon SNS mobile
push APIs. For more information, see Amazon SNS Mobile
Push High‐Level Steps (p. 89).
Support for Updated a topic on how to send authenticated messages August 19, 2014
authenticated with MPNS. For more information, see Getting Started
messages with with MPNS (p. 120).
Microsoft Push
Notification Service
for Windows Phone
Support for setting Added a topic on how to specify expiration metadata July 10, 2014
a Time To Live for a mobile push notification message. For more
(TTL) message information, see Using the Amazon SNS Time
attribute for mobile To Live (TTL) Message Attribute for Mobile Push
push notification Notifications (p. 144).
messages
Support for Baidu Added topics on how to use Baidu, MPNS, and WNS, June 12, 2014
Cloud Push, with Amazon SNS to send push notification messages to
Microsoft Push mobile devices. For more information, see Getting Started
Notification Service with Baidu Cloud Push (p. 100), Getting Started with
for Windows Phone, MPNS (p. 120), and Getting Started with WNS (p. 123).
and Windows
Push Notification
Services
Message attributes Message attributes allow you to provide structured June 12, 2014
metadata items about a message. For more information,
see Amazon SNS Message Attributes (p. 17).
Amazon SNS Added a section about using the AWS SDK for Java with April 23, 2014
samples in Java Amazon SNS. Examples in this section show how to create
a new Amazon SNS client, set the Amazon SNS endpoint
to use, and create a new topic. In addition, examples are
provided on how to subscribe to, publish to, and delete a
topic. For more information, see Using the AWS SDK for
Java with Amazon SNS (p. 9).
Mobile push Added a topic about how to create and send custom December 17, 2013
notifications platform-specific payloads in messages to mobile devices.
For more information, see Send Custom Platform-Specific
Payloads in Messages to Mobile Devices (p. 137).
Mobile push Added support to send notification messages directly August 13, 2013
notifications to apps on mobile devices. For more information, see
Using Amazon SNS for User Notifications with a Mobile
Application as a Subscriber (Mobile Push) (p. 87).
Initial Release This is the first release of the Amazon SNS Developer May 1, 2013
Guide.
AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.