In this guide, we'll cover how to secure your C# / ASP.NET Core 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!
If you don't want to develop your own validation filter, you can install the Twilio helper library for ASP.NET Core and use the library's [ValidateRequest]
attribute instead that has more features. This library also contains an endpoint filter and a middleware validator.
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 controllers and actions that accept incoming requests from Twilio.
Confirm incoming requests to your controllers are genuine with this filter.
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Threading.Tasks;5using Microsoft.AspNetCore.Http;6using Microsoft.AspNetCore.Mvc;7using Microsoft.AspNetCore.Mvc.Filters;8using Microsoft.Extensions.Configuration;9using Twilio.Security;1011namespace ValidateRequestExample.Filters12{13[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]14public class ValidateTwilioRequestAttribute : TypeFilterAttribute15{16public ValidateTwilioRequestAttribute() : base(typeof(ValidateTwilioRequestFilter))17{18}19}2021internal class ValidateTwilioRequestFilter : IAsyncActionFilter22{23private readonly RequestValidator _requestValidator;2425public ValidateTwilioRequestFilter(IConfiguration configuration)26{27var authToken = configuration["Twilio:AuthToken"] ?? throw new Exception("'Twilio:AuthToken' not configured.");28_requestValidator = new RequestValidator(authToken);29}3031public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)32{33var httpContext = context.HttpContext;34var request = httpContext.Request;3536var requestUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";37Dictionary<string, string> parameters = null;3839if (request.HasFormContentType)40{41var form = await request.ReadFormAsync(httpContext.RequestAborted).ConfigureAwait(false);42parameters = form.ToDictionary(p => p.Key, p => p.Value.ToString());43}4445var signature = request.Headers["X-Twilio-Signature"];46var isValid = _requestValidator.Validate(requestUrl, parameters, signature);4748if (!isValid)49{50httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;51return;52}5354await next();55}56}57}
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 forbidden 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 Microsoft.AspNetCore.Mvc;2using Twilio.TwiML;3using ValidateRequestExample.Filters;45namespace ValidateRequestExample.Controllers6{7[Route("[controller]/[action]")]8public class IncomingController : Controller9{10[ValidateTwilioRequest]11public IActionResult 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 Content(response.ToString(), "text/xml");23}2425[ValidateTwilioRequest]26public IActionResult 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(message);3334return Content(response.ToString(), "text/xml");35}36}37}
To use the filter attribute with an existing controller action, 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.
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 method will need to reconstruct the request's original URL using request headers like X-Original-Host
and X-Forwarded-Proto
, if available.
Before running the application, make sure you configure your Twilio Auth Token as the Twilio:AuthToken
configuration, using .NET's secrets manager, environment variables, a vault service, or some other secure configuration source.
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.Linq;4using System.Threading.Tasks;5using Microsoft.AspNetCore.Hosting;6using Microsoft.AspNetCore.Http;7using Microsoft.AspNetCore.Mvc;8using Microsoft.AspNetCore.Mvc.Filters;9using Microsoft.Extensions.Configuration;10using Twilio.Security;1112namespace ValidateRequestExample.Filters13{14[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]15public class ValidateTwilioRequestAttribute : TypeFilterAttribute16{17public ValidateTwilioRequestAttribute() : base(typeof(ValidateTwilioRequestFilter))18{19}20}2122internal class ValidateTwilioRequestFilter : IAsyncActionFilter23{24private readonly RequestValidator _requestValidator;25private readonly bool _isEnabled;2627public ValidateTwilioRequestFilter(IConfiguration configuration, IWebHostEnvironment environment)28{29var authToken = configuration["Twilio:AuthToken"] ?? throw new Exception("'Twilio:AuthToken' not configured.");30_requestValidator = new RequestValidator(authToken);31_isEnabled = configuration.GetValue("Twilio:RequestValidation:Enabled", true);32}3334public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)35{36if (!_isEnabled)37{38await next();39return;40}4142var httpContext = context.HttpContext;43var request = httpContext.Request;4445var requestUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";46Dictionary<string, string> parameters = null;4748if (request.HasFormContentType)49{50var form = await request.ReadFormAsync(httpContext.RequestAborted).ConfigureAwait(false);51parameters = form.ToDictionary(p => p.Key, p => p.Value.ToString());52}5354var signature = request.Headers["X-Twilio-Signature"];55var isValid = _requestValidator.Validate(requestUrl, parameters, signature);5657if (!isValid)58{59httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;60return;61}6263await next();64}65}66}
To disable the request validation, you can now configure Twilio:RequestValidation:Enabled
to false
in your appsettings.json or appsettings.Development.json file.
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.