Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Secure your C# / ASP.NET app by validating incoming Twilio requests


(warning)

Warning

See the AspNetCore version of this guide.

In this guide we'll cover how to secure your C# / ASP.NET MVC(link takes you to an external page) 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(link takes you to an external page)'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!


Create a custom filter attribute

create-a-custom-filter-attribute page anchor

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(link takes you to an external page). This way we can reuse our validation logic across all our controller actions which accept incoming requests from Twilio.

Use filter attribute to validate Twilio requests

use-filter-attribute-to-validate-twilio-requests page anchor

Confirm incoming requests to your controllers are genuine with this filter.


_38
using System;
_38
using System.Configuration;
_38
using System.Web;
_38
using System.Net;
_38
using System.Web.Mvc;
_38
using Twilio.Security;
_38
_38
namespace ValidateRequestExample.Filters
_38
{
_38
[AttributeUsage(AttributeTargets.Method)]
_38
public class ValidateTwilioRequestAttribute : ActionFilterAttribute
_38
{
_38
private readonly RequestValidator _requestValidator;
_38
_38
public ValidateTwilioRequestAttribute()
_38
{
_38
var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
_38
_requestValidator = new RequestValidator(authToken);
_38
}
_38
_38
public override void OnActionExecuting(ActionExecutingContext actionContext)
_38
{
_38
var context = actionContext.HttpContext;
_38
if(!IsValidRequest(context.Request))
_38
{
_38
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
_38
}
_38
_38
base.OnActionExecuting(actionContext);
_38
}
_38
_38
private bool IsValidRequest(HttpRequestBase request) {
_38
var signature = request.Headers["X-Twilio-Signature"];
_38
var requestUrl = request.Url.AbsoluteUri;
_38
return _requestValidator.Validate(requestUrl, request.Form, signature);
_38
}
_38
}
_38
}

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.


Use the filter attribute with our Twilio webhooks

use-the-filter-attribute-with-our-twilio-webhooks page anchor

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 the request validation filter attribute to a set of controller methods

apply-the-request-validation-filter-attribute-to-a-set-of-controller-methods page anchor

Apply a custom Twilio request validation filter attribute to a set of controller methods used for Twilio webhooks.


_37
using System.Web.Mvc;
_37
using Twilio.AspNet.Mvc;
_37
using Twilio.TwiML;
_37
using ValidateRequestExample.Filters;
_37
_37
namespace ValidateRequestExample.Controllers
_37
{
_37
public class IncomingController : TwilioController
_37
{
_37
[ValidateTwilioRequest]
_37
public ActionResult Voice(string from)
_37
{
_37
var message = "Thanks for calling! " +
_37
$"Your phone number is {from}. " +
_37
"I got your call because of Twilio's webhook. " +
_37
"Goodbye!";
_37
_37
var response = new VoiceResponse();
_37
response.Say(string.Format(message, from));
_37
response.Hangup();
_37
_37
return TwiML(response);
_37
}
_37
_37
[ValidateTwilioRequest]
_37
public ActionResult Message(string body)
_37
{
_37
var message = $"Your text to me was {body.Length} characters long. " +
_37
"Webhooks are neat :)";
_37
_37
var response = new MessagingResponse();
_37
response.Message(new Message(message));
_37
_37
return TwiML(response);
_37
}
_37
}
_37
}

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.


Disable request validation during testing

disable-request-validation-during-testing page anchor

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.

An improved request validation filter attribute, useful for testing

an-improved-request-validation-filter-attribute-useful-for-testing page anchor

Use this version of the custom filter attribute if you test your controllers.


_40
using System;
_40
using System.Configuration;
_40
using System.Web;
_40
using System.Net;
_40
using System.Web.Mvc;
_40
using Twilio.Security;
_40
_40
namespace ValidateRequestExample.Filters
_40
{
_40
[AttributeUsage(AttributeTargets.Method)]
_40
public class ValidateTwilioRequestAttribute : ActionFilterAttribute
_40
{
_40
private readonly RequestValidator _requestValidator;
_40
private static bool IsTestEnvironment =>
_40
bool.Parse(ConfigurationManager.AppSettings["IsTestEnvironment"]);
_40
_40
public ValidateTwilioRequestAttribute()
_40
{
_40
var authToken = ConfigurationManager.AppSettings["TwilioAuthToken"];
_40
_requestValidator = new RequestValidator(authToken);
_40
}
_40
_40
public override void OnActionExecuting(ActionExecutingContext actionContext)
_40
{
_40
var context = actionContext.HttpContext;
_40
if (!IsTestEnvironment && !IsValidRequest(context.Request))
_40
{
_40
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
_40
}
_40
_40
base.OnActionExecuting(actionContext);
_40
}
_40
_40
private bool IsValidRequest(HttpRequestBase request) {
_40
var signature = request.Headers["X-Twilio-Signature"];
_40
var requestUrl = request.RawUrl;
_40
return _requestValidator.Validate(requestUrl, request.Form, signature);
_40
}
_40
}
_40
}


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(link takes you to an external page).


Rate this page: