I use the below code for validation incoming request, if it is really coming from Twilio.
The url is,
We use get & POST method.
We get the expectedSignature as follows,
String expectedSignature = request.getHeader("X-Twilio-Signature");
Request URl is,
String serverUrl = request.getRequestURL().toString()+"/"+request.getQueryString();
// Since we use GET, it will be empty and it is working fine.
Map<String,String> tempParams = new HashMap<String,String>();
TwilioUtils util = new TwilioUtils("AUTH_TOKEN_OF_USER");
boolean validationResult = util.validateRequest(expectedSignature, serverUrl, tempParams);
For POST it is not working. Code for POST,
------------ EDIT ---------------------
// Check twilio header ...
String expectedSignature = request.getHeader("X-Twilio-Signature");
// These are the post params twilio sent in its request
Map<String, String> params = null;
String serverUrl = null;
serverUrl = PROTOCOL + "://" + request.getServerName() + request.getRequestURI() + "?" + request.getQueryString();
if (request.getMethod().equalsIgnoreCase("POST")) {
params = new HashMap<String, String>();
Enumeration<String> reqParams = request.getParameterNames();
LOGGER.info("NUMBER OF PARAMS ===>>>> " + request.getParameterMap().size());
int i = 1;
while (reqParams.hasMoreElements()) {
String paramName = reqParams.nextElement();
String paramValue = request.getParameter(paramName);
LOGGER.info("KKKKK KEY is {}, value is {} count {}", paramName, paramValue, i);
params.put(paramName, paramValue);
i = i + 1;
}
String queryString = request.getQueryString();
if (! StringUtils.isEmpty(queryString)) {
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
params.remove(keyValuePair[0]);
LOGGER.info("===>>>> Removing KEY {} ", keyValuePair[0]);
}
}
LOGGER.info("NUMBER OF PARAMS COUNT FINAL ===>>>> " + params.size());
}
}
TwilioUtils util = new TwilioUtils(authToken);
boolean validationResult = util.validateRequest(expectedSignature, serverUrl, params);
It always returns false. Am I doing anything wrong.