2

尝试开始使用 Amazon SNS。API 是非常简单的 REST。我似乎被电话的签名部分挂断了。API 示例是:

http://sns.us-east-1.amazonaws.com/
?Subject=My%20first%20message
&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A698519295917%3AMy-Topic
&Message=Hello%20world%21
&Action=Publish
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-03-31T12%3A00%3A00.000Z
&AWSAccessKeyId=AKIAJHS4T6XPF7XIURNA
&Signature=9GZysQ4Jpnz%2BHklqM7VFTvEcjR2LIUtn6jW47054xxE%3D

我一直在关注API docs for signatures,所以我正在尝试:

from time import strftime,gmtime,time
import urllib2
import hmac
import hashlib
import base64
import string

def publichSNSMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = 'sns.us-east-1.amazonaws.com'
  values = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }

  amazquote=lambda v: urllib2.quote(v).replace('%7E','~')
  cannqs=string.join(["%s=%s"%(amazquote(key),amazquote(values[key])) for key in sorted(values.keys(),key=str.lower)],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')

  sig=base64.encodestring(hmac.new(privatekey,string_to_sign,hashlib.sha1).digest())
  querystring = "%s&Signature=%s"%(cannqs,amazquote(sig))
  url="http://%s/?%s"%(amzsnshost,querystring)

  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())

回来:

<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"> 
  <Error> 
    <Type>Sender</Type> 
    <Code>SignatureDoesNotMatch</Code> 
    <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> 
  </Error> 
  <RequestId>8d6e5a41-dafb-11df-ac33-f981dc4e6c50</RequestId> 
</ErrorResponse> 

有任何想法吗?

4

3 回答 3

3

哦,这很简单!

查询字符串中的键应该按字节顺序排序,而不是不区分大小写的排序(用于版本 1 签名)。

gist上提供了稍微更新的(现在是正确的)代码。

于 2010-10-18T22:10:20.990 回答
1

我发现这个例子非常有用,所以我用 C# 重写了它。由于 AWS 没有用于 SNS 的 WP7 库,也许这会对某人有所帮助:https ://gist.github.com/2705156

于 2012-05-15T21:18:32.110 回答
1

我建议您将 boto3 用于 SNS。该文档可以在http://boto3.readthedocs.io/en/latest/reference/services/sns.html找到。以下代码片段可用于以 JSON 格式获取签名。

import boto3
from django.views.decorators.csrf import csrf_exempt
topic_arn = <your topic>
client = boto3.client('sns',region_name="us-west-2")

#Call this to publish
def sns_publish(arg1,arg2):
    response = client.publish(
                        TopicArn=topic_arn,
                        Message=arg2,
                        Subject=arg2
                    )

#Function to subscribe to topic
@csrf_exempt
def sns_parse(request):
    print request.body.decode('utf-8')
    if request.method == "POST":
        response = json.loads(request.body.decode('utf-8'))
        type = response.get('Type')
        if type == 'Subscription':
            print(type)
            return("Subscription URL: "+<Url obtained>)
        elif type == 'Notification':
            return HttpResponse(type.get('Signature'))
    else:
        return HttpResponse('Not a POST object')

虽然这只是一个模板代码,但是是的,boto3 确实很有帮助。

于 2016-12-09T20:05:27.233 回答