This guide is for ASP.NET Web API on the .NET Framework. For ASP.NET Core, see this guide. For ASP.NET MVC on the .NET Framework, see this guide.
In this guide, we'll cover how to secure your C# / ASP.NET Web API 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.Collections.Generic;3using System.Configuration;4using System.IO;5using System.Linq;6using System.Net;7using System.Net.Http;8using System.Threading;9using System.Threading.Tasks;10using System.Web.Http.Controllers;11using System.Web.Http.Filters;12using Twilio.Security;1314namespace ValidateRequestExample.Filters15{16[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]17public class ValidateTwilioRequestAttribute : ActionFilterAttribute18{19private readonly string _authToken;20private readonly string _urlSchemeAndDomain;2122public ValidateTwilioRequestAttribute()23{24_authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];25_urlSchemeAndDomain = ConfigurationManager.AppSettings["TwilioBaseUrl"];26}2728public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)29{30if (!await IsValidRequestAsync(actionContext.Request))31{32actionContext.Response = actionContext.Request.CreateErrorResponse(33HttpStatusCode.Forbidden,34"The Twilio request is invalid"35);36}3738await base.OnActionExecutingAsync(actionContext, cancellationToken);39}4041private async Task<bool> IsValidRequestAsync(HttpRequestMessage request)42{43var headerExists = request.Headers.TryGetValues(44"X-Twilio-Signature", out IEnumerable<string> signature);45if (!headerExists) return false;4647var requestUrl = _urlSchemeAndDomain + request.RequestUri.PathAndQuery;48var formData = await GetFormDataAsync(request.Content);49return new RequestValidator(_authToken).Validate(requestUrl, formData, signature.First());50}5152private async Task<IDictionary<string, string>> GetFormDataAsync(HttpContent content)53{54string postData;55using (var stream = new StreamReader(await content.ReadAsStreamAsync()))56{57stream.BaseStream.Position = 0;58postData = await stream.ReadToEndAsync();59}6061if(!String.IsNullOrEmpty(postData) && postData.Contains("="))62{63return postData.Split('&')64.Select(x => x.Split('='))65.ToDictionary(66x => Uri.UnescapeDataString(x[0]),67x => Uri.UnescapeDataString(x[1].Replace("+", "%20"))68);69}7071return new Dictionary<string, string>();72}73}74}75
To validate an incoming request genuinely originated from Twilio, we first need to create an instance of the RequestValidator
class passing it our Twilio Auth Token. Then we call its Validate
method passing the requester URL, the form parameters, and the Twilio request signature.
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.
1using System.Net.Http;2using System.Text;3using System.Web.Http;4using Twilio.TwiML;5using Twilio.TwiML.Messaging;6using ValidateRequestExample.Filters;78namespace ValidateRequestExample.Controllers9{10public class TwilioMessagingRequest11{12public string Body { get; set; }13}1415public class TwilioVoiceRequest16{17public string From { get; set; }18}1920public class IncomingController : ApiController21{22[Route("voice")]23[AcceptVerbs("POST")]24[ValidateTwilioRequest]25public HttpResponseMessage PostVoice([FromBody] TwilioVoiceRequest voiceRequest)26{27var message =28"Thanks for calling! " +29$"Your phone number is {voiceRequest.From}. " +30"I got your call because of Twilio's webhook. " +31"Goodbye!";3233var response = new VoiceResponse();34response.Say(message);35response.Hangup();3637return ToResponseMessage(response.ToString());38}3940[Route("message")]41[AcceptVerbs("POST")]42[ValidateTwilioRequest]43public HttpResponseMessage PostMessage([FromBody] TwilioMessagingRequest messagingRequest)44{45var message =46$"Your text to me was {messagingRequest.Body.Length} characters long. " +47"Webhooks are neat :)";4849var response = new MessagingResponse();50response.Append(new Message(message));5152return ToResponseMessage(response.ToString());53}5455private static HttpResponseMessage ToResponseMessage(string response)56{57return new HttpResponseMessage58{59Content = new StringContent(response, Encoding.UTF8, "application/xml")60};61}62}63}64
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.
You will need to add the following to your Web.config
file, in the appSettings
section:
1<add key="TwilioAuthToken" value="your_auth_token" />2<add key="TwilioBaseUrl" value="https://????.ngrok.io"/>
You can get your Twilio Auth Token from the Twilio Console. The TwilioBaseUrl
setting should be the public protocol and domain that you have configured on your Twilio phone number. For example, if you are using ngrok, you would put your ngrok URL here. If you are deploying to Azure or another cloud provider, put your publicly accessible domain here and include https or http, as appropriate for your application.
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.Collections.Generic;3using System.Configuration;4using System.IO;5using System.Linq;6using System.Net;7using System.Net.Http;8using System.Threading;9using System.Threading.Tasks;10using System.Web.Http.Controllers;11using System.Web.Http.Filters;12using Twilio.Security;1314namespace ValidateRequestExample.Filters15{16[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]17public class ValidateTwilioRequestImprovedAttribute : ActionFilterAttribute18{19private readonly string _authToken;20private readonly string _urlSchemeAndDomain;21private static bool IsTestEnvironment =>22bool.Parse(ConfigurationManager.AppSettings["IsTestEnvironment"]);2324public ValidateTwilioRequestImprovedAttribute()25{26_authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];27_urlSchemeAndDomain = ConfigurationManager.AppSettings["TwilioBaseUrl"];28}2930public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)31{32if (!await IsValidRequestAsync(actionContext.Request) && !IsTestEnvironment)33{34actionContext.Response = actionContext.Request.CreateErrorResponse(35HttpStatusCode.Forbidden,36"The Twilio request is invalid"37);38}3940await base.OnActionExecutingAsync(actionContext, cancellationToken);41}4243private async Task<bool> IsValidRequestAsync(HttpRequestMessage request)44{45var headerExists = request.Headers.TryGetValues(46"X-Twilio-Signature", out IEnumerable<string> signature);47if (!headerExists) return false;4849var requestUrl = _urlSchemeAndDomain + request.RequestUri.PathAndQuery;50var formData = await GetFormDataAsync(request.Content);51return new RequestValidator(_authToken).Validate(requestUrl, formData, signature.First());52}5354private async Task<IDictionary<string, string>> GetFormDataAsync(HttpContent content)55{56string postData;57using (var stream = new StreamReader(await content.ReadAsStreamAsync()))58{59stream.BaseStream.Position = 0;60postData = await stream.ReadToEndAsync();61}6263if (!String.IsNullOrEmpty(postData) && postData.Contains("="))64{65return postData.Split('&')66.Select(x => x.Split('='))67.ToDictionary(68x => Uri.UnescapeDataString(x[0]),69x => Uri.UnescapeDataString(x[1].Replace("+", "%20"))70);71}7273return new Dictionary<string, string>();74}75}76}77
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 Web API application in general, check out the security considerations in the official ASP.NET Web API docs.