Skip to contentSkip to navigationSkip to topbar
On this page

Secure your Gin project by validating incoming Twilio requests


In this guide, you'll learn how to secure your Gin(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, you'll write a custom middleware for our Gin project that uses the Twilio Go SDK(link takes you to an external page)'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!


Create and apply a custom middleware

create-and-apply-a-custom-middleware page anchor

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.

Custom middleware for Gin projects to validate Twilio requests

custom-middleware-for-gin-projects-to-validate-twilio-requests page anchor

Confirm incoming requests to your Gin routes are genuine with this custom middleware.

1
package main
2
3
import (
4
"fmt"
5
"net/http"
6
"os"
7
8
"github.com/gin-gonic/gin"
9
"github.com/twilio/twilio-go/client"
10
"github.com/twilio/twilio-go/twiml"
11
)
12
13
// Custom Gin middleware that rejects non-Twilio requests
14
func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {
15
return func(context *gin.Context) {
16
// Your url will vary depending on your environment and how your application is deployed
17
// Modify this url declaration sample as necessary
18
url := "https://some-digits.ngrok.io" + context.Request.URL.Path
19
signatureHeader := context.Request.Header.Get("X-Twilio-Signature")
20
params := make(map[string]string)
21
context.Request.ParseForm()
22
for key, value := range context.Request.PostForm {
23
params[key] = value[0]
24
}
25
26
// 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 error
29
if !validator.Validate(url, params, signatureHeader) {
30
fmt.Println("Request isn't from Twilio 🚫")
31
context.AbortWithStatus(http.StatusForbidden)
32
return
33
}
34
// If the request is valid, execute the next middleware (in this case, the route handler)
35
context.Next()
36
}
37
}
38
39
func main() {
40
router := gin.Default()
41
// Create a RequestValidator instance
42
requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))
43
44
// Apply the requireValidTwilioSignature middleware to your route handler(s), before any
45
// code that you want to only apply to validated requests
46
router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {
47
message := &twiml.MessagingMessage{
48
Body: "Yay, valid requests!",
49
}
50
51
twimlResult, err := twiml.Messages([]twiml.Element{message})
52
if err != nil {
53
context.String(http.StatusInternalServerError, err.Error())
54
} else {
55
context.Header("Content-Type", "text/xml")
56
context.String(http.StatusOK, twimlResult)
57
}
58
})
59
60
router.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.

(warning)

Warning

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.


Disable request validation during testing

disable-request-validation-during-testing page anchor

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 Twilio webhook middleware when testing Gin routes.

disable-twilio-webhook-middleware-when-testing-gin-routes page anchor

Disable webhook validation during testing.

1
import (
2
"flag"
3
"fmt"
4
"net/http"
5
"os"
6
"testing"
7
8
"github.com/gin-gonic/gin"
9
"github.com/twilio/twilio-go/client"
10
"github.com/twilio/twilio-go/twiml"
11
)
12
13
// The init function is a great place to prepare application state prior to execution
14
// In this case, parsing input flags to your app
15
func init() {
16
testing.Init()
17
flag.Parse()
18
}
19
20
// Helper method to determine if your Go code is being run in test mode
21
func IsTestRun() bool {
22
return flag.Lookup("test.v").Value.(flag.Getter).Get().(bool)
23
// Some teams may prefer to use env vars to indicate testing instead, such as
24
// return os.Getenv("GO_ENV") == "testing"
25
}
26
27
// Custom Gin middleware that rejects non-Twilio requests
28
func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {
29
return func(context *gin.Context) {
30
// Your url will vary depending on your environment and how your application is deployed
31
// Modify this url declaration sample as necessary
32
url := "https://some-digits.ngrok.io" + context.Request.URL.Path
33
signatureHeader := context.Request.Header.Get("X-Twilio-Signature")
34
params := make(map[string]string)
35
context.Request.ParseForm()
36
for key, value := range context.Request.PostForm {
37
params[key] = value[0]
38
}
39
40
// 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 error
43
if !validator.Validate(url, params, signatureHeader) && !IsTestRun() {
44
fmt.Println("Request isn't from Twilio 🚫")
45
context.AbortWithStatus(http.StatusForbidden)
46
return
47
}
48
// If the request is valid, execute the next middleware (in this case, the route handler)
49
context.Next()
50
}
51
}
52
53
func main() {
54
router := gin.Default()
55
// Create a RequestValidator instance
56
requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))
57
58
// Apply the requireValidTwilioSignature middleware to your route handler(s), before any
59
// code that you want to only apply to validated requests
60
router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {
61
message := &twiml.MessagingMessage{
62
Body: "Yay, valid requests!",
63
}
64
65
twimlResult, err := twiml.Messages([]twiml.Element{message})
66
if err != nil {
67
context.String(http.StatusInternalServerError, err.Error())
68
} else {
69
context.Header("Content-Type", "text/xml")
70
context.String(http.StatusOK, twimlResult)
71
}
72
})
73
74
router.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.