Skip to content

Instantly share code, notes, and snippets.

@mjg123
Created August 18, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjg123/294b4af36be1b9b09ba32e7009eef3bb to your computer and use it in GitHub Desktop.
Save mjg123/294b4af36be1b9b09ba32e7009eef3bb to your computer and use it in GitHub Desktop.
import com.twilio.security.RequestValidator;
import java.util.HashMap;
import static spark.Spark.get;
import static spark.Spark.post;
public class RequestValidation {
public static void main(String[] args) {
setupUnvalidatedEndpoints();
setupValidatedEndpoints();
}
private static void setupUnvalidatedEndpoints() {
get("/unvalidated", (req, res) -> {
return "ok";
});
post("/unvalidated", (req, res) -> {
return "ok";
});
}
private static void setupValidatedEndpoints() {
var twilioAuthToken = System.getenv("TWILIO_AUTH_TOKEN");
var requestValidator = new RequestValidator(twilioAuthToken);
get("/validated", (req, res) -> {
// We can't pull this from the request because ngrok will have rewritten it
// by the time the request reaches our server, so I'm hard-coding the value
// from the PN configuration page.
String originalUrl = "https://7a0834548d4a.ngrok.io/validated";
var twilioSignature = req.headers("X-Twilio-Signature");
var validationParams = new HashMap<String, String>();
// Query params can (in theory) have multiple values. Assuming that Twilio doesn't
// actually send any repeated values seems to be valid, hence `e.getValue()[0]` below.
req.queryMap().toMap().entrySet().forEach(e -> {
validationParams.put(e.getKey(), e.getValue()[0]);
});
System.out.println("\nTwilio used this URL: " + originalUrl);
System.out.println(validationParams);
System.out.println(twilioSignature);
var isValidRequest = requestValidator.validate(originalUrl, validationParams, twilioSignature);
if (!isValidRequest) {
// We always always end up here
res.status(401);
return "unauthorized";
}
return "OK, you're valid";
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment