In this guide, you'll learn how to secure your Gin application by validating incoming requests to your Twilio webhooks are, in fact, from Twilio.
With a few lines of code, you'll write a custom middleware for our Gin project that uses the Twilio Go SDK's validator struct method. You can then apply that middleware to any route which accepts Twilio webhooks to confirm that incoming requests genuinely originated from Twilio.
Let's get started!
The Twilio Go SDK includes a RequestValidator
struct that you can use to validate incoming requests.
Building this into a middleware is a great way to reuse our validation logic across all routes that accept incoming requests from Twilio.
Confirm incoming requests to your Gin routes are genuine with this custom middleware.
1package main23import (4"fmt"5"net/http"6"os"78"github.com/gin-gonic/gin"9"github.com/twilio/twilio-go/client"10"github.com/twilio/twilio-go/twiml"11)1213// Custom Gin middleware that rejects non-Twilio requests14func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {15return func(context *gin.Context) {16// Your url will vary depending on your environment and how your application is deployed17// Modify this url declaration sample as necessary18url := "https://some-digits.ngrok.io" + context.Request.URL.Path19signatureHeader := context.Request.Header.Get("X-Twilio-Signature")20params := make(map[string]string)21context.Request.ParseForm()22for key, value := range context.Request.PostForm {23params[key] = value[0]24}2526// Requests are validated based on the incoming url, parameters,27// and the X-Twilio-Signature header.28// If the request is not valid, return a 403 error29if !validator.Validate(url, params, signatureHeader) {30fmt.Println("Request isn't from Twilio 🚫")31context.AbortWithStatus(http.StatusForbidden)32return33}34// If the request is valid, execute the next middleware (in this case, the route handler)35context.Next()36}37}3839func main() {40router := gin.Default()41// Create a RequestValidator instance42requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))4344// Apply the requireValidTwilioSignature middleware to your route handler(s), before any45// code that you want to only apply to validated requests46router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {47message := &twiml.MessagingMessage{48Body: "Yay, valid requests!",49}5051twimlResult, err := twiml.Messages([]twiml.Element{message})52if err != nil {53context.String(http.StatusInternalServerError, err.Error())54} else {55context.Header("Content-Type", "text/xml")56context.String(http.StatusOK, twimlResult)57}58})5960router.Run(":3000")61}62
To validate an incoming request genuinely originated from Twilio, you first need to create an instance of the RequestValidator
struct using our Twilio auth token. After that you call its Validate
method, passing in the request's URL, payload, and the value of the request's X-TWILIO-SIGNATURE
header. Remember that the incoming request from a Twilio webhook is of type application/x-www-form-urlencoded
, so you will need to create a map
and populate it with all of the key/value pairs from the request in order for this to work.
The Validate
method will return the Boolean true
if the request is valid or false
if it isn't. Based on this result, this middleware then either calls context.Next()
to pass the request onto the next middleware or handler code or returns a 403 HTTP response for inauthentic requests.
To apply this middleware, add it to the list of handlers for any route before any code that requires this validation.
Your request validator may fail locally when you use a ngrok tunnel, or in production if your app is behind a load balancer, proxy, etc. This is because the request URL that your Gin application sees does not match the URL Twilio used to reach your application.
To fix this for local development with ngrok, you may want to manually set the value of the URL based on your tunnel's scheme and host. To fix this in your production app, your middleware will need to reconstruct the request's original URL using deployment environment variables and request headers like X-Forwarded-Proto
, if available.
If you write tests for your Gin app, those tests may fail for routes where you use your Twilio request validation middleware. Any requests your test suite sends to those routes will fail the validation check.
To fix this problem, we recommend adding an extra check in your middleware, telling it to only reject invalid requests if your app is running outside of a test environment. Implementation details such as checking for Go Flags vs environment variables will very depending on your development stack, but the principle remains the same.
Disable webhook validation during testing.
1import (2"flag"3"fmt"4"net/http"5"os"6"testing"78"github.com/gin-gonic/gin"9"github.com/twilio/twilio-go/client"10"github.com/twilio/twilio-go/twiml"11)1213// The init function is a great place to prepare application state prior to execution14// In this case, parsing input flags to your app15func init() {16testing.Init()17flag.Parse()18}1920// Helper method to determine if your Go code is being run in test mode21func IsTestRun() bool {22return flag.Lookup("test.v").Value.(flag.Getter).Get().(bool)23// Some teams may prefer to use env vars to indicate testing instead, such as24// return os.Getenv("GO_ENV") == "testing"25}2627// Custom Gin middleware that rejects non-Twilio requests28func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {29return func(context *gin.Context) {30// Your url will vary depending on your environment and how your application is deployed31// Modify this url declaration sample as necessary32url := "https://some-digits.ngrok.io" + context.Request.URL.Path33signatureHeader := context.Request.Header.Get("X-Twilio-Signature")34params := make(map[string]string)35context.Request.ParseForm()36for key, value := range context.Request.PostForm {37params[key] = value[0]38}3940// Requests are validated based on the incoming url, parameters,41// and the X-Twilio-Signature header.42// If the request is not valid AND this isn't being run in a test env, return a 403 error43if !validator.Validate(url, params, signatureHeader) && !IsTestRun() {44fmt.Println("Request isn't from Twilio 🚫")45context.AbortWithStatus(http.StatusForbidden)46return47}48// If the request is valid, execute the next middleware (in this case, the route handler)49context.Next()50}51}5253func main() {54router := gin.Default()55// Create a RequestValidator instance56requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))5758// Apply the requireValidTwilioSignature middleware to your route handler(s), before any59// code that you want to only apply to validated requests60router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {61message := &twiml.MessagingMessage{62Body: "Yay, valid requests!",63}6465twimlResult, err := twiml.Messages([]twiml.Element{message})66if err != nil {67context.String(http.StatusInternalServerError, err.Error())68} else {69context.Header("Content-Type", "text/xml")70context.String(http.StatusOK, twimlResult)71}72})7374router.Run(":3000")75}76
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.