aws-sdk gemによるSNSの認証処理

3526 ワード

注意:以下に挙げるコードはaws-sdk 2.xに基づいています.
1https://console.aws.amazon.com/sns/v2/hometopicの作成
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.To 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.To 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にアクセスする必要があります.