如何确认来自amazon SNS的订阅请求HTTP

时间:2014-04-01 03:12:47

标签: amazon-web-services amazon-sns

我一直在网上搜索,没有一个明确的答案来确认亚马逊SNS的订阅请求。我已经将订阅从亚马逊控制台发送到我的网站,但下一步是什么?我使用amazon EC2作为我的PHP服务器。

5 个答案:

答案 0 :(得分:16)

在通过AWS管理控制台配置HTTP / HTTPS端点订阅之前,您需要确保PHP网站的HTTP或HTTPS端点能够处理Amazon SNS生成的HTTP POST请求。有几种类型的SNS消息: SubscriptionConfirmation ,Notification和UnsubscribeConfirmation。您的PHP代码需要从请求中获取标题 x-amz-sns-message-type ,并根据消息类型对其进行处理。对于SubscriptionConfirmation消息,您的PHP应用程序需要处理POST消息正文,这是一个JSON文档。为了订阅主题,您的PHP代码需要访问" SubscriberURL"在JSON正文中指定。 (可选)您应该在订阅主题之前验证签名以确保消息的真实性。

您可以在AWS文档中找到更多详细信息:http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html

答案 1 :(得分:3)

这是一个确认SNS订阅的快速应用程序(Node.js):

const express = require('express')
const request = require('request')
// parse urlencoded request bodies into req.body
const bodyParser = require('body-parser')
const app = express()
const port = 8080

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.post('/', (req, res) => {
  let body = ''

  req.on('data', (chunk) => {
    body += chunk.toString()
  })

  req.on('end', () => {
    let payload = JSON.parse(body)

    if (payload.Type === 'SubscriptionConfirmation') {
      const promise = new Promise((resolve, reject) => {
        const url = payload.SubscribeURL

        request(url, (error, response) => {
          if (!error && response.statusCode == 200) {
            console.log('Yess! We have accepted the confirmation from AWS')
            return resolve()
          } else {
            return reject()
          }
        })
      })

      promise.then(() => {
        res.end("ok")
      })
    }
  })
})

app.listen(port, () => console.log('Example app listening on port ' + port + '!'))

要使用它,需要安装必需的软件包:

yarn add express request body-parser

确认订阅后,AWS将向服务器发送一个具有以下内容的POST请求:

{
  "Type": "SubscriptionConfirmation",
  "MessageId": "XXXXXXXX-1ee3-4de3-9c69-XXXXXXXXXXXX",
  "Token": "SECRET_TOKEN",
  "TopicArn": "arn:aws:sns:us-west-2:XXXXXXXXXXXX:ses-test",
  "Message": "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:XXXXXXXXXXXX:ses-test. To 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:XXXXXXXXXXXX:ses-test&Token=SECRET_TOKEN",
  "Timestamp": "2018-11-21T19:48:08.170Z",
  "SignatureVersion": "1",
  "Signature": "SECRET",
  "SigningCertURL": "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.pem"
}

有效负载包含服务器请求的SubscribeURL

答案 2 :(得分:2)

带注释的Spring Cloud SNS订阅

spring cloud AWS支持自动确认订阅者,您只需要将此注释" @ NotificationSubscriptionMapping"

@Controller
@RequestMapping("/topicName")
public class NotificationTestController {

    @NotificationSubscriptionMapping
    public void handleSubscriptionMessage(NotificationStatus status) throws IOException {
        //We subscribe to start receive the message
        status.confirmSubscription();
    }

    @NotificationMessageMapping
    public void handleNotificationMessage(@NotificationSubject String subject, @NotificationMessage String message) {
        // ...
    }

    @NotificationUnsubscribeConfirmationMapping
    public void handleUnsubscribeMessage(NotificationStatus status) {
        //e.g. the client has been unsubscribed and we want to "re-subscribe"
        status.confirmSubscription();
    }
}

http://cloud.spring.io/spring-cloud-aws/spring-cloud-aws.html#_sns_support

答案 3 :(得分:2)

您指定的终点将从AWS SNS端点验证服务获取数据,相同的终点将用于验证终点并从aws获取通知,

只需将AWS SNS发送的输入转储到一个文本文件中,如

$json_write_to_text = json_decode(file_get_contents("php://input"));

您将找到AWS SNS发送的所有数据,但只需查找SubscriptionUrl(将特定于具有有效令牌的端点),在浏览器中打开您将具有SubscriptionConfirmation状态。那是

享受。

答案 4 :(得分:1)

我使用NodeJS后端解决了这个问题。假设你在HapiJS中有这样的API(那么你可以拥有另一种技术并不重要)

{
    method: 'POST',
    path: '/hello',
    handler: ( request, reply ) => {

        reply( Hello.print(request.payload) );
    },
    config: {
        tags: ['api']
    }
}

将您收到的有效负载传递给您的业务逻辑。

在业务逻辑流程中,它就像这样

    'use strict';
    const request = require('request');

    exports.print = (payload) => {

    payload = JSON.parse(payload);
    if(payload.Type === 'SubscriptionConfirmation'){

        return new Promise((resolve, reject) => {
            const url = payload.SubscribeURL;
            request(url, (error, response) => {

                if (!error && response.statusCode == 200) {
                    console.log('Yess! We have accepted the confirmation from AWS');
                    return resolve();
                }
                else 
                    return reject();
            });
        });
    }

我正在使用NPM的请求模块自动接受此类请求。

另一种方法是打印payload的内容,然后点击payload.SubscribeURL中给出的网址。

AWS接受后,您可以在订阅页面上查看确认,其中Subscription ARN将从Pending Confirmation更改为具有您的主题名称的复杂名称兼SHA。