In this guide we'll cover how to secure your C# / ASP.NET MVC application by validating incoming requests to your Twilio webhooks are, in fact, from Twilio.
With a few lines of code, we'll write a custom filter attribute for our ASP.NET app that uses the Twilio C# SDK's validator utility. This filter will then be invoked on the controller actions that accept Twilio webhooks to confirm that incoming requests genuinely originated from Twilio.
Let's get started!
The Twilio C# SDK includes a RequestValidator
class we can use to validate incoming requests.
We could include our request validation code as part of our controller, but this is a perfect opportunity to write an action filter attribute. This way we can reuse our validation logic across all our controller actions which accept incoming requests from Twilio.
Confirm incoming requests to your controllers are genuine with this filter.
1using System;2using System.Configuration;3using System.Web;4using System.Net;5using System.Web.Mvc;6using Twilio.Security;78namespace ValidateRequestExample.Filters9{10[AttributeUsage(AttributeTargets.Method)]11public class ValidateTwilioRequestAttribute : ActionFilterAttribute12{13private readonly RequestValidator _requestValidator;1415public ValidateTwilioRequestAttribute()16{17var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];18_requestValidator = new RequestValidator(authToken);19}2021public override void OnActionExecuting(ActionExecutingContext actionContext)22{23var context = actionContext.HttpContext;24if(!IsValidRequest(context.Request))25{26actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);27}2829base.OnActionExecuting(actionContext);30}3132private bool IsValidRequest(HttpRequestBase request) {33var signature = request.Headers["X-Twilio-Signature"];34var requestUrl = request.Url.AbsoluteUri;35return _requestValidator.Validate(requestUrl, request.Form, signature);36}37}38}39
To validate an incoming request genuinely originated from Twilio, we first need to create an instance of the RequestValidator
class. After that we call its validate method, passing in the request's HTTP context and our Twilio auth token.
That method will return True if the request is valid or False if it isn't. Our filter attribute then either continues processing the action or returns a 403 HTTP response for invalid requests.
Now we're ready to apply our filter attribute to any controller action in our ASP.NET application that handles incoming requests from Twilio.
Apply a custom Twilio request validation filter attribute to a set of controller methods used for Twilio webhooks.
1using System.Web.Mvc;2using Twilio.AspNet.Mvc;3using Twilio.TwiML;4using ValidateRequestExample.Filters;56namespace ValidateRequestExample.Controllers7{8public class IncomingController : TwilioController9{10[ValidateTwilioRequest]11public ActionResult Voice(string from)12{13var message = "Thanks for calling! " +14$"Your phone number is {from}. " +15"I got your call because of Twilio's webhook. " +16"Goodbye!";1718var response = new VoiceResponse();19response.Say(string.Format(message, from));20response.Hangup();2122return TwiML(response);23}2425[ValidateTwilioRequest]26public ActionResult Message(string body)27{28var message = $"Your text to me was {body.Length} characters long. " +29"Webhooks are neat :)";3031var response = new MessagingResponse();32response.Message(new Message(message));3334return TwiML(response);35}36}37}38
To use the filter attribute with an existing view, just put [ValidateTwilioRequest]
above the action's definition. In this sample application, we use our filter attribute with two controller actions: one that handles incoming phone calls and another that handles incoming text messages.
Note: If your Twilio webhook URLs start with https://
instead of http://
, your request validator may fail locally when you use Ngrok or in production if your stack terminates SSL connections upstream from your app. This is because the request URL that your ASP.NET application sees does not match the URL Twilio used to reach your application.
To fix this for local development with Ngrok, use http://
for your webhook instead of https://
. To fix this in your production app, your decorator will need to reconstruct the request's original URL using request headers like X-Original-Host
and X-Forwarded-Proto
, if available.
If you write tests for your controller actions, those tests may fail where you use your Twilio request validation filter. Any requests your test suite sends to those actions will fail the filter's validation check.
To fix this problem we recommend adding an extra check in your filter attribute, like so, telling it to only reject incoming requests if your app is running in production.
Use this version of the custom filter attribute if you test your controllers.
1using System;2using System.Configuration;3using System.Web;4using System.Net;5using System.Web.Mvc;6using Twilio.Security;78namespace ValidateRequestExample.Filters9{10[AttributeUsage(AttributeTargets.Method)]11public class ValidateTwilioRequestAttribute : ActionFilterAttribute12{13private readonly RequestValidator _requestValidator;14private static bool IsTestEnvironment =>15bool.Parse(ConfigurationManager.AppSettings["IsTestEnvironment"]);1617public ValidateTwilioRequestAttribute()18{19var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];20_requestValidator = new RequestValidator(authToken);21}2223public override void OnActionExecuting(ActionExecutingContext actionContext)24{25var context = actionContext.HttpContext;26if (!IsTestEnvironment && !IsValidRequest(context.Request))27{28actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);29}3031base.OnActionExecuting(actionContext);32}3334private bool IsValidRequest(HttpRequestBase request) {35var signature = request.Headers["X-Twilio-Signature"];36var requestUrl = request.RawUrl;37return _requestValidator.Validate(requestUrl, request.Form, signature);38}39}40}41
Validating requests to your Twilio webhooks is a great first step for securing your Twilio application. We recommend reading over our full security documentation for more advice on protecting your app, and the Anti-Fraud Developer's Guide in particular.
To learn more about securing your ASP.NET MVC application in general, check out the security considerations page in the official ASP.NET docs.