Skip to contentSkip to navigationSkip to topbar
On this page

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


(warning)

Warning

See the ASP.NET version of thisguide.

In this guide, we'll cover how to secure your C# / ASP.NET Core(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!

(information)

Info

If you don't want to develop your own validation filter, you can install the Twilio helper library for ASP.NET Core(link takes you to an external page) and use the library's [ValidateRequest] attribute instead that has more features. This library also contains an endpoint filter and a middleware validator.


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 controllers and actions that 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.

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using Microsoft.AspNetCore.Http;
6
using Microsoft.AspNetCore.Mvc;
7
using Microsoft.AspNetCore.Mvc.Filters;
8
using Microsoft.Extensions.Configuration;
9
using Twilio.Security;
10
11
namespace ValidateRequestExample.Filters
12
{
13
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
14
public class ValidateTwilioRequestAttribute : TypeFilterAttribute
15
{
16
public ValidateTwilioRequestAttribute() : base(typeof(ValidateTwilioRequestFilter))
17
{
18
}
19
}
20
21
internal class ValidateTwilioRequestFilter : IAsyncActionFilter
22
{
23
private readonly RequestValidator _requestValidator;
24
25
public ValidateTwilioRequestFilter(IConfiguration configuration)
26
{
27
var authToken = configuration["Twilio:AuthToken"] ?? throw new Exception("'Twilio:AuthToken' not configured.");
28
_requestValidator = new RequestValidator(authToken);
29
}
30
31
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
32
{
33
var httpContext = context.HttpContext;
34
var request = httpContext.Request;
35
36
var requestUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
37
Dictionary<string, string> parameters = null;
38
39
if (request.HasFormContentType)
40
{
41
var form = await request.ReadFormAsync(httpContext.RequestAborted).ConfigureAwait(false);
42
parameters = form.ToDictionary(p => p.Key, p => p.Value.ToString());
43
}
44
45
var signature = request.Headers["X-Twilio-Signature"];
46
var isValid = _requestValidator.Validate(requestUrl, parameters, signature);
47
48
if (!isValid)
49
{
50
httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
51
return;
52
}
53
54
await 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.


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.

1
using Microsoft.AspNetCore.Mvc;
2
using Twilio.TwiML;
3
using ValidateRequestExample.Filters;
4
5
namespace ValidateRequestExample.Controllers
6
{
7
[Route("[controller]/[action]")]
8
public class IncomingController : Controller
9
{
10
[ValidateTwilioRequest]
11
public IActionResult Voice(string from)
12
{
13
var message = "Thanks for calling! " +
14
$"Your phone number is {from}. " +
15
"I got your call because of Twilio\'s webhook. " +
16
"Goodbye!";
17
18
var response = new VoiceResponse();
19
response.Say(string.Format(message, from));
20
response.Hangup();
21
22
return Content(response.ToString(), "text/xml");
23
}
24
25
[ValidateTwilioRequest]
26
public IActionResult Message(string body)
27
{
28
var message = $"Your text to me was {body.Length} characters long. " +
29
"Webhooks are neat :)";
30
31
var response = new MessagingResponse();
32
response.Message(message);
33
34
return 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.

(information)

Info

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(link takes you to an external page) as the Twilio:AuthToken configuration, using .NET's secrets manager(link takes you to an external page), environment variables, a vault service, or some other secure configuration source.


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.

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using Microsoft.AspNetCore.Hosting;
6
using Microsoft.AspNetCore.Http;
7
using Microsoft.AspNetCore.Mvc;
8
using Microsoft.AspNetCore.Mvc.Filters;
9
using Microsoft.Extensions.Configuration;
10
using Twilio.Security;
11
12
namespace ValidateRequestExample.Filters
13
{
14
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
15
public class ValidateTwilioRequestAttribute : TypeFilterAttribute
16
{
17
public ValidateTwilioRequestAttribute() : base(typeof(ValidateTwilioRequestFilter))
18
{
19
}
20
}
21
22
internal class ValidateTwilioRequestFilter : IAsyncActionFilter
23
{
24
private readonly RequestValidator _requestValidator;
25
private readonly bool _isEnabled;
26
27
public ValidateTwilioRequestFilter(IConfiguration configuration, IWebHostEnvironment environment)
28
{
29
var 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
}
33
34
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
35
{
36
if (!_isEnabled)
37
{
38
await next();
39
return;
40
}
41
42
var httpContext = context.HttpContext;
43
var request = httpContext.Request;
44
45
var requestUrl = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
46
Dictionary<string, string> parameters = null;
47
48
if (request.HasFormContentType)
49
{
50
var form = await request.ReadFormAsync(httpContext.RequestAborted).ConfigureAwait(false);
51
parameters = form.ToDictionary(p => p.Key, p => p.Value.ToString());
52
}
53
54
var signature = request.Headers["X-Twilio-Signature"];
55
var isValid = _requestValidator.Validate(requestUrl, parameters, signature);
56
57
if (!isValid)
58
{
59
httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
60
return;
61
}
62
63
await 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(link takes you to an external page).

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.