Skip to contentSkip to navigationSkip to topbar
On this page

Secure your Servlet app by validating incoming Twilio requests


In this guide we'll cover how to secure your Servlet application by validating incoming requests to your Twilio webhooks that are, in fact, from Twilio.

With a few lines of code, we'll write a custom filter for our Servlet app that uses the Twilio Java SDK's(link takes you to an external page) validator utility. This filter will then be invoked on the relevant paths that accept Twilio webhooks to confirm that incoming requests genuinely originated from Twilio.

Let's get started!


Create a custom filter

create-a-custom-filter page anchor

The Twilio Java SDK includes a RequestValidator class we can use to validate incoming requests.

We could include our request validation code as part of our Servlet, but this is a perfect opportunity to write a Java filter(link takes you to an external page). This way we can reuse our validation logic across all our Servlets which accept incoming requests from Twilio.

Use Servlet filter to validate Twilio requests

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

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

1
package guide;
2
3
import com.twilio.security.RequestValidator;
4
5
import javax.servlet.*;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8
import java.io.IOException;
9
import java.util.Arrays;
10
import java.util.Collections;
11
import java.util.List;
12
import java.util.Map;
13
import java.util.stream.Collectors;
14
15
public class TwilioRequestValidatorFilter implements Filter {
16
17
private RequestValidator requestValidator;
18
19
@Override
20
public void init(FilterConfig filterConfig) throws ServletException {
21
requestValidator = new RequestValidator(System.getenv("TWILIO_AUTH_TOKEN"));
22
}
23
24
@Override
25
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
26
throws IOException, ServletException {
27
28
boolean isValidRequest = false;
29
if (request instanceof HttpServletRequest) {
30
HttpServletRequest httpRequest = (HttpServletRequest) request;
31
32
// Concatenates the request URL with the query string
33
String pathAndQueryUrl = getRequestUrlAndQueryString(httpRequest);
34
// Extracts only the POST parameters and converts the parameters Map type
35
Map<String, String> postParams = extractPostParams(httpRequest);
36
String signatureHeader = httpRequest.getHeader("X-Twilio-Signature");
37
38
isValidRequest = requestValidator.validate(
39
pathAndQueryUrl,
40
postParams,
41
signatureHeader);
42
}
43
44
if(isValidRequest) {
45
chain.doFilter(request, response);
46
} else {
47
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN);
48
}
49
}
50
51
@Override
52
public void destroy() {
53
// Nothing to do
54
}
55
56
private Map<String, String> extractPostParams(HttpServletRequest request) {
57
String queryString = request.getQueryString();
58
Map<String, String[]> requestParams = request.getParameterMap();
59
List<String> queryStringKeys = getQueryStringKeys(queryString);
60
61
return requestParams.entrySet().stream()
62
.filter(e -> !queryStringKeys.contains(e.getKey()))
63
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0]));
64
}
65
66
private List<String> getQueryStringKeys(String queryString) {
67
if(queryString == null || queryString.length() == 0) {
68
return Collections.emptyList();
69
} else {
70
return Arrays.stream(queryString.split("&"))
71
.map(pair -> pair.split("=")[0])
72
.collect(Collectors.toList());
73
}
74
}
75
76
private String getRequestUrlAndQueryString(HttpServletRequest request) {
77
String queryString = request.getQueryString();
78
String requestUrl = request.getRequestURL().toString();
79
if(queryString != null && !queryString.equals("")) {
80
return requestUrl + "?" + queryString;
81
}
82
return requestUrl;
83
}
84
}
85

The doFilter method will be executed before our Servlet, so it's here where we will validate that the request originated genuinely from Twilio, and prevent it from reaching our Servlet if it didn't. First, we gather the relevant request metadata (URL, query string and X-TWILIO-SIGNATURE header) and the POST parameters. We then pass this data onto the validate method of RequestValidator, which will return whether the validation was successful or not.

If the validation turns out successful, we continue executing other filters and eventually our Servlet. If it is unsuccessful, we stop the request and send a 403 - Forbidden response to the requester, in this case, Twilio.


Use the filter with our Twilio webhooks

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

Now we're ready to apply our filter to any path in our Servlet application that handles incoming requests from Twilio.

Apply the request validation filter to a set of Servlets

apply-the-request-validation-filter-to-a-set-of-servlets page anchor

Apply a custom Twilio request validation filter to a set of Servlets used for Twilio webhooks.

1
<?xml version="1.0" encoding="UTF-8"?>
2
<web-app version="3.0"
3
metadata-complete="true"
4
xmlns="http://java.sun.com/xml/ns/javaee"
5
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7
8
<servlet>
9
<servlet-name>voiceHandler</servlet-name>
10
<servlet-class>guide.VoiceHandlerServlet</servlet-class>
11
</servlet>
12
13
<servlet>
14
<servlet-name>messageHandler</servlet-name>
15
<servlet-class>guide.MessageHandlerServlet</servlet-class>
16
</servlet>
17
18
<servlet-mapping>
19
<servlet-name>voiceHandler</servlet-name>
20
<url-pattern>/voice</url-pattern>
21
</servlet-mapping>
22
23
<servlet-mapping>
24
<servlet-name>messageHandler</servlet-name>
25
<url-pattern>/message</url-pattern>
26
</servlet-mapping>
27
28
<filter>
29
<filter-name>requestValidatorFilter</filter-name>
30
<filter-class>guide.TwilioRequestValidatorFilter</filter-class>
31
</filter>
32
<filter-mapping>
33
<filter-name>requestValidatorFilter</filter-name>
34
<url-pattern>/*</url-pattern>
35
</filter-mapping>
36
</web-app>
37

To use the filter just add <filter> and <filter-mapping> sections to your web.xml. No changes are needed in the actual Servlets.

In the <filter> section we give a name to be used within your web.xml. In this case requestValidatorFilter. We also point to the filter class using its fully qualified name.

In the <filter-mapping> section, we configure what paths in our container will use TwilioRequestFilter when receiving a request. It uses URL patterns to select those paths, and you can have multiple <url-pattern> elements in this section. Since we want to apply the filter to both Servlets, we use their common root path.

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 Servlet 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 filter 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 Servlets those tests may fail where you use your Twilio request validation filter. Any requests your test suite sends to those Servlets will fail the filter's validation check.

To fix this problem we recommend adding an extra check in your filter, like so, telling it to only reject incoming requests if your app is running in production.

An improved request validation filter, useful for testing

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

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

1
package guide;
2
3
import com.twilio.security.RequestValidator;
4
5
import javax.servlet.*;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8
import java.io.IOException;
9
import java.util.Arrays;
10
import java.util.Collections;
11
import java.util.List;
12
import java.util.Map;
13
import java.util.stream.Collectors;
14
15
public class TwilioRequestValidatorFilter implements Filter {
16
17
private final String currentEnvironment = System.getenv("ENVIRONMENT");
18
19
private RequestValidator requestValidator;
20
21
@Override
22
public void init(FilterConfig filterConfig) throws ServletException {
23
requestValidator = new RequestValidator(System.getenv("TWILIO_AUTH_TOKEN"));
24
}
25
26
@Override
27
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
28
throws IOException, ServletException {
29
30
boolean isValidRequest = false;
31
if (request instanceof HttpServletRequest) {
32
HttpServletRequest httpRequest = (HttpServletRequest) request;
33
34
// Concatenates the request URL with the query string
35
String pathAndQueryUrl = getRequestUrlAndQueryString(httpRequest);
36
// Extracts only the POST parameters and converts the parameters Map type
37
Map<String, String> postParams = extractPostParams(httpRequest);
38
String signatureHeader = httpRequest.getHeader("X-Twilio-Signature");
39
40
isValidRequest = requestValidator.validate(
41
pathAndQueryUrl,
42
postParams,
43
signatureHeader);
44
}
45
46
if(isValidRequest || environmentIsTest()) {
47
chain.doFilter(request, response);
48
} else {
49
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN);
50
}
51
}
52
53
@Override
54
public void destroy() {
55
// Nothing to do
56
}
57
58
private boolean environmentIsTest() {
59
return "test".equals(currentEnvironment);
60
}
61
62
private Map<String, String> extractPostParams(HttpServletRequest request) {
63
String queryString = request.getQueryString();
64
Map<String, String[]> requestParams = request.getParameterMap();
65
List<String> queryStringKeys = getQueryStringKeys(queryString);
66
67
return requestParams.entrySet().stream()
68
.filter(e -> !queryStringKeys.contains(e.getKey()))
69
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0]));
70
}
71
72
private List<String> getQueryStringKeys(String queryString) {
73
if(queryString == null || queryString.length() == 0) {
74
return Collections.emptyList();
75
} else {
76
return Arrays.stream(queryString.split("&"))
77
.map(pair -> pair.split("=")[0])
78
.collect(Collectors.toList());
79
}
80
}
81
82
private String getRequestUrlAndQueryString(HttpServletRequest request) {
83
String queryString = request.getQueryString();
84
String requestUrl = request.getRequestURL().toString();
85
if(queryString != null && queryString != "") {
86
return requestUrl + "?" + queryString;
87
}
88
return requestUrl;
89
}
90
}
91

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 Servlet application in general, check out the security considerations page in the official Oracle docs(link takes you to an external page).