利用aws-sdk gem的方式处理SNS的认证

注意:下面列举的代码都是 aws-sdk 2.x的基础上的。

1 在https://console.aws.amazon.com/sns/v2/home创建topic

2 为了可以在action中获取到aws发送的参数,需要追加一个文件

config/initializers/sns_content_type.rb, 其中代码如下:

class SnsContentType
  def initialize(app, message = "Response Time")
    @app = app
  end

  def call(env)
    env['CONTENT_TYPE'] = 'application/json' if env['HTTP_X_AMZ_SNS_MESSAGE_TYPE'].present?
    @app.call(env)
  end
end

然后再config/application.rb中插入一个middleware,代码如下:

config.middleware.insert_before ActionDispatch::ParamsParser, "SnsContentType"

然后controller的action中的认证代码如下:

if params['Type'] == 'SubscriptionConfirmation'   
  message_body = params["bounce"]        
  # returns true/false
  verifier = Aws::SNS::MessageVerifier.new
  verifier.authenticate! message_body.to_json
else

end

3 创建subscription, 创建好了之后,aws 会发送一个确认的请求,而上面的action中会接收到,接收到的参数如下:

Parameters: {"Type"=>"SubscriptionConfirmation", "MessageId"=>"1bc562c5-4edc",
"Token"=>"[FILTERED]",
"TopicArn"=>"arn:aws:sns:us-east-1:1122:bounce-complaint-topic",
"Message"=>"You have chosen to subscribe to the topic arn:aws:sns:us-east-1:1122:bounce-complaint-topic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL"=>"https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:test:bounce-complaint-topic&Token=test",
"Timestamp"=>"2017-07-18T03:15:33.290Z",
"SignatureVersion"=>"1",
"Signature"=>"OR1ex/EINY6Yox7bpypOWM04knDBVzu7HiNZRTvoXtAhqmluJF/PcyWZ0NsKvME7Gd0dDzeG/IHbMhT0Gw4uFYZElbqM1b08U8O6V87kyjPE+Bql7RIG+nW6zBtu8mgua18cNf8hpWr7WSCyN0+e4WQGPpYAiUfWtyN1vKKmkY1xysUG7NoMn4NokX5zkS+PLVIY35/iKzUNv8riJP6/77UkCT0a8TqHIAkO3Lb+zhlqIdW7K2R0KYrp7TRe8PfFvMIziw7kdVm3r13jT6H4HI+pS0SMYkP1wn+LnvpS+FdlQYkmrlO5FMwl0Un/Sa9B2ywIAg38kcJ0peNpS9BmXw==", "SigningCertURL"=>"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-test",
"bounce"=>{"Type"=>"SubscriptionConfirmation",
"MessageId"=>"1bc562c5-4edc-451e-83b7-test",
"Token"=>"[FILTERED]",
"TopicArn"=>"arn:aws:sns:us-east-1:test:bounce-complaint-topic",
"Message"=>"You have chosen to subscribe to the topic arn:aws:sns:us-east-1:test:bounce-complaint-topic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL"=>"https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:test:bounce-complaint-topic&Token=test",
"Timestamp"=>"2017-07-18T03:15:33.290Z",
"SignatureVersion"=>"1",
"Signature"=>"OR1ex/test/PcyWZ0NsKvME7Gd0dDzeG/test+Bql7RIG+nW6zBtu8mgua18cNf8hpWr7WSCyN0+e4WQGPpYAiUfWtyN1vKKmkY1xysUG7NoMn4NokX5zkS+PLVIY35/iKzUNv8riJP6/77UkCT0a8TqHIAkO3Lb+zhlqIdW7K2R0KYrp7TRe8PfFvMIziw7kdVm3r13jT6H4HI+pS0SMYkP1wn+LnvpS+FdlQYkmrlO5FMwl0Un/Sa9B2ywIAg38kcJ0peNpS9BmXw==", "SigningCertURL"=>"https://sns.us-east-1.amazonaws.com/SimpleNotificationService-tst.pem"}}

执行完action之后,aws console中的状态还是pending confirmation。 后面还需要在浏览器中 访问上面的SubscribeURL 。

你可能感兴趣的:(利用aws-sdk gem的方式处理SNS的认证)