# Secure your Gin project by validating incoming Twilio requests

In this guide, you'll learn how to secure your [Gin](https://gin-gonic.com/) 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](https://github.com/twilio/twilio-go)'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

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.

```go title="Custom middleware for Gin projects to validate Twilio requests" description="Confirm incoming requests to your Gin routes are genuine with this custom middleware."
package main

import (
 "fmt"
 "net/http"
 "os"

 "github.com/gin-gonic/gin"
 "github.com/twilio/twilio-go/client"
 "github.com/twilio/twilio-go/twiml"
)

// Custom Gin middleware that rejects non-Twilio requests
func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {
 return func(context *gin.Context) {
  // Your url will vary depending on your environment and how your application is deployed
  // Modify this url declaration sample as necessary
  url := "https://some-digits.ngrok.io" + context.Request.URL.Path
  signatureHeader := context.Request.Header.Get("X-Twilio-Signature")
  params := make(map[string]string)
  context.Request.ParseForm()
  for key, value := range context.Request.PostForm {
   params[key] = value[0]
  }

  // Requests are validated based on the incoming url, parameters,
  // and the X-Twilio-Signature header.
  // If the request is not valid, return a 403 error
  if !validator.Validate(url, params, signatureHeader) {
   fmt.Println("Request isn't from Twilio 🚫")
   context.AbortWithStatus(http.StatusForbidden)
   return
  }
  // If the request is valid, execute the next middleware (in this case, the route handler)
  context.Next()
 }
}

func main() {
 router := gin.Default()
 // Create a RequestValidator instance
 requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))

 // Apply the requireValidTwilioSignature middleware to your route handler(s), before any
 // code that you want to only apply to validated requests
 router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {
  message := &twiml.MessagingMessage{
   Body: "Yay, valid requests!",
  }

  twimlResult, err := twiml.Messages([]twiml.Element{message})
  if err != nil {
   context.String(http.StatusInternalServerError, err.Error())
  } else {
   context.Header("Content-Type", "text/xml")
   context.String(http.StatusOK, twimlResult)
  }
 })

 router.Run(":3000")
}

```

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]
>
> 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

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.

```go title="Disable Twilio webhook middleware when testing Gin routes." description="Disable webhook validation during testing."
import (
 "flag"
 "fmt"
 "net/http"
 "os"
 "testing"

 "github.com/gin-gonic/gin"
 "github.com/twilio/twilio-go/client"
 "github.com/twilio/twilio-go/twiml"
)

// The init function is a great place to prepare application state prior to execution
// In this case, parsing input flags to your app
func init() {
 testing.Init()
 flag.Parse()
}

// Helper method to determine if your Go code is being run in test mode
func IsTestRun() bool {
 return flag.Lookup("test.v").Value.(flag.Getter).Get().(bool)
 // Some teams may prefer to use env vars to indicate testing instead, such as
 // return os.Getenv("GO_ENV") == "testing"
}

// Custom Gin middleware that rejects non-Twilio requests
func requireValidTwilioSignature(validator *client.RequestValidator) gin.HandlerFunc {
 return func(context *gin.Context) {
  // Your url will vary depending on your environment and how your application is deployed
  // Modify this url declaration sample as necessary
  url := "https://some-digits.ngrok.io" + context.Request.URL.Path
  signatureHeader := context.Request.Header.Get("X-Twilio-Signature")
  params := make(map[string]string)
  context.Request.ParseForm()
  for key, value := range context.Request.PostForm {
   params[key] = value[0]
  }

  // Requests are validated based on the incoming url, parameters,
  // and the X-Twilio-Signature header.
  // If the request is not valid AND this isn't being run in a test env, return a 403 error
  if !validator.Validate(url, params, signatureHeader) && !IsTestRun() {
   fmt.Println("Request isn't from Twilio 🚫")
   context.AbortWithStatus(http.StatusForbidden)
   return
  }
  // If the request is valid, execute the next middleware (in this case, the route handler)
  context.Next()
 }
}

func main() {
 router := gin.Default()
 // Create a RequestValidator instance
 requestValidator := client.NewRequestValidator(os.Getenv("TWILIO_AUTH_TOKEN"))

 // Apply the requireValidTwilioSignature middleware to your route handler(s), before any
 // code that you want to only apply to validated requests
 router.POST("/sms", requireValidTwilioSignature(&requestValidator), func(context *gin.Context) {
  message := &twiml.MessagingMessage{
   Body: "Yay, valid requests!",
  }

  twimlResult, err := twiml.Messages([]twiml.Element{message})
  if err != nil {
   context.String(http.StatusInternalServerError, err.Error())
  } else {
   context.Header("Content-Type", "text/xml")
   context.String(http.StatusOK, twimlResult)
  }
 })

 router.Run(":3000")
}

```

## What's next?

Validating requests to your Twilio webhooks is a great first step for securing your Twilio application. We recommend reading over [our full security documentation](/docs/usage/security) for more advice on protecting your app, and the [Anti-Fraud Developer's Guide](/docs/usage/anti-fraud-developer-guide) in particular.
