Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example SNS subscription confirmation using AWS .NET SDK

I am trying to figure out how to use the AWS .NET SDK to confirm a subscription to a SNS Topic.

The subscription is via HTTP

The endpoint will be in a .net mvc website.

I can't find any .net examples anywhere?

A working example would be fantastic.

I'm trying something like this

 Dim snsclient As New Amazon.SimpleNotificationService.AmazonSimpleNotificationServiceClient(ConfigurationSettings.AppSettings("AWSAccessKey"), ConfigurationSettings.AppSettings("AWSSecretKey"))

    Dim TopicArn As String = "arn:aws:sns:us-east-1:991924819628:post-delivery"


    If Request.Headers("x-amz-sns-message-type") = "SubscriptionConfirmation" Then

        Request.InputStream.Seek(0, 0)
        Dim reader As New System.IO.StreamReader(Request.InputStream)
        Dim inputString As String = reader.ReadToEnd()

        Dim jsSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
        Dim message As Dictionary(Of String, String) = jsSerializer.Deserialize(Of Dictionary(Of String, String))(inputString)

        snsclient.ConfirmSubscription(New Amazon.SimpleNotificationService.Model.ConfirmSubscriptionRequest With {.AuthenticateOnUnsubscribe = False, .Token = message("Token"), .TopicArn = TopicArn})


   End If
like image 647
Scott Anderson Avatar asked Feb 26 '13 01:02

Scott Anderson


2 Answers

Here is a working example using MVC WebApi 2 and the latest AWS .NET SDK.

var jsonData = Request.Content.ReadAsStringAsync().Result;
var snsMessage = Amazon.SimpleNotificationService.Util.Message.ParseMessage(jsonData);

//verify the signaure using AWS method
if(!snsMessage.IsMessageSignatureValid())
    throw new Exception("Invalid signature");

if(snsMessage.Type == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_SUBSCRIPTION_CONFIRMATION)
{
    var subscribeUrl = snsMessage.SubscribeURL;
    var webClient = new WebClient();
    webClient.DownloadString(subscribeUrl);
    return "Successfully subscribed to: " + subscribeUrl;
}
like image 114
cmilam Avatar answered Sep 22 '22 18:09

cmilam


Building on @Craig's answer above (which helped me greatly), the below is an ASP.NET MVC WebAPI controller for consuming and auto-subscribing to SNS topics. #WebHooksFTW

using RestSharp;
using System;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Description;

namespace sb.web.Controllers.api {
  [System.Web.Mvc.HandleError]
  [AllowAnonymous]
  [ApiExplorerSettings(IgnoreApi = true)]
  public class SnsController : ApiController {
    private static string className = MethodBase.GetCurrentMethod().DeclaringType.Name;

    [HttpPost]
    public HttpResponseMessage Post(string id = "") {
      try {
        var jsonData = Request.Content.ReadAsStringAsync().Result;
        var sm = Amazon.SimpleNotificationService.Util.Message.ParseMessage(jsonData);
        //LogIt.D(jsonData);
        //LogIt.D(sm);

        if (!string.IsNullOrEmpty(sm.SubscribeURL)) {
          var uri = new Uri(sm.SubscribeURL);
          var baseUrl = uri.GetLeftPart(System.UriPartial.Authority);
          var resource = sm.SubscribeURL.Replace(baseUrl, "");
          var response = new RestClient {
            BaseUrl = new Uri(baseUrl),
          }.Execute(new RestRequest {
            Resource = resource,
            Method = Method.GET,
            RequestFormat = RestSharp.DataFormat.Xml
          });
          if (response.StatusCode != System.Net.HttpStatusCode.OK) {
            //LogIt.W(response.StatusCode);
          } else {
            //LogIt.I(response.Content);
          }
        }

        //read for topic: sm.TopicArn
        //read for data: dynamic json = JObject.Parse(sm.MessageText);
        //extract value: var s3OrigUrlSnippet = json.input.key.Value as string;

        //do stuff
        return Request.CreateResponse(HttpStatusCode.OK, new { });
      } catch (Exception ex) {
        //LogIt.E(ex);
        return Request.CreateResponse(HttpStatusCode.InternalServerError, new { status = "unexpected error" });
      }
    }
  }
}
like image 35
sobelito Avatar answered Sep 21 '22 18:09

sobelito